Example #1
0
  def testExtensionSaveRestore(self):
    # saving and restoring
    SaveName = self.TempPath + os.sep + "SaveRestoreExtensions.FCStd"
    Doc = FreeCAD.newDocument("SaveRestoreExtensions")
    #we try to create a normal python object and add a extension to it 
    obj  = Doc.addObject("App::DocumentObject", "Obj") 
    grp1 = Doc.addObject("App::DocumentObject", "Extension_1")
    grp2 = Doc.addObject("App::FeaturePython", "Extension_2") 
    
    grp1.addExtension("App::GroupExtensionPython", None)
    SaveRestoreSpecialGroup(grp2)
    if FreeCAD.GuiUp:
        SaveRestoreSpecialGroupViewProvider(grp2.ViewObject)
    grp2.Group = [obj]
    
    Doc.saveAs(SaveName)
    FreeCAD.closeDocument("SaveRestoreExtensions")
    Doc = FreeCAD.open(SaveName)
    
    self.failUnless(Doc.Extension_1.hasExtension("App::GroupExtension"))
    self.failUnless(Doc.Extension_2.hasExtension("App::GroupExtension"))
    self.failUnless(Doc.Extension_1.ExtensionProxy is None)
    self.failUnless(Doc.Extension_2.ExtensionProxy is not None)
    self.failUnless(Doc.Extension_2.Group[0] is Doc.Obj)
    self.failUnless(hasattr(Doc.Extension_2.Proxy, 'allowObject'))
    self.failUnless(hasattr(Doc.Extension_2.ExtensionProxy, 'allowObject'))

    if FreeCAD.GuiUp:
      self.failUnless(Doc.Extension_2.ViewObject.hasExtension("Gui::ViewProviderGroupExtensionPython"))
      self.failUnless(hasattr(Doc.Extension_2.ViewObject.Proxy, 'testFunction'))
      self.failUnless(hasattr(Doc.Extension_2.ViewObject.ExtensionProxy, 'testFunction'))

    FreeCAD.closeDocument("SaveRestoreExtensions")
    def Activated(self):
        # So we can open the save-as dialog
        mw = FreeCADGui.getMainWindow()
        cqCodePane = Shared.getActiveCodePane()

        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # Try to keep track of the previous path used to open as a convenience to the user
        if self.previousPath is None:
            self.previousPath = "/home/"

        filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), self.previousPath,
                                                     mw.tr("CadQuery Files (*.py)"))

        self.previousPath = filename[0]

        # Make sure the user didn't click cancel
        if filename[0]:
            # Close the 3D view for the original script if it's open
            try:
                docname = os.path.splitext(os.path.basename(cqCodePane.get_path()))[0]
                FreeCAD.closeDocument(docname)
            except:
                # Assume that there was no 3D view to close
                pass

            # Change the name of our script window's tab
            Shared.setActiveWindowTitle(os.path.basename(filename[0]))

            # Save the file before closing the original and the re-rendering the new one
            ExportCQ.save(filename[0])
            CadQueryExecuteScript().Activated()
Example #3
0
 def _test_file( self, testFile_basename, solution = None ):
     testFile = os.path.join( test_assembly_path, testFile_basename + '.fcstd' )
     debugPrint(1, testFile_basename )
     stats.n_attempted += 1
     #if testFile == 'tests/testAssembly11-Pipe_assembly.fcstd':
     #    print('Skipping known fail')
     #    continue
     doc =  FreeCAD.open(testFile)
     t_start_solver = time.time()
     constraintSystem = solveConstraints( doc, solver_name = 'dof_reduction_solver', use_cache = self.use_cache, showFailureErrorDialog=False )
     if solution:
         self.check_solution( constraintSystem, solution )
     stats.t_solver += time.time() - t_start_solver
     if  self.use_cache:
         debugPrint(1,'\n\n')
         X_org = constraintSystem.variableManager.X
         t_start_cache = time.time()
         #cache.debugMode = 1
         constraintSystem = solveConstraints( doc, solver_name = 'dof_reduction_solver', use_cache =  self.use_cache )
         self.assertTrue(
             numpy.allclose( X_org , constraintSystem.variableManager.X ),
             'Cache solution differs from originial solution: %s != %s' % ( X_org , constraintSystem.variableManager.X )
         )
         #cache.debugMode = 0
         stats.t_cache += time.time() - t_start_cache
         constraintSystem.update()
     stats.n_solved += 1
     FreeCAD.closeDocument( doc.Name )
     debugPrint(1,'\n\n\n')
Example #4
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
	def testIssue3245_2(self):
		self.Doc2 = FreeCAD.newDocument("Issue3245")
		ActiveSketch = self.Doc2.addObject('Sketcher::SketchObject','Sketch')
		ActiveSketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000))
		ActiveSketch.MapMode = "Deactivated"
		geoList = []
		geoList.append(Part.LineSegment(App.Vector(-23.574591,42.399727,0),App.Vector(81.949776,42.399727,0)))
		geoList.append(Part.LineSegment(App.Vector(81.949776,42.399727,0),App.Vector(81.949776,-19.256901,0)))
		geoList.append(Part.LineSegment(App.Vector(81.949776,-19.256901,0),App.Vector(-23.574591,-19.256901,0)))
		geoList.append(Part.LineSegment(App.Vector(-23.574591,-19.256901,0),App.Vector(-23.574591,42.399727,0)))
		ActiveSketch.addGeometry(geoList,False)
		conList = []
		conList.append(Sketcher.Constraint('Coincident',0,2,1,1))
		conList.append(Sketcher.Constraint('Coincident',1,2,2,1))
		conList.append(Sketcher.Constraint('Coincident',2,2,3,1))
		conList.append(Sketcher.Constraint('Coincident',3,2,0,1))
		conList.append(Sketcher.Constraint('Horizontal',0))
		conList.append(Sketcher.Constraint('Horizontal',2))
		conList.append(Sketcher.Constraint('Vertical',1))
		conList.append(Sketcher.Constraint('Vertical',3))
		ActiveSketch.addConstraint(conList)
		ActiveSketch.addConstraint(Sketcher.Constraint('DistanceX',0,1,0,2,105.524367))
		ActiveSketch.setExpression('Constraints[8]', u'10 + 10')
		ActiveSketch.addConstraint(Sketcher.Constraint('DistanceY',3,1,3,2,61.656628))
		ActiveSketch.setDatum(9,App.Units.Quantity('5.000000 mm'))
		ActiveSketch.delConstraint(8)
		values = d = {key: value for (key, value) in self.Doc2.Sketch.ExpressionEngine}
		self.Doc2.recompute()
		self.failUnless(len(values) == 0)
		FreeCAD.closeDocument("Issue3245")
    def Activated(self):
        #So we can open the save-as dialog
        mw = FreeCADGui.getMainWindow()
        cqCodePane = mw.findChild(QtGui.QPlainTextEdit, "cqCodePane")

        #Try to keep track of the previous path used to open as a convenience to the user
        if self.previousPath is None:
            self.previousPath = "/home/"

        filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), self.previousPath,
                                                     mw.tr("CadQuery Files (*.py)"))

        self.previousPath = filename[0]

        #Make sure the user didn't click cancel
        if filename[0]:
            #Close the 3D view for the original script if it's open
            try:
                docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0]
                FreeCAD.closeDocument(docname)
            except:
                #Assume that there was no 3D view to close
                pass

            #Save the file before closing the original and the re-rendering the new one
            ExportCQ.save(filename[0])
            CadQueryExecuteScript().Activated()
	def testIssue3245(self):
		self.Doc2 = FreeCAD.newDocument("Issue3245")
		self.Doc2.addObject('Sketcher::SketchObject','Sketch')
		self.Doc2.Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000))
		self.Doc2.Sketch.MapMode = "Deactivated"
		self.Doc2.Sketch.addGeometry(Part.LineSegment(App.Vector(-1.195999,56.041161,0),App.Vector(60.654316,56.382877,0)),False)
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-2))
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('Horizontal',0))
		self.Doc2.Sketch.addGeometry(Part.LineSegment(App.Vector(0.512583,32.121155,0),App.Vector(60.654316,31.779440,0)),False)
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('Horizontal',1))
		self.Doc2.Sketch.addGeometry(Part.LineSegment(App.Vector(0.170867,13.326859,0),App.Vector(61.679455,13.326859,0)),False)
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('PointOnObject',2,1,-2))
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('Horizontal',2))
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('PointOnObject',1,1,-2))
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('DistanceX',0,1,0,2,60.654316))
		self.Doc2.Sketch.setExpression('Constraints[6]', u'60')
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('DistanceX',1,1,1,2,60.654316))
		self.Doc2.Sketch.setExpression('Constraints[7]', u'65')
		self.Doc2.Sketch.addConstraint(Sketcher.Constraint('DistanceX',2,1,2,2,61.679455))
		self.Doc2.Sketch.setExpression('Constraints[8]', u'70')
		self.Doc2.recompute()
		self.Doc2.Sketch.delGeometry(2)
		values = d = {key: value for (key, value) in self.Doc2.Sketch.ExpressionEngine}
		self.failUnless(values['Constraints[4]'] == u'60')
		self.failUnless(values['Constraints[5]'] == u'65')
		FreeCAD.closeDocument("Issue3245")
Example #8
0
def makeSnapshotWithGui():
	from PyQt4 import QtGui
	import FreeCADGui

	def getMainWindow():
		toplevel = QtGui.qApp.topLevelWidgets()
		for i in toplevel:
			if i.metaObject().className() == "Gui::MainWindow":
				return i
		raise Exception("No main window found")

	mw=getMainWindow()
	mw.hide()
	#mw.showMinimized()

	# Create a test geometry and add it to the document
	obj=Part.makeCone(10,8,10)
	doc = FreeCAD.newDocument()
	Part.show(obj)

	# switch off animation so that the camera is moved to the final position immediately
	view = FreeCADGui.getDocument(doc.Name).activeView()
	view.setAnimationEnabled(False)
	view.viewAxometric()
	view.fitAll()
	view.saveImage('crystal.png',800,600,'Current')
	FreeCAD.closeDocument(doc.Name)
	# close the application
	QtGui.qApp.quit()
Example #9
0
 def testSaveAndRestore(self):
   # saving and restoring
   SaveName = self.TempPath + os.sep + "SaveRestoreTests.FCStd"
   self.Doc.FileName = SaveName
   self.failUnless(self.Doc.Label_1.TypeTransient == 4711)
   self.Doc.Label_1.TypeTransient = 4712
   # setup Linking
   self.Doc.Label_1.Link = self.Doc.Label_2
   self.Doc.Label_2.Link = self.Doc.Label_1
   self.Doc.Label_1.LinkSub = (self.Doc.Label_2,["Sub1","Sub2"])
   self.Doc.Label_2.LinkSub = (self.Doc.Label_1,["Sub3","Sub4"])
   # save the document
   self.Doc.save()
   FreeCAD.closeDocument("SaveRestoreTests")
   self.Doc = FreeCAD.open(SaveName)
   self.failUnless(self.Doc.Label_1.Integer == 4711)
   self.failUnless(self.Doc.Label_2.Integer == 4711)
   # test Linkage
   self.failUnless(self.Doc.Label_1.Link == self.Doc.Label_2)
   self.failUnless(self.Doc.Label_2.Link == self.Doc.Label_1)
   self.failUnless(self.Doc.Label_1.LinkSub == (self.Doc.Label_2,["Sub1","Sub2"]))
   self.failUnless(self.Doc.Label_2.LinkSub == (self.Doc.Label_1,["Sub3","Sub4"]))
   # do  NOT save transient properties
   self.failUnless(self.Doc.Label_1.TypeTransient == 4711)
   self.failUnless(self.Doc == FreeCAD.getDocument(self.Doc.Name))
Example #10
0
def add_part(base,params,doc):
	if isinstance(base,freecad.BaseFunction):
		module = importlib.import_module("BOLTS.freecad.%s.%s" %
			(base.collection,base.module_name))
		module.__dict__[base.name](params,doc)
	elif isinstance(base,freecad.BaseFcstd):
		#copy part to doc
		src_doc = FreeCAD.openDocument(base.path)
		src_obj = src_doc.getObject(base.objectname)
		if src_obj is None:
			raise MalformedBaseError("No object %s found" % base.objectname)
		#maps source name to destination object
		srcdstmap = {}
		dst_obj = copy_part_recursive(src_obj,doc,srcdstmap)

		#set parameters
		for obj_name,proptoparam in base.proptoparam.iteritems():
			for prop,param in proptoparam.iteritems():
				setattr(srcdstmap[obj_name],prop,params[param])

		#finish presentation
		dst_obj.touch()
		doc.recompute()
		FreeCADGui.getDocument(doc.Name).getObject(dst_obj.Name).Visibility = True
		FreeCAD.setActiveDocument(doc.Name)
		FreeCAD.closeDocument(src_doc.Name)
Example #11
0
 def testSaveAndRestore(self):
   # saving and restoring
   SaveName = self.TempPath + os.sep + "UnicodeTest.FCStd"
   self.Doc.FileName = SaveName
   self.Doc.save()
   self.Doc.FileName = ""
   self.Doc = FreeCAD.open(SaveName)
   self.failUnless(self.Doc.Label_1.Label == u"हिन्दी")
   FreeCAD.closeDocument("UnicodeTest")
  def testVectorList(self):
    self.Doc.Test.VectorList = [(-0.05, 2.5, 5.2),(-0.05, 2.5, 5.2)]

    # saving and restoring
    self.Doc.saveAs(self.DocName)
    FreeCAD.closeDocument("PlatformTests")
    self.Doc = FreeCAD.open(self.DocName)

    self.failUnless(len(self.Doc.Test.VectorList) == 2)
Example #13
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.collections:
			makedirs(join(ver_root,coll.id))
			sys.path.append(join(self.repo.path,"freecad",coll.id))
			for cl in coll.classes:
				if not cl.id in self.freecad.getbase:
					continue
				if cl.parameters.common is None:
					continue

				base = self.freecad.getbase[cl.id]

				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
					params["standard"] = cl.name
					name = cl.naming.get_name(params)
					params["name"] = name
					filename = name + ".igs"
					filename = filename.replace(" ","_").replace("/","-")

					doc = FreeCAD.newDocument()

					add_part(base,params,doc)

					shape = None
					if base.type == "function":
						shape = doc.ActiveObject.Shape
					elif base.type == "fcstd":
						shape = doc.getObject(base.objectname).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
 def testDescent(self):
   # testing the up and downstream stuff
   props=self.Obj.supportedProperties()
   for i in props:
       self.Obj.addProperty(i,i)
   tempPath = tempfile.gettempdir()
   tempFile = tempPath + os.sep + "PropertyTests.FCStd"
   self.Doc.saveAs(tempFile)
   FreeCAD.closeDocument("PropertyTests")
   self.Doc = FreeCAD.open(tempFile)
 def testRestore(self):
   Doc = FreeCAD.newDocument("RestoreTests")
   Doc.addObject("App::FeatureTest","Label_1")
   # saving and restoring
   FileName = self.TempPath + os.sep + "Test2.FCStd"
   Doc.saveAs(FileName)
   # restore must first clear the current content
   Doc.restore()
   self.failUnless(len(Doc.Objects) == 1)
   FreeCAD.closeDocument("RestoreTests")
  def testFloatList(self):
    self.Doc.Test.FloatList = [-0.05, 2.5, 5.2]

    # saving and restoring
    self.Doc.saveAs(self.DocName)
    FreeCAD.closeDocument("PlatformTests")
    self.Doc = FreeCAD.open(self.DocName)

    self.failUnless(abs(self.Doc.Test.FloatList[0] + .05) < 0.01)
    self.failUnless(abs(self.Doc.Test.FloatList[1] - 2.5) < 0.01)
    self.failUnless(abs(self.Doc.Test.FloatList[2] - 5.2) < 0.01)
Example #17
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 #18
0
def setup(part,view):
    date = datetime.date.today().strftime("%m_%d_%Y")
    printerDir = gv.printerDir+"Printer_"+date+"/"
    #part: "printBedSupport"
    #subpart: App.ActiveDocument.Pocket001
    
    FreeCAD.open(printerDir+"Parts/"+part+".FCStd")
    App.setActiveDocument(part)
    view = eval('App.ActiveDocument.'+view)
    create(view)
    App.getDocument(part).save()
    App.closeDocument(part)
  def testPoints(self):
    try:
      self.Doc.addObject("Points::Feature", "Points")

      # saving and restoring
      self.Doc.saveAs(self.DocName)
      FreeCAD.closeDocument("PlatformTests")
      self.Doc = FreeCAD.open(self.DocName)

      self.failUnless(self.Doc.Points.Points.count() == 0)
    except:
      pass
Example #20
0
	def write_output(self,out_path,template):

		revision = int(FreeCAD.Version()[2].split()[0])
		if revision < 3481:
			raise RuntimeError("FreeCAD version too old")

		importWebGL.template = template

		self.clear_output_dir(out_path)

		#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.collections:
			#TODO: handle collision with python standard library properly
			if coll.id == "pipes":
				continue
			makedirs(join(out_path,coll.id))
			sys.path.append(join(self.repo.path,"freecad",coll.id))
			for cl in coll.classes_by_ids():
				if not cl.id in self.freecad.getbase:
					continue

				base = self.freecad.getbase[cl.id]

				try:
					parameters = cl.parameters.union(base.parameters)
					params = parameters.collect(parameters.defaults)
				except:
					print "A problem occured when parameters for %s where collected for %s" % \
						(cl.parameters.defaults,cl.id)
					raise
				params["standard"] = cl.name
				params["name"] = "irrelevant"
				filename = cl.id + ".js"

				doc = FreeCAD.newDocument()
				add_part(base,params,doc)

				#find bounding box
				part = FreeCAD.ActiveDocument.ActiveObject
				bb = part.Shape.BoundBox
				importWebGL.cameraPosition = (2*bb.XMax, 2*bb.YMax, 2*bb.ZMax)
				importWebGL.wireframeStyle = "multimaterial"
				importWebGL.export([part], join(out_path,coll.id,filename))
				FreeCAD.closeDocument(doc.Name)

			sys.path.pop()

		#restore byte code writing
		sys.dont_write_bytecode = write_bytecode
 def testActiveDocument(self):
   # open 2nd doc
   Second = FreeCAD.newDocument("Active")
   FreeCAD.closeDocument("Active")
   try:
       # There might be no active document anymore
       # This also checks for dangling pointers
       Active = FreeCAD.activeDocument()
       # Second is still a valid object
       self.failUnless(Second != Active)
   except:
       # Okay, no document open
       self.failUnless(True)
Example #22
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()
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 DVAnnoSymImageTest():
    path = os.path.dirname(os.path.abspath(__file__))
    print ('TDTestAnno path: ' + path)
    templateFileSpec = path + '/TestTemplate.svg'
    symbolFileSpec = path + '/TestSymbol.svg'
    imageFileSpec = path + '/TestImage.png'

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

    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.ViewObject.show()    # unit tests run in console mode

    #annotation
    anno = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewAnnotation','TestAnno')
    s = 'Different Text'
    sl = list()
    sl.append(s)
    anno.Text = sl
    anno.TextStyle = 'Bold'
    rc = page.addView(anno)
    anno.X = 30.0
    anno.Y = 150.0

    #symbol
    sym = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewSymbol','TestSymbol')
    f = open(symbolFileSpec, 'r')
    svg = f.read()
    f.close()
    sym.Symbol = svg
    rc = page.addView(sym)
    sym.X = 220.0
    sym.Y = 150.0

    #image
    img = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewImage','TestImage')
    img.ImageFile = imageFileSpec
    rc = page.addView(img)

    FreeCAD.ActiveDocument.recompute()
    rc = False
    if ("Up-to-date" in anno.State) and ("Up-to-date" in sym.State) and ("Up-to-date" in img.State):
        rc = True
    FreeCAD.closeDocument("TDAnno")
    return rc
Example #25
0
def clearDocument():
    '''
    remove all objects from view
    '''
    
    print '###########################\n######### clearing document ####'
    import DDADatabase
    DDADatabase.enableOperationObverser(False)

    label = FreeCAD.ActiveDocument.Label
    FreeCAD.closeDocument(label)
    FreeCAD.newDocument(label)
    print '##############################'
    FreeCADGui.runCommand('DDA_ResetCamera')
    DDADatabase.enableOperationObverser(True)
Example #26
0
def ConvertToStepAndStl(path,name,tess=0.0):
	input = path + "/Parts/PrintedParts/" + name + ".FCStd"
	stl = path + "/stl/" + name + ".stl"
	step = path + "/step/" + name + ".step"
	doc = FreeCAD.openDocument(input);
	s = doc.ActiveObject.Shape
	s.exportStep(step)
	print("tess = " + str(tess))
	if tess == 0.0:
		s.exportStl(stl)
	else:
		m=Mesh.Mesh()
		m.addFacets(s.tessellate(tess))
		m.write(stl)
	FreeCAD.closeDocument(doc.Name)
  def testColorList(self):
    self.Doc.Test.ColourList = [(1.0,0.5,0.0),(0.0,0.5,1.0)]

    # saving and restoring
    self.Doc.saveAs(self.DocName)
    FreeCAD.closeDocument("PlatformTests")
    self.Doc = FreeCAD.open(self.DocName)

    self.failUnless(abs(self.Doc.Test.ColourList[0][0] - 1.0) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[0][1] - 0.5) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[0][2] - 0.0) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[0][3] - 0.0) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[1][0] - 0.0) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[1][1] - 0.5) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[1][2] - 1.0) < 0.01)
    self.failUnless(abs(self.Doc.Test.ColourList[1][3] - 0.0) < 0.01)
Example #28
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)

		#extrude crossBarTop
		uf.extrudeFrameMember(self.name, gv.frameSpacerLength)
Example #29
0
    def draw(self):

        self.defineVariables()
        # import FreeCAD modules
        import FreeCAD as App
        import Part
        import Sketcher

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

        # make document
        App.newDocument("xRodBottom")
        App.setActiveDocument("xRodBottom")
        App.ActiveDocument = App.getDocument("xRodBottom")

        # 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.Circle(App.Vector(50, 50, 0), App.Vector(0, 0, 1), self.Diameter / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident', 0, 3, -1, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Radius', 0, self.Diameter / 2))
        App.ActiveDocument.recompute()
        App.getDocument('xRodBottom').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()
        App.ActiveDocument.Pad.Length = self.Length_of_Shorter_X_Rod
        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()
Example #30
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        mw = FreeCADGui.getMainWindow()
        cqCodePane = mw.findChild(QtGui.QPlainTextEdit, "cqCodePane")

        # If there's nothing open in the code pane, we don't need to close it
        if len(cqCodePane.file.path) == 0:
            return

        # Check to see if we need to save the script
        if cqCodePane.dirty:
            reply = QtGui.QMessageBox.question(
                cqCodePane,
                "Save CadQuery Script",
                "Save script before closing?",
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
            )

            if reply == QtGui.QMessageBox.Cancel:
                return

            if reply == QtGui.QMessageBox.Yes:
                # If we've got a file name already save it there, otherwise give a save-as dialog
                if len(cqCodePane.file.path) == 0:
                    filename = QtGui.QFileDialog.getSaveFileName(
                        mw, mw.tr("Save CadQuery Script As"), "/home/", mw.tr("CadQuery Files (*.py)")
                    )
                else:
                    filename = cqCodePane.file.path

                # Make sure we got a valid file name
                if filename is not None:
                    ExportCQ.save(filename)

        # Close the matching 3D view if it's open
        if cqCodePane.file.path is not None:
            docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0]

            try:
                FreeCAD.closeDocument(docname)
            except:
                # Assume that the document has already been closed
                pass

        # Clear our script and whatever was rendered by it out
        cqCodePane.file.close()
Example #31
0
 def tearDown(self):
     FreeCAD.closeDocument("FemTest")
     pass
Example #32
0
 def testBlockConstraintEllipse(self):
     self.Doc3 = FreeCAD.newDocument("BlockConstraintTests")
     ActiveSketch = self.Doc3.addObject('Sketcher::SketchObject', 'Sketch')
     ActiveSketch.Placement = App.Placement(
         App.Vector(0.000000, 0.000000, 0.000000),
         App.Rotation(0.000000, 0.000000, 0.000000, 1.000000))
     ActiveSketch.MapMode = "Deactivated"
     ActiveSketch.addGeometry(
         Part.Ellipse(App.Vector(-19.129438, 14.345055, 0),
                      App.Vector(-33.806261, 12.085921, 0),
                      App.Vector(-30.689360, 7.107538, 0)), False)
     ActiveSketch.solve()
     ActiveSketch.exposeInternalGeometry(0)
     ActiveSketch.solve()
     ActiveSketch.movePoint(0, 0, App.Vector(-26.266434, 14.345055, 0), 0)
     ActiveSketch.solve()
     ActiveSketch.addConstraint(Sketcher.Constraint(
         'Block', 0))  # Block the Ellipse in place
     ActiveSketch.addConstraint(Sketcher.Constraint(
         'Block', 1))  # Block the major axis in place (on purpose)
     status = ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     ActiveSketch.addConstraint(
         Sketcher.Constraint('Distance', 1,
                             27.277350))  # Length of major axis
     ActiveSketch.setDriving(
         6, True
     )  # ensure length is driving (because pre-existing block constraint on major axis)
     ActiveSketch.setDatum(6, App.Units.Quantity('28.000000 mm'))
     status = ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     ActiveSketch.addConstraint(
         Sketcher.Constraint('Distance', 2,
                             11.747233))  # Length of minor axis
     ActiveSketch.setDatum(7, App.Units.Quantity('15.000000 mm'))
     ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     ActiveSketch.addConstraint(Sketcher.Constraint('Block', 2))
     ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     ActiveSketch.addConstraint(
         Sketcher.Constraint('Horizontal', 1)
     )  # Make major axis horizontal (together with horizontal and length driving constraints)
     ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     ActiveSketch.addConstraint(
         Sketcher.Constraint('DistanceX', 0, 3, -1, 1,
                             27.655024))  # Locate Ellipse center
     ActiveSketch.addConstraint(
         Sketcher.Constraint('DistanceY', 0, 3, -1, 1, -20.877021))
     ActiveSketch.setDatum(10, App.Units.Quantity('25.000000 mm'))
     ActiveSketch.setDatum(11, App.Units.Quantity('-20.000000 mm'))
     ActiveSketch.solve()
     self.failUnless(
         status == 0)  # no redundants/conflicts/convergence issues
     FreeCAD.closeDocument(self.Doc3.Name)
Example #33
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("SketchSolverTest")
Example #34
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)

		#Revolve tip of nozzle
		#Sketch Points
		p1x = gv.nozzleDia/2
		p1y = 0
		p2x = gv.nozzleTipDia/2
		p2y = p1y
		p3x = gv.nozzleBaseDia/2
		p3y = (gv.nozzleBaseDia/2-gv.nozzleTipDia/2)
		p4x = p3x
		p4y = gv.nozzleLength
		p5x = gv.extruderBarrelLinerDia/2
		p5y = p4y
		p6x = p5x
		p6y = p3y
		p7x = gv.nozzleStepDia/2
		p7y = p6y-(p6x-p7x)/math.tan(math.pi/180*gv.nozzleDrillAngle/2)
		p8x = p7x
		p8y = gv.nozzleStepOffset+(p7x-p1x)/math.tan(math.pi/180*gv.nozzleDrillAngle/2)
		p9x = gv.nozzleDia/2
		p9y = gv.nozzleStepOffset
		
		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch')
		App.activeDocument().Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(-0.707107,0.000000,0.000000,-0.707107))
		App.ActiveDocument.Sketch.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p2x,p2y,0)))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('PointOnObject',0,2,-1)) 
		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.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(p7x,p7y,0)))
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',4,2,5,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addGeometry(Part.Line(App.Vector(p7x,p7y,0),App.Vector(p8x,p8y,0)))
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',5,2,6,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addGeometry(Part.Line(App.Vector(p8x,p8y,0),App.Vector(p9x,p9y,0)))
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',6,2,7,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addGeometry(Part.Line(App.Vector(p9x,p9y,0),App.Vector(p1x,p1y,0)))
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',7,2,8,1)) 
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',8,2,0,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Vertical',8)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Vertical',6))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addGeometry(Part.Line(App.Vector(p3x,p3y,0),App.Vector(p6x,p6y,0)))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',9,1,1,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',9,2,4,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.toggleConstruction(9) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Horizontal',9)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		
		#Add dimensions
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceY',-1,1,3,2,gv.nozzleLength)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceX',-1,1,0,1,gv.nozzleDia/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceX',-1,1,1,2,gv.nozzleBaseDia/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceX',-1,1,5,2,gv.nozzleStepDia/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceY',8,-1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Angle',4,2,5,1,math.pi/180*(180-.5*gv.nozzleDrillAngle))) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Angle',6,2,7,1,math.pi/180*(180-.5*gv.nozzleDrillAngle))) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceX',-1,1,0,2,gv.nozzleTipDia/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Angle',2,1,1,2,3*math.pi/4)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('DistanceX',-1,1,3,2,gv.extruderBarrelLinerDia/2)) 
		App.ActiveDocument.recompute()
		App.getDocument(self.name).recompute()
		
		#Revolve Sketch
		App.activeDocument().addObject("PartDesign::Revolution","Revolution")
		App.activeDocument().Revolution.Sketch = App.activeDocument().Sketch
		App.activeDocument().Revolution.ReferenceAxis = (App.activeDocument().Sketch,['V_Axis'])
		App.activeDocument().Revolution.Angle = 360.0
		App.activeDocument().Revolution.Reversed = 1
		App.ActiveDocument.recompute()
		App.ActiveDocument.Revolution.Angle = 360.000000
		App.ActiveDocument.Revolution.ReferenceAxis = (App.ActiveDocument.Sketch,['V_Axis'])
		App.ActiveDocument.Revolution.Midplane = 0
		App.ActiveDocument.Revolution.Reversed = 1
		App.ActiveDocument.recompute()

		#make heater block
		#Sketch Points
		p1x = -gv.nozzleBodyDepth/2
		p1y = -gv.nozzleBodyDepth/2
		p2x = p1x
		p2y = -p1y
		p3x = gv.nozzleBodyWidth-gv.nozzleBodyDepth/2
		p3y = -p1y
		p4x = p3x
		p4y = p1y

		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch001')
		#App.activeDocument().Sketch001.Support = (App.ActiveDocument.Revolution,["Face4"])
		App.activeDocument().Sketch001.Support = uf.getFace(App.ActiveDocument.Revolution,
															None,None,
															None,None, 
															gv.nozzleLength,0)
		App.activeDocument().recompute()
#		App.ActiveDocument.Sketch001.addExternal("Revolution","Edge7")

		App.ActiveDocument.Sketch001.addExternal("Revolution",uf.getEdge(App.ActiveDocument.Revolution,
															None,None,
															None,None, 
															gv.nozzleLength,0,
															radius = gv.extruderBarrelLinerDia/2))
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p4x,p4y,0)))
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p4x,p4y,0),App.Vector(p3x,p3y,0)))
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p3x,p3y,0),App.Vector(p2x,p2y,0)))
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p2x,p2y,0),App.Vector(p1x,p1y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',0,2,1,1)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',1,2,2,1)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',3,2,0,1)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Horizontal',0)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Horizontal',2)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',1)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Symmetric',2,2,0,1,-1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p1x,0,0),App.Vector(0,0,0)))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('PointOnObject',4,1,3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',4,2,-1,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Horizontal',4)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(0,0,0),App.Vector(0,p1y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',4,2,5,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('PointOnObject',5,2,0)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',5)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.toggleConstruction(5) 
		App.ActiveDocument.Sketch001.toggleConstruction(4) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',5,4)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(0,0,0),App.Vector(0,0,1),gv.extruderBarrelLinerDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',6,3,-1,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',6,-3)) 
		App.ActiveDocument.recompute()
		
		#Add dimensions
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceX',0,gv.nozzleBodyWidth)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceY',1,gv.nozzleBodyDepth)) 
		App.ActiveDocument.recompute()
#		App.getDocument(self.name).recompute()
		
		#Extrude Block
		App.activeDocument().addObject("PartDesign::Pad","Pad")
		App.activeDocument().Pad.Sketch = App.activeDocument().Sketch001
		App.ActiveDocument.Pad.Reversed = 1
		App.ActiveDocument.Pad.Length = gv.nozzleBodyHeight
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()

		#Refine Shape
		App.ActiveDocument.addObject('Part::Feature','Pad').Shape=App.ActiveDocument.Pad.Shape.removeSplitter()
		App.ActiveDocument.ActiveObject.Label=App.ActiveDocument.Pad.Label
		App.ActiveDocument.recompute()

		#Make Resistor Hole
		#Sketch Points
		p1x = -gv.nozzleBodyWidth+gv.nozzleBodyDepth/2
		p1y = gv.nozzleLength-gv.nozzleBodyHeight/2
		p2x = p1x + gv.nozzleResistorInset
		p2y = -p1y

		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch002')
		App.activeDocument().Sketch002.Support = uf.getFace(App.ActiveDocument.Pad001,
															None, None,
															-gv.nozzleBodyDepth/2,0, 
															None, None)
		App.activeDocument().recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addExternal("Pad001",uf.getEdge(App.ActiveDocument.Pad001,
															-gv.nozzleBodyWidth+gv.nozzleBodyDepth/2, 0,
															-gv.nozzleBodyDepth/2,0, 
															None, None))
		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('Horizontal',0)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addConstraint(Sketcher.Constraint('Symmetric',-3,2,-3,1,0,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.toggleConstruction(0) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addGeometry(Part.Circle(App.Vector(p2x,p2y,0),App.Vector(0,0,1),gv.nozzleResistorDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addConstraint(Sketcher.Constraint('Coincident',1,3,0,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addConstraint(Sketcher.Constraint('DistanceX',0,gv.nozzleResistorInset)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch002.addConstraint(Sketcher.Constraint('Radius',1,gv.nozzleResistorDia/2)) 
		App.ActiveDocument.recompute()
		App.getDocument(self.name).recompute()
		
		#Cut resistor hole through all
		App.activeDocument().addObject("PartDesign::Pocket","Pocket")
		App.activeDocument().Pocket.Sketch = App.activeDocument().Sketch002
		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 hole for thermistor
		#Sketch Points
		p1x = 0
		p1y = gv.nozzleLength - gv.nozzleBodyHeight
		p2x = p1x
		p2y = gv.nozzleLength - gv.nozzleBodyHeight + gv.nozzleThermistorHoleVertOffset
		
		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch003')
		#App.activeDocument().Sketch003.Support = (App.ActiveDocument.Pocket,["Face10"])
		App.activeDocument().Sketch003.Support = uf.getFace(App.ActiveDocument.Pocket,
															gv.nozzleBodyDepth/2, 0,
															None, None, 
															None, None)
		App.activeDocument().recompute()
		App.ActiveDocument.Sketch003.addExternal("Pocket",uf.getEdge(App.ActiveDocument.Pocket,
															gv.nozzleBodyDepth/2,0,
															0, 0,	 
															gv.nozzleLength-gv.nozzleBodyHeight,0))
		App.ActiveDocument.Sketch003.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p2x,p2y,0)))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('PointOnObject',0,2,-2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-2)) 
		App.ActiveDocument.Sketch003.addGeometry(Part.Circle(App.Vector(p2x,p2y,0),App.Vector(0,0,1),gv.nozzleThermistorDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('Coincident',1,3,0,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.toggleConstruction(0) 
		App.ActiveDocument.recompute()
		
		#Add dimensions
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('DistanceY',0,gv.nozzleThermistorHoleVertOffset)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch003.addConstraint(Sketcher.Constraint('Radius',1,gv.nozzleThermistorDia/2)) 
		App.ActiveDocument.recompute()
		App.getDocument(self.name).recompute()
		
		#Cut hole
		App.activeDocument().addObject("PartDesign::Pocket","Pocket001")
		App.activeDocument().Pocket001.Sketch = App.activeDocument().Sketch003
		App.activeDocument().Pocket001.Length = 5.0
		App.ActiveDocument.recompute()
		App.ActiveDocument.Pocket001.Length = gv.nozzleThermistorDepth
		App.ActiveDocument.Pocket001.Type = 0
		App.ActiveDocument.Pocket001.UpToFace = None
		App.ActiveDocument.recompute()

		#Make Thermistor retainer hole
		#Sketch Points
		p1x = -gv.nozzleBodyWidth/2
		p1y = gv.nozzleLength - gv.nozzleBodyHeight/2
		p2x = -gv.nozzleBodyWidth/2 + gv.nozzleThermistorRetainerHorizOffset
		p2y = gv.nozzleLength - gv.nozzleBodyHeight/2
		
		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch004')
		App.activeDocument().Sketch004.Support = uf.getFace(App.ActiveDocument.Pocket001,
															gv.nozzleBodyDepth/2, 0,
															None, None, 
															None, None)
		App.activeDocument().recompute()
		App.ActiveDocument.Sketch004.addExternal("Pocket001",uf.getEdge(App.ActiveDocument.Pocket001,
															gv.nozzleBodyDepth/2,0,
															-gv.nozzleBodyDepth/2,0,	 
															None, None))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p2x,p2y,0)))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('Horizontal',0)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('Symmetric',-3,2,-3,1,0,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.toggleConstruction(0) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addGeometry(Part.Circle(App.Vector(p2x,p2y,0),App.Vector(0,0,1),gv.nozzleThermistorRetainerDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('Coincident',1,3,0,2)) 
		App.ActiveDocument.recompute()
		
		#Add dimensions
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('DistanceX',0,gv.nozzleThermistorRetainerHorizOffset)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch004.addConstraint(Sketcher.Constraint('Radius',1,gv.nozzleThermistorRetainerDia/2)) 
		App.ActiveDocument.recompute()
		App.getDocument(self.name).recompute()
		
		#Cut Hole
		App.activeDocument().addObject("PartDesign::Pocket","Pocket002")
		App.activeDocument().Pocket002.Sketch = App.activeDocument().Sketch004
		App.activeDocument().Pocket002.Length = 5.0
		App.ActiveDocument.recompute()
		App.ActiveDocument.Pocket002.Length = gv.nozzleThermistorRetainerDepth
		App.ActiveDocument.Pocket002.Type = 0
		App.ActiveDocument.Pocket002.UpToFace = None
		App.ActiveDocument.recompute()
Example #35
0
def importPart(filename, partName=None, doc_assembly=None):
    if doc_assembly == None:
        doc_assembly = FreeCAD.ActiveDocument
    updateExistingPart = partName != None
    if updateExistingPart:
        FreeCAD.Console.PrintMessage("updating part %s from %s\n" %
                                     (partName, filename))
    else:
        FreeCAD.Console.PrintMessage("importing part from %s\n" % filename)
    doc_already_open = filename in [
        d.FileName for d in FreeCAD.listDocuments().values()
    ]
    debugPrint(4, "%s open already %s" % (filename, doc_already_open))
    if doc_already_open:
        doc = [
            d for d in FreeCAD.listDocuments().values()
            if d.FileName == filename
        ][0]
    else:
        if filename.lower().endswith('.fcstd'):
            debugPrint(4, '  opening %s' % filename)
            doc = FreeCAD.openDocument(filename)
            debugPrint(4, '  succesfully opened %s' % filename)
        else:  #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = FreeCAD.newDocument(os.path.basename(filename))
            shapeobj = ImportGui.insert(filename, doc.Name)

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

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

    if updateExistingPart:
        obj = doc_assembly.getObject(partName)
        prevPlacement = obj.Placement
        if not hasattr(obj, 'updateColors'):
            obj.addProperty("App::PropertyBool", "updateColors",
                            "importPart").updateColors = True
        importUpdateConstraintSubobjects(doc_assembly, obj, obj_to_copy)
    else:
        partName = findUnusedObjectName(doc.Label + '_', document=doc_assembly)
        try:
            obj = doc_assembly.addObject("Part::FeaturePython", partName)
        except UnicodeEncodeError:
            safeName = findUnusedObjectName('import_', document=doc_assembly)
            obj = doc_assembly.addObject("Part::FeaturePython", safeName)
            obj.Label = findUnusedLabel(doc.Label + '_', document=doc_assembly)
        obj.addProperty("App::PropertyFile", "sourceFile",
                        "importPart").sourceFile = filename
        obj.addProperty("App::PropertyFloat", "timeLastImport", "importPart")
        obj.setEditorMode("timeLastImport", 1)
        obj.addProperty("App::PropertyBool", "fixedPosition", "importPart")
        obj.fixedPosition = not any([
            i.fixedPosition
            for i in doc_assembly.Objects if hasattr(i, 'fixedPosition')
        ])
        obj.addProperty("App::PropertyBool", "updateColors",
                        "importPart").updateColors = True
    obj.Shape = obj_to_copy.Shape.copy()
    if updateExistingPart:
        obj.Placement = prevPlacement
    else:
        for p in obj_to_copy.ViewObject.PropertiesList:  #assuming that the user may change the appearance of parts differently depending on the assembly.
            if hasattr(obj.ViewObject, p) and p not in ['DiffuseColor']:
                setattr(obj.ViewObject, p, getattr(obj_to_copy.ViewObject, p))
        obj.ViewObject.Proxy = ImportedPartViewProviderProxy()
    if getattr(obj, 'updateColors', True):
        obj.ViewObject.DiffuseColor = copy.copy(
            obj_to_copy.ViewObject.DiffuseColor)
        #obj.ViewObject.Transparency = copy.copy( obj_to_copy.ViewObject.Transparency )   # .Transparency property
        tsp = copy.copy(obj_to_copy.ViewObject.Transparency
                        )  #  .Transparency workaround for FC 0.17 @ Nov 2016
        if tsp < 100 and tsp != 0:
            obj.ViewObject.Transparency = tsp + 1
        if tsp == 100:
            obj.ViewObject.Transparency = tsp - 1
        obj.ViewObject.Transparency = tsp  # .Transparency workaround end
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime(filename)
    #clean up
    if subAssemblyImport:
        doc_assembly.removeObject(tempPartName)
    if not doc_already_open:  #then close again
        FreeCAD.closeDocument(doc.Name)
        FreeCAD.setActiveDocument(doc_assembly.Name)
        FreeCAD.ActiveDocument = doc_assembly
    return obj
Example #36
0
 def tearDown(self):
     FreeCAD.closeDocument("boxtest")
Example #37
0
def build_3d_geometry(
    input_parts: List[Geo3DPart],
    input_file: Optional[str] = None,
    xsec_dict: Dict[str, Dict] = None,
    serialized_input_file: Optional[bytes] = None,
    params: Optional[Dict] = None,
    lunit: Optional[str] = None,
) -> Geo3DData:
    """Build a geometry in 3D.

    Parameters
    ----------
    input_parts : list
        Ordered list of input parts, leftmost items get built first
    input_file : str
        Path to FreeCAD template file. Either this or serialized_input_file
        must be set (but not both).
        (Default value = None)
    xsec_dict : dict
        Dictionary of cross-section specifications. It should be of the
        form {'xsec_name':{'axis':(1,0,0),'distance':0.}}, where the axis parameter is a tuple
        defining the axis that defines the normal of the cross section, and distance is
        the length along the axis used to set the cross section.
        (Default value = None)
    serialized_input_file : bytes
        FreeCAD template file that has been serialized using
        qmt.infrastructure.serialize_file. This is useful for passing a
        file into a docker container or other environment that
        doesn't have access to a shared drive. Either this or
        input_file must be set (but not both).
        (Default value = None)
    params : dict
        Dictionary of parameters to use in FreeCAD.
        (Default value = None)
    Returns
    -------
    Geo3DData instance

    """
    from qmt.geometry.freecad.objectConstruction import build

    if input_file is None and serialized_input_file is None:
        raise ValueError(
            "One of input_file or serialized_input_file must be non-none.")
    elif input_file is not None and serialized_input_file is not None:
        raise ValueError(
            "Both input_file and serialized_input_file were non-none.")
    elif input_file is not None:
        serial_fcdoc = serialize_file(input_file)
    else:
        serial_fcdoc = serialized_input_file
    if params is None:
        params = {}
    if xsec_dict is None:
        xsec_dict = {}
    options_dict = {}
    options_dict["serial_fcdoc"] = serial_fcdoc
    options_dict["input_parts"] = input_parts
    options_dict["params"] = params
    options_dict["xsec_dict"] = xsec_dict
    options_dict["lunit"] = lunit

    data = Geo3DData(lunit)
    data.serial_fcdoc = serial_fcdoc
    data.get_data("fcdoc")

    try:
        built = build(options_dict)
    except Exception:
        FreeCAD.closeDocument("instance")
        raise
    FreeCAD.closeDocument("instance")
    return built
Example #38
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("PlatformTests")
Example #39
0
 def tearDown(self):
     # closing doc
     FreeCAD.closeDocument("UndoTest")
Example #40
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("RecomputeTests")
Example #41
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("SaveRestoreTests")
App.ActiveDocument.recompute()
#Gui.SendMsgToActiveView("ViewFit")

App.ActiveDocument.addObject("Part::Cylinder", "Cylinder")
App.ActiveDocument.ActiveObject.Label = "Cylinder"
App.ActiveDocument.recompute()
#Gui.SendMsgToActiveView("ViewFit")

# can not import this module, if this script is not called from FreeCAD
import BOPTools.SplitFeatures
j = BOPTools.SplitFeatures.makeBooleanFragments(name='BooleanFragments')
j.Objects = [App.ActiveDocument.Box, App.ActiveDocument.Cylinder]
j.Mode = 'Standard'
j.Proxy.execute(j)
j.purgeTouched()

__objs__ = []
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("BooleanFragments"))
import Part
Part.export(__objs__, u"./a.brep")

del __objs__

print('this script complete sucessfully')
######################### end of paste ##############################
'''
# exit FreeCAD, only after you have done the debugging
FreeCAD.closeDocument('Unnamed')
if FreeCAD.GuiUp:
    Gui.doCommand('exit(0)')  # another way to exit
'''
Example #43
0
 def tearDown(self):
     # tearDown is executed after every test
     FreeCAD.closeDocument(self.document.Name)
Example #44
0
    def loadTemplate(self):
        """loads the contents of a template into the current file"""

        import FreeCADGui
        from PySide import QtCore, QtGui
        filename = QtGui.QFileDialog.getOpenFileName(
            QtGui.QApplication.activeWindow(),
            translate("BIM", "Open template file"), None,
            "FreeCAD file (*.FCStd)")
        if filename:
            filename = filename[0]
            if FreeCAD.ActiveDocument:
                d = FreeCAD.ActiveDocument
                td = FreeCAD.openDocument(filename, True)  #hidden
                tname = td.Name
                values = td.Meta
                FreeCAD.closeDocument(tname)
                d.mergeProject(filename)
                FreeCADGui.ActiveDocument = FreeCADGui.getDocument(
                    d.Name)  # fix b/c hidden doc
            else:
                d = FreeCAD.openDocument(filename)
                FreeCAD.ActiveDocument = d
                values = d.Meta
            bimunit = 0
            if hasattr(FreeCAD, "DraftWorkingPlane"):
                from FreeCAD import Vector
                if "wppos" in values:
                    FreeCAD.DraftWorkingPlane.position = eval(
                        values["wpposition"])
                if "wpu" in values:
                    FreeCAD.DraftWorkingPlane.u = eval(values["wpu"])
                if "wpv" in values:
                    FreeCAD.DraftWorkingPlane.v = eval(values["wpv"])
                if "wpaxis" in values:
                    FreeCAD.DraftWorkingPlane.axis = eval(values["wpaxis"])
            if "unit" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Units").SetInt(
                        "UserSchema", int(values["unit"]))
                if hasattr(FreeCAD.Units, "setSchema"):
                    FreeCAD.Units.setSchema(int(values["unit"]))
                    bimunit = [0, 2, 3, 3, 1, 5, 0, 4][int(values["unit"])]
            if "textsize" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "textheight", float(values["textsize"]))
                if hasattr(FreeCADGui, "draftToolBar"):
                    FreeCADGui.draftToolBar.fontsizeButton.setValue(
                        float(values["textsize"]))
            if "textfont" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetString(
                        "textfont", values["textfont"])
            if "dimstyle" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetInt(
                        "dimsymbol", int(values["dimstyle"]))
            if "arrowsize" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "arrowsize", float(values["arrowsize"]))
            if "decimals" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Units").SetInt(
                        "Decimals", int(values["decimals"]))
            if "grid" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "gridSpacing", float(values["grid"]))
            if "squares" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetInt(
                        "gridEvery", int(values["squares"]))
            if hasattr(FreeCADGui, "Snapper"):
                FreeCADGui.Snapper.setGrid()
            if "linewidth" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetInt(
                        "DefautShapeLineWidth", int(values["linewidth"]))
                if hasattr(FreeCADGui, "draftToolBar"):
                    FreeCADGui.draftToolBar.widthButton.setValue(
                        int(values["linewidth"]))
            if "colFace" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetUnsigned(
                        "DefaultShapeColor", int(values["colFace"]))
            if "colLine" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetUnsigned(
                        "DefaultShapeLineColor", int(values["colLine"]))
            if "colHelp" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Arch").SetUnsigned(
                        "ColorHelpers", int(values["colHelp"]))
            if "colConst" in values:
                FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft"
                                 ).SetUnsigned("constructioncolor",
                                               int(values["colConst"]))

            # set the status bar widgets
            mw = FreeCADGui.getMainWindow()
            if mw:
                st = mw.statusBar()
                statuswidget = st.findChild(QtGui.QToolBar, "BIMStatusWidget")
                if statuswidget:
                    statuswidget.unitLabel.setText(
                        statuswidget.unitsList[bimunit])
                    # change the unit of the nudge button
                    nudgeactions = statuswidget.nudge.menu().actions()
                    if bimunit in [2, 3, 5, 7]:
                        nudgelabels = statuswidget.nudgeLabelsI
                    else:
                        nudgelabels = statuswidget.nudgeLabelsM
                    for i in range(len(nudgelabels)):
                        nudgeactions[i].setText(nudgelabels[i])
                    if not "auto" in statuswidget.nudge.text().replace(
                            "&", "").lower():
                        statuswidget.nudge.setText(
                            FreeCAD.Units.Quantity(
                                statuswidget.nudge.text().replace(
                                    "&", "")).UserString)

            FreeCAD.Console.PrintMessage(
                translate(
                    "BIM",
                    "Template successfully loaded into current document") +
                "\n")
            self.reject()
Example #45
0
    def testApplyFiles(self):
        self.Doc.openTransaction("Transaction0")
        self.L1 = self.Doc.addObject("App::DocumentObjectFileIncluded",
                                     "FileObject1")
        self.failUnless(self.L1.File == "")
        self.Filename = self.L1.File

        self.Doc.openTransaction("Transaction1")
        self.TempPath = tempfile.gettempdir()
        # creating a file in the Transient directory of the document
        file = open(self.Doc.getTempFileName("test"), "w")
        file.write("test No1")
        file.close()
        # applying the file
        self.L1.File = (file.name, "Test.txt")
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        # read again
        file = open(self.L1.File, "r")
        self.failUnless(file.read() == "test No1")
        file.close()
        file = open(self.TempPath + "/testNest.txt", "w")
        file.write("test No2")
        file.close()
        # applying the file
        self.Doc.openTransaction("Transaction2")
        self.L1.File = file.name
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        # read again
        file = open(self.L1.File, "r")
        self.failUnless(file.read() == "test No2")
        file.close()
        self.Doc.undo()
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        # read again
        file = open(self.L1.File, "r")
        self.failUnless(file.read() == "test No1")
        file.close()
        self.Doc.undo()
        # read again
        self.failUnless(self.L1.File == "")
        self.Doc.redo()
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        # read again
        file = open(self.L1.File, "r")
        self.failUnless(file.read() == "test No1")
        file.close()
        self.Doc.redo()
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        # read again
        file = open(self.L1.File, "r")
        self.failUnless(file.read() == "test No2")
        file.close()
        # Save restore test
        FileName = self.TempPath + "/FileIncludeTests.fcstd"
        self.Doc.saveAs(FileName)
        FreeCAD.closeDocument("FileIncludeTests")
        self.Doc = FreeCAD.open(self.TempPath + "/FileIncludeTests.fcstd")
        # check if the file is still there
        self.L1 = self.Doc.getObject("FileObject1")
        file = open(self.L1.File, "r")
        res = file.read()
        FreeCAD.Console.PrintLog(res + "\n")
        self.failUnless(res == "test No2")
        self.failUnless(self.L1.File.split("/")[-1] == "Test.txt")
        file.close()

        # test for bug #94 (File overlap in PropertyFileIncluded)
        L2 = self.Doc.addObject("App::DocumentObjectFileIncluded",
                                "FileObject2")
        L3 = self.Doc.addObject("App::DocumentObjectFileIncluded",
                                "FileObject3")

        # creating two files in the Transient directory of the document
        file1 = open(self.Doc.getTempFileName("test"), "w")
        file1.write("test No1")
        file1.close()
        file2 = open(self.Doc.getTempFileName("test"), "w")
        file2.write("test No2")
        file2.close()

        # applying the file with the same base name
        L2.File = (file1.name, "Test.txt")
        L3.File = (file2.name, "Test.txt")

        file = open(L2.File, "r")
        self.failUnless(file.read() == "test No1")
        file.close()
        file = open(L3.File, "r")
        self.failUnless(file.read() == "test No2")
        file.close()

        # create a second document, copy a file and close the document
        # the test is about to put the file to the correct transient dir
        doc2 = FreeCAD.newDocument("Doc2")
        L4 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject")
        L5 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject")
        L6 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject")
        L4.File = (L3.File, "Test.txt")
        L5.File = L3.File
        L6.File = L3.File
        FreeCAD.closeDocument("FileIncludeTests")
        self.Doc = FreeCAD.open(self.TempPath + "/FileIncludeTests.fcstd")
        self.failUnless(os.path.exists(L4.File))
        self.failUnless(os.path.exists(L5.File))
        self.failUnless(os.path.exists(L6.File))
        self.failUnless(L5.File != L6.File)
        # copy file from L5 which is in the same directory
        L7 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject3")
        L7.File = (L5.File, "Copy.txt")
        self.failUnless(os.path.exists(L5.File))
        FreeCAD.closeDocument("Doc2")
Example #46
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("FileIncludeTests")
Example #47
0
def read(filename):
    "reads the file and creates objects in the active document"
    #import importZip; reload(importZip)
    print("open Zip STEP version " + ___ZipVersion___)

    z = zipfile.ZipFile(filename)
    l = z.printdir()
    #il = z.infolist()
    nl = z.namelist()
    print("file list: ", nl)
    import ImportGui, FreeCADGui

    for f in nl:
        if '.stp' in f.lower() or '.step' in f.lower():  #\
            #or '.igs' in f.lower() or '.iges' in f.lower():
            file_content = z.read(f)
            #sfe = z.extract(f)
            #print ('extracted ',sfe)
            print('extracted ', f)
            # fname=os.path.splitext(os.path.basename(filename))[0]
            # ext = os.path.splitext(os.path.basename(filename))[1]
            fname = f
            print('fname ', f)
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            ImportGui.insert(tempfilepath, doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
        elif '.fcstd' in f.lower():  #\
            fname = f
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            i = 0
            for obj in FreeCAD.ActiveDocument.Objects:
                i += 1
            if i == 0:
                FreeCAD.closeDocument(doc.Name)
            FreeCAD.open(tempfilepath)
            #ImportGui.insert(tempfilepath,doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
        elif '.brep' in f.lower():  #\
            fname = f
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            import Part
            #Part.open(tempfilepath,doc.Name)
            Part.insert(tempfilepath, doc.Name)
            #FreeCAD.open(tempfilepath)
            #ImportGui.insert(tempfilepath,doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
Example #48
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("PropertyTests")
Example #49
0
# ---
# Outputs for photovoltaic materials (PV) in Spectral Analysis
# ---

if captured_energy_PV > 1E-9:

    data_PV_values = np.array(np.concatenate(PV_values))
    table_PV = otsun.make_histogram_from_experiment_results(
        PV_wavelength, PV_energy, wavelength_step, aperture_collector_PV,
        exp.light_source.emitting_region.aperture)
    spectrum_by_table_PV = source_spectrum[:, 1] * table_PV[:, 1]
    power_absorbed_from_source_PV = np.trapz(spectrum_by_table_PV,
                                             x=source_spectrum[:, 0])
    efficiency_from_source_PV = power_absorbed_from_source_PV / energy_emitted
    iqe = internal_quantum_efficiency
    SR = otsun.spectral_response(table_PV, iqe)
    ph_cu = otsun.photo_current(SR, source_spectrum)

    # print power_absorbed_from_source_PV * aperture_collector_PV * 1E-6, energy_emitted * exp.light_source.emitting_region.aperture * 1E-6, efficiency_from_source_PV, ph_cu

# --------- end

FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name)


def test_4():
    assert 0.1 > table_Th[0][1] > 0.0 and 0.1 > table_Th[1][
        1] > 0.0 and 0.98 > table_PV[0][1] > 0.75 and 0.98 > table_PV[1][
            1] > 0.75
Example #50
0
 def tearDown(self):
     #closing doc
     FreeCAD.closeDocument("CreateTest")
    def test02(self):
        '''Verify bones are correctly generated for a Profile.'''
        doc = FreeCAD.newDocument("TestDressupDogbone")

        # This is a real world test to make sure none of the tool chain broke
        box0 = doc.addObject('Part::Box', 'Box')
        box0.Width = 100
        box0.Length = 100
        box0.Height = 10
        box1 = doc.addObject('Part::Box', 'Box')
        box1.Width = 50
        box1.Length = 50
        box1.Height = 20
        box1.Placement = FreeCAD.Placement(
            FreeCAD.Vector(25, 25, -5),
            FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0))
        doc.recompute()
        cut = doc.addObject('Part::Cut', 'Cut')
        cut.Base = box0
        cut.Tool = box1
        doc.recompute()

        for i in range(11):
            face = "Face%d" % (i + 1)
            f = cut.Shape.getElement(face)
            if f.Surface.Axis == FreeCAD.Vector(
                    0, 0, 1) and f.Orientation == 'Forward':
                break

        job = doc.addObject("Path::FeatureCompoundPython", "Job")
        PathJob.ObjectPathJob(job, cut, None)

        profile = PathProfileFaces.Create('Profile Faces')
        profile.Base = (cut, face)
        profile.StepDown = 5
        profile.processHoles = True
        profile.processPerimeter = True
        doc.recompute()

        dogbone = PathDressupDogbone.Create(profile)
        doc.recompute()

        dog = dogbone.Proxy
        locs = sorted([bone[1] for bone in dog.bones],
                      key=lambda xy: xy[0] * 1000 + xy[1])

        def formatBoneLoc(pt):
            return "(%.2f, %.2f)" % (pt[0], pt[1])

        # Make sure we get 8 bones, 2 in each corner (different heights)
        self.assertEquals(len(locs), 8)
        self.assertEquals("(27.50, 27.50)", formatBoneLoc(locs[0]))
        self.assertEquals("(27.50, 27.50)", formatBoneLoc(locs[1]))
        self.assertEquals("(27.50, 72.50)", formatBoneLoc(locs[2]))
        self.assertEquals("(27.50, 72.50)", formatBoneLoc(locs[3]))
        self.assertEquals("(72.50, 27.50)", formatBoneLoc(locs[4]))
        self.assertEquals("(72.50, 27.50)", formatBoneLoc(locs[5]))
        self.assertEquals("(72.50, 72.50)", formatBoneLoc(locs[6]))
        self.assertEquals("(72.50, 72.50)", formatBoneLoc(locs[7]))

        FreeCAD.closeDocument("TestDressupDogbone")
 def tearDown(self):
     FreeCAD.closeDocument("SketchGuiTest")
Example #53
0
 def tearDown(self):
     App.closeDocument("ArchTest")
     pass
Example #54
0
 def tearDown(self):
     # clearance, is executed after every test
     FreeCAD.closeDocument(self.doc_name)
Example #55
0
def MakeHeader(n, model, all_params):
    global formerDOC
    global LIST_license
    ModelName = model.replace('yy', "{n:02}".format(n=n))

    full_path = os.path.realpath(__file__)
    expVRML.say(full_path)
    scriptdir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(scriptdir)
    sub_path = full_path.split(scriptdir)
    expVRML.say(sub_path)
    sub_dir_name = full_path.split(os.sep)[-2]
    expVRML.say(sub_dir_name)
    sub_path = full_path.split(sub_dir_name)[0]
    expVRML.say(sub_path)
    models_dir = sub_path + "_3Dmodels"
    script_dir = os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    expVRML.say(models_dir)
    out_dir = models_dir + all_params[model]['output_directory']
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')

    newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    App.ActiveDocument = App.getDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)

    header_type = all_params[model]['type']
    pitch = all_params[model]['pitch']
    rows = all_params[model]['rows']
    base_width = all_params[model]['base_width']
    base_height = all_params[model]['base_height']
    base_chamfer = all_params[model]['base_chamfer']
    pin_width = all_params[model]['pin_width']
    pin_length_above_base = all_params[model]['pin_length_above_base']

    pin_end_chamfer = all_params[model]['pin_end_chamfer']
    rotation = all_params[model]['rotation']

    if base_chamfer == 'auto':
        base_chamfer = pitch / 10.

    if pin_end_chamfer == 'auto':
        pin_end_chamfer = pin_width / 4.

    if header_type == 'Vertical_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base = make_Vertical_THT_base(n, pitch, rows, base_width, base_height,
                                      base_chamfer)
        pins = make_Vertical_THT_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_below_board, base_height,
                                      pin_width, pin_end_chamfer)
    elif header_type == 'Horizontal_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base_x_offset = all_params[model]['base_x_offset']
        base = make_Horizontal_THT_base(n, pitch, rows, base_width,
                                        base_height, base_x_offset,
                                        base_chamfer)
        pins = make_Horizontal_THT_pins(n, pitch, rows, pin_length_above_base,
                                        pin_length_below_board, base_height,
                                        base_width, pin_width, pin_end_chamfer,
                                        base_x_offset)
    elif header_type == 'Vertical_SMD':
        pin_length_horizontal = all_params[model]['pin_length_horizontal']
        base_z_offset = all_params[model]['base_z_offset']
        if rows == 1:
            pin_1_start = all_params[model]['pin_1_start']
        else:
            pin_1_start = None
        pins = make_Vertical_SMD_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_horizontal, base_height,
                                      base_width, pin_width, pin_end_chamfer,
                                      base_z_offset, pin_1_start)
        base = make_Vertical_SMD_base(n, pitch, base_width, base_height,
                                      base_chamfer, base_z_offset)
    else:
        print("Header type: ")
        print(header_type)
        print(" is not recognized, please check parameters")
        stop

    show(base)
    show(pins)

    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], pins_color)
    #Color_Objects(Gui,objs[2],marking_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    #col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_pin[:-1]: pins_color_key,
        #col_mark[:-1]:marking_color_key
    }
    expVRML.say(material_substitutions)

    #objs=GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()

    if (rotation != 0):
        z_RotateObject(doc, rotation)

    doc.Label = CheckedModelName

    #save the STEP file
    exportSTEP(doc, ModelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)

    #save the VRML file
    #scale=0.3937001
    #exportVRML(doc,name,scale,out_dir)

    if save_memory == False:
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()

    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, ModelName, out_dir, False)

    check_Model = True
    if save_memory == True or check_Model == True:
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
    step_path = os.path.join(out_dir, ModelName + u'.step')
    if check_Model == True:
        #ImportGui.insert(step_path,ModelName)
        ImportGui.open(step_path)
        docu = FreeCAD.ActiveDocument
        if cq_cad_tools.checkUnion(docu) == True:
            FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        else:
            FreeCAD.Console.PrintError('step file is not Unioned\n')
            FreeCAD.closeDocument(docu.Name)
            return 1
            #stop
        FC_majorV = int(FreeCAD.Version()[0])
        FC_minorV = int(FreeCAD.Version()[1])
        if FC_majorV == 0 and FC_minorV >= 17:
            for o in docu.Objects:
                if hasattr(o, 'Shape'):
                    chks = cq_cad_tools.checkBOP(o.Shape)
                    print(cq_cad_tools.mk_string(o.Label))
                    if chks != True:
                        msg = 'Checking shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' failed.\n'
                        FreeCAD.Console.PrintError(msg)
                        FreeCAD.Console.PrintWarning(chks[0])
                        FreeCAD.closeDocument(docu.Name)
                        return 1
                        #stop
                    else:
                        msg = 'Checking shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' passed.\n'
                        FreeCAD.Console.PrintMessage(msg)
        else:
            FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n')
            # Save the doc in Native FC format
        saveFCdoc(App, Gui, docu, ModelName, out_dir, False)
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)

    return 0
    def tearDown(self):
        """Finish the test.

        This is executed after each test, so we close the document.
        """
        App.closeDocument(self.doc_name)
Example #57
0
        colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
        expVRML.writeVRMLFile(colored_meshes, export_file_name,
                              used_color_keys, LIST_license)

        # Save the doc in Native FC format
        if save_memory == False:
            Gui.SendMsgToActiveView("ViewFit")
            Gui.activeDocument().activeView().viewAxometric()

        # Save the doc in Native FC format
        saveFCdoc(App, Gui, doc, ModelName, out_dir, False)

        check_Model = True
        if save_memory == True or check_Model == True:
            doc = FreeCAD.ActiveDocument
            FreeCAD.closeDocument(doc.Name)

        step_path = os.path.join(out_dir, ModelName + u'.step')
        if check_Model == True:
            #ImportGui.insert(step_path,ModelName)
            ImportGui.open(step_path)
            docu = FreeCAD.ActiveDocument
            if cq_cad_tools.checkUnion(docu) == True:
                FreeCAD.Console.PrintMessage(
                    'step file is correctly Unioned\n')
            else:
                FreeCAD.Console.PrintError('step file is NOT Unioned\n')
                stop
            FC_majorV = int(FreeCAD.Version()[0])
            FC_minorV = int(FreeCAD.Version()[1])
            if FC_majorV == 0 and FC_minorV >= 17:
Example #58
0
	def tearDown(self):
		#closing doc
		FreeCAD.closeDocument("PartDesignTest")
Example #59
0
	def tearDown(self):
		#closing doc
		FreeCAD.closeDocument("PartDesignTest")
		# print ("omit closing document for debugging")
Example #60
0
 def tearDown(self):
     FreeCAD.closeDocument(self.doc_name)
     pass