Example #1
0
    def onOpen(self):

        "opens the reference file"

        if hasattr(self,"Object") and self.Object:
            if self.Object.File:
                FreeCAD.openDocument(self.Object.File)
Example #2
0
    def testCrossDocumentLinks(self):
        """ Expressions accross files are not saved (bug #2442) """

        # Create a box
        box = self.doc.addObject('Part::Box', 'Box')

        # Create a second document with a cylinder
        doc2 = FreeCAD.newDocument()
        cylinder = doc2.addObject('Part::Cylinder', 'Cylinder')
        cylinder.setExpression('Radius', 'cube#Cube.Height')

        # Save and close first document
        self.doc.saveAs(self.TempPath + os.sep + 'cube.fcstd')
        FreeCAD.closeDocument(self.doc.Name)

        # Save and close second document
        doc2.saveAs(self.TempPath + os.sep + 'cylinder.fcstd')
        FreeCAD.closeDocument(doc2.Name)

        # Open both documents again
        self.doc = FreeCAD.openDocument(self.TempPath + os.sep + 'cube.fcstd')
        doc2 = FreeCAD.openDocument(self.TempPath + os.sep + 'cylinder.fcstd')

        # Check reference between them
        self.assertEqual(doc2.getObject('Cylinder').ExpressionEngine[0][1], 'cube#Cube.Height')

        # Close second document
        FreeCAD.closeDocument(doc2.Name)
Example #3
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 #4
0
 def load_file(self, doc, doc_file_id, path, gdoc=None):
     try:
         document = gdoc or FreeCAD.openDocument(path.encode("utf-8"))
     except IOError:
         show_error("Can not load %s" % path, self.window)
         return
     self.documents[document] = dict(openplm_doc=doc,
         openplm_file_id=doc_file_id, openplm_path=path)
     if " rev. " not in document.Label:
         document.Label = document.Label + " / %(name)s rev. %(revision)s" % doc
     return document
Example #5
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)
Example #6
0
def machinebuilder(diameter, height, file_path):
  
  #-- Get the freecad document
  document = os.path.abspath("cylinder.fcstd")
  doc = FreeCAD.openDocument(document)
  
  #-- Get the Cylinder object from the document
  cyl = doc.getObjectsByLabel("mycylinder")[0]
  
  #-- Set the cylinder's parameters
  if cyl:
      cyl.Radius = diameter / 2.0
      cyl.Height = height
      doc.recompute()
      
      #-- Export the file
      Mesh.export([cyl], file_path)
    def testIssue3363(self):
        """ Regression test for issue 3363; Nested conditionals statement fails with additional conditional statement in false-branch"""
        sheet = self.doc.addObject('Spreadsheet::Sheet','Spreadsheet')
        sheet.set('A1', '1')
        sheet.set('B1', '=A1==1?11:(A1==2?12:13)')
        sheet.set('C1', '=A1==1?(A1==2?12:13) : 11')
        self.doc.recompute()

        # Save and close first document
        self.doc.saveAs(self.TempPath + os.sep + 'conditionals.fcstd')
        FreeCAD.closeDocument(self.doc.Name)

        # Open documents again
        self.doc = FreeCAD.openDocument(self.TempPath + os.sep + 'conditionals.fcstd')

        sheet = self.doc.getObject('Spreadsheet')
        self.assertEqual(sheet.getContents('B1'), '=A1 == 1 ? 11 : (A1 == 2 ? 12 : 13)')
        self.assertEqual(sheet.getContents('C1'), '=A1 == 1 ? (A1 == 2 ? 12 : 13) : 11')
 def openFile(self):
     filename = None
     importDoc = None
     importDocIsOpen = False
     dialog = QtGui.QFileDialog(
         QtGui.QApplication.activeWindow(),
         "Select FreeCAD document to import part from")
     # set option "DontUseNativeDialog"=True, as native Filedialog shows
     # misbehavior on Unbuntu 18.04 LTS. It works case sensitively, what is not wanted...
     '''
     if a2plib.getNativeFileManagerUsage():
         dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, False)
     else:
         dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
     '''
     dialog.setNameFilter(
         "Supported Formats *.FCStd *.fcstd (*.FCStd *.fcstd);;All files (*.*)"
     )
     if dialog.exec_():
         filename = str(dialog.selectedFiles()[0])
         # look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
         requestedFile = os.path.split(filename)[1]
         # see whether the file is already open
         for d in App.listDocuments().values():
             recentFile = os.path.split(d.FileName)[1]
             if requestedFile == recentFile:
                 importDoc = d  # file is already open...
                 importDocIsOpen = True
                 break
         # if not, open it
         if not importDocIsOpen:
             if filename.lower().endswith('.fcstd'):
                 importDoc = App.openDocument(filename)
                 App.setActiveDocument(self.activeDoc.Name)
                 # update the part list
                 self.lookForParts(importDoc)
     return
Example #9
0
def add_part(base, params, doc):
    if base.type == "function":
        module = importlib.import_module(base.module_name)
        module.__dict__[base.name](params, doc)
    elif base.type == "fcstd":
        #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()
        FreeCAD.setActiveDocument(doc.Name)
        FreeCAD.closeDocument(src_doc.Name)
Example #10
0
    def _loadBitBody(self, obj, path=None):
        PathLog.track(obj.Label, path)
        p = path if path else obj.BitShape
        docOpened = False
        doc = None
        for d in FreeCAD.listDocuments():
            if FreeCAD.getDocument(d).FileName == p:
                doc = FreeCAD.getDocument(d)
                break
        if doc is None:
            p = findToolShape(p, path if path else obj.File)
            if p is None:
                raise FileNotFoundError

            if not path and p != obj.BitShape:
                obj.BitShape = p
            PathLog.debug("ToolBit {} using shape file: {}".format(
                obj.Label, p))
            doc = FreeCAD.openDocument(p, True)
            obj.ShapeName = doc.Name
            docOpened = True
        else:
            PathLog.debug("ToolBit {} already open: {}".format(obj.Label, doc))
        return (doc, docOpened)
Example #11
0
def add_part(base,params,doc):
	if base.type == "function":
		module = importlib.import_module(base.module_name)
		module.__dict__[base.name](params,doc)
	elif base.type == "fcstd":
		#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()
		FreeCAD.setActiveDocument(doc.Name)
		FreeCAD.closeDocument(src_doc.Name)
Example #12
0
def open_doc(filepath):
    doc = FreeCAD.openDocument(filepath)
    # time.sleep(1)
    return doc
Example #13
0
    def openFile(self):

        if self.obj.File:
            FreeCAD.openDocument(self.obj.File)
            FreeCADGui.Control.closeDialog()
            FreeCADGui.ActiveDocument.resetEdit()
Example #14
0
    def openFile(self):

        if self.obj.File:
            FreeCAD.openDocument(self.obj.File)
            FreeCADGui.Control.closeDialog()
            FreeCADGui.ActiveDocument.resetEdit()
Example #15
0
    def Activated(self):
        a2plib.setAutoSolve(True)  # makes no sense without autosolve = ON
        doc = FreeCAD.activeDocument()
        fileName = doc.FileName
        workingDir, basicFileName = os.path.split(fileName)

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

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

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

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

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

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

            FreeCADGui.updateGui()
            importDoc.save()
            print(u"==== Assembly '{}' has been updated! =====".format(
                importDoc.FileName))
            if importDoc != doc:
                FreeCAD.closeDocument(importDoc.Name)
Example #16
0
    if len(g) != 2:
        print("ERROR: {} not a valid group mapping".format(args.move))
        sys.exit(1)
    GroupMap[g[0]] = g[1]

if args.set:
    s = args.set.split('=')
    if len(s) != 2:
        print("ERROR: {} not a valid group mapping".format(args.move))
        sys.exit(1)
    set_var = s[0]
    set_val = s[1]

for i, fname in enumerate(args.path):
    #print(fname)
    doc = FreeCAD.openDocument(fname, False)
    print("{}:".format(doc.Name))
    for o in doc.Objects:
        if PathPropertyBag.IsPropertyBag(o):
            if args.print_groups:
                print("  {}:  {}".format(o.Label, sorted(o.CustomPropertyGroups)))
            else:
                print("  {}:".format(o.Label))
            for p in o.Proxy.getCustomProperties():
                grp = o.getGroupOfProperty(p)
                typ = o.getTypeIdOfProperty(p)
                ttp = PathPropertyBag.getPropertyTypeName(typ)
                val = PathUtil.getProperty(o, p)
                dsc = o.getDocumentationOfProperty(p)
                enm = ''
                enum = []
import sys
from pathlib import Path

# path to FreeCAD.so
FREECADPATH = 'G:\\program files\\FreeCAD 0.19\\bin'
sys.path.append(FREECADPATH)
import FreeCAD
import pytest

civiltools_path = Path(__file__).absolute().parent.parent.parent
sys.path.insert(0, str(civiltools_path))
from freecad_py.assign import wall_loads

tos = civiltools_path / 'tests' / 'test_files' / 'tos.FCStd'
tos = FreeCAD.openDocument(str(tos))


def test_add_wall_on_beams():
    wall_loads.add_wall_on_beams(
        'Dead',
        220,
        labels=('B35', ),
        # stories=('Story1', 'Story9'),
        opening_ratio=0.3,
        #  height=3000,
    )


def test_create_wall():
    base = tos.getObjectsByLabel('B35_Story1_CenterLine')[0]
    wall = wall_loads.create_wall(base, 0.2, .8, relative=True)
Example #18
0
def importPartFromFile(_doc, filename, importToCache=False):
    doc = _doc
    #-------------------------------------------
    # Get the importDocument
    #-------------------------------------------
    importDocIsOpen = filename in [ d.FileName for d in FreeCAD.listDocuments().values() ]
    if importDocIsOpen:
        importDoc = [ d for d in FreeCAD.listDocuments().values() if d.FileName == filename][0]
    else:
        if filename.lower().endswith('.fcstd'):
            importDoc = FreeCAD.openDocument(filename)
        else:
            msg = "A part can only be imported from a FreeCAD '*.fcstd' file"
            QtGui.QMessageBox.information(  QtGui.QApplication.activeWindow(), "Value Error", msg )
            return
    #-------------------------------------------
    # Get a list of the visible Objects
    #-------------------------------------------
    visibleObjects = [ obj for obj in importDoc.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]

    if visibleObjects == None or len(visibleObjects) == 0:
        msg = "No visible Part to import found. Aborting operation"
        QtGui.QMessageBox.information(
            QtGui.QApplication.activeWindow(),
            "Import Error",
            msg
            )
        return

    #-------------------------------------------
    # Discover whether we are importing a subassembly or a single part
    #-------------------------------------------
    #if any([ 'importPart' in obj.Content for obj in importDoc.Objects]) and not len(visibleObjects) == 1:
    subAssemblyImport = False
    if len(visibleObjects) > 1:
        subAssemblyImport = True

    #-------------------------------------------
    # create new object
    #-------------------------------------------
    if importToCache:
        partName = 'CachedObject_'+str(objectCache.len())
        newObj = doc.addObject("Part::FeaturePython",partName)
        newObj.Label = partName
    else:
        partName = a2plib.findUnusedObjectName( importDoc.Label, document=doc )
        partLabel = a2plib.findUnusedObjectLabel( importDoc.Label, document=doc )
        newObj = doc.addObject("Part::FeaturePython",partName.encode('utf-8'))
        newObj.Label = partLabel


    newObj.addProperty("App::PropertyString", "a2p_Version","importPart").a2p_Version = A2P_VERSION
    newObj.addProperty("App::PropertyFile",    "sourceFile",    "importPart").sourceFile = filename
    newObj.addProperty("App::PropertyStringList","muxInfo","importPart")
    newObj.addProperty("App::PropertyFloat", "timeLastImport","importPart")
    newObj.setEditorMode("timeLastImport",1)
    newObj.timeLastImport = os.path.getmtime( filename )
    newObj.addProperty("App::PropertyBool","fixedPosition","importPart")
    newObj.fixedPosition = not any([i.fixedPosition for i in doc.Objects if hasattr(i, 'fixedPosition') ])
    newObj.addProperty("App::PropertyBool","subassemblyImport","importPart").subassemblyImport = subAssemblyImport
    newObj.setEditorMode("subassemblyImport",1)
    newObj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
    #
    if subAssemblyImport:
        newObj.muxInfo, newObj.Shape, newObj.ViewObject.DiffuseColor = muxObjectsWithKeys(importDoc, withColor=True)
        #newObj.muxInfo, newObj.Shape = muxObjectsWithKeys(importDoc, withColor=False)
    else:
        tmpObj = visibleObjects[0]
        newObj.Shape = tmpObj.Shape.copy()
        newObj.ViewObject.ShapeColor = tmpObj.ViewObject.ShapeColor
        if appVersionStr() <= '000.016': #FC0.17: DiffuseColor overrides ShapeColor !
            newObj.ViewObject.DiffuseColor = tmpObj.ViewObject.DiffuseColor
        newObj.muxInfo = createTopoInfo(tmpObj)

    newObj.Proxy = Proxy_muxAssemblyObj()
    newObj.ViewObject.Proxy = ImportedPartViewProviderProxy()

    doc.recompute()

    if importToCache:
        objectCache.add(newObj.sourceFile, newObj)

    if not importDocIsOpen:
        FreeCAD.closeDocument(importDoc.Name)

    return newObj
	else:
		# if not matched, throw error
		raise Warning("Command not matched")



# If not imported
if __name__ == "__main__":

	try:
		# Get first argument (sys.argv[0] is path), throws IndexError
		fn = sys.argv[1]

		# Open document. Throws I/O Error.
		DOCUMENT = FreeCAD.openDocument ( fn )

		# Flag to signal that no more bullshit (load info) will be printed on stdout
		sys.stderr.write( BEGINFLAG )
		sys.stderr.flush()

	except IndexError:
		raise Warning("No filename passed in")

	except IOError:
		raise Warning("Invalid or non-existing file %s" % sys.argv[1])


	# Main loop. Using an infinite loop is fine, as the parent process can kill this one.
	while 1:
		# sys.stdin.readline() happily blocks
Example #20
0
#!/usr/bin/env python

# Description: Enters all subfolders in 'rootdir', opens all .FCStd files found, and exports the latest object created in each file as .stl
# Usage: Run as macro script from FreeCAD (e.g. from 'Macro' menu).
# Note: Tested on Mac OSX Yosemite only.

import os
import glob
import FreeCAD
import Mesh

rootdir = '/Users/mstoelen/github/GummiArm/printables' # point to printables folder

for subdir, dirs, files in os.walk(rootdir):
    for filename in glob.glob(os.path.join(subdir, '*.FCStd')):
        document = FreeCAD.openDocument(filename)
        objects = [ document.ActiveObject ]
        outname = filename[:-5] + "stl"
        Mesh.export(objects, outname)
        FreeCAD.closeDocument(document.Name)
Example #21
0
 def setUpClass(cls):
     global doc
     doc = FreeCAD.openDocument(FreeCAD.getHomePath() +
                                "Mod/Path/PathTests/test_geomop.fcstd")
    def openSubAssembly(
        self, subFile
    ):  #recursive func!! This can consumpt the total memory of your computer
        filename = findSourceFileInProject(
            subFile)  # path within subfile will be ignored..
        if filename == None:
            FreeCAD.Console.PrintMessage(
                "Missing file {} ignored".format(subFile))
            return False

        doc_already_open = filename in [
            d.FileName for d in FreeCAD.listDocuments().values()
        ]
        if doc_already_open:
            doc = [
                d for d in FreeCAD.listDocuments().values()
                if d.FileName == filename
            ][0]
        else:
            doc = FreeCAD.openDocument(filename)

        needUpdate = False

        for obj in doc.Objects:
            if hasattr(obj, 'sourceFile'):

                # This Section: Add missing but necessary properties of this Version
                if not hasattr(obj, 'a2p_Version'):
                    obj.addProperty("App::PropertyString", "a2p_Version",
                                    "importPart").a2p_Version = 'V0.0'
                    obj.setEditorMode("a2p_Version", 1)
                    needUpdate = True

                if not hasattr(obj, 'muxInfo'):
                    obj.addProperty("App::PropertyStringList", "muxInfo",
                                    "importPart").muxInfo = []
                    needUpdate = True

                if not hasattr(obj, 'subassemblyImport'):
                    obj.addProperty("App::PropertyBool", "subassemblyImport",
                                    "importPart").subassemblyImport = False
                    obj.setEditorMode("subassemblyImport", 1)
                    obj.subassemblyImport = self.checkForSubAssembly(
                        obj.sourceFile)
                    needUpdate = True

                if obj.subassemblyImport == True:
                    # This Section: Open subassemblies which this assembly depends on...
                    replacement = findSourceFileInProject(
                        obj.sourceFile
                    )  # work in any case with files within projectFolder!
                    if replacement == None:
                        QtGui.QMessageBox.critical(
                            QtGui.QApplication.activeWindow(),
                            "Source file not found",
                            "update of %s aborted!\nUnable to find %s" %
                            (obj.Name, obj.sourceFile))
                    else:
                        if obj.sourceFile != replacement:
                            obj.sourceFile = replacement  # update Filepath, perhaps location changed due to new projectFile!
                        result = self.openSubAssembly(obj.sourceFile)
                        if result == True:
                            needUpdate = True

                if obj.a2p_Version != A2P_VERSION:
                    needUpdate = True

                if os.path.getmtime(obj.sourceFile) > obj.timeLastImport:
                    needUpdate = True

        if not needUpdate:
            if doc not in self.docsToBeClosed:
                self.docsToBeClosed.append(doc)

        return needUpdate
Example #23
0
import sys
#otsun_path = "D:\\Ramon_2015\\RECERCA\\RETOS-2015\\Tareas\\OTSun_local\\"
#sys.path.append(otsun_path)
import otsun
import os
import FreeCAD
from FreeCAD import Base
import Part
import numpy as np
np.random.seed(1)
import random
random.seed(1)

MyProject = 'Perovskite_Stack_200nm.FCStd'
FreeCAD.openDocument(MyProject)

# ---
# Materials
# ---
otsun.TransparentSimpleLayer("Trans", 1.0)
otsun.AbsorberSimpleLayer("Abs", 1.0)
otsun.TwoLayerMaterial("Trans_Abs", "Trans", "Abs")
file_thin_film = 'Fitxer_OTSun_Exp1a_theta0_90.txt'
file_Perovskite = 'Perovskite_Leguy.txt'
otsun.PolarizedThinFilm("ThinFilm", file_thin_film, "Vacuum", file_Perovskite)
otsun.PVMaterial("PV", file_Perovskite)
file_Spiro = 'Spiro_.txt'
otsun.WavelengthVolumeMaterial("Spiro", file_Spiro)
file_Ag = 'Ag_Yang.txt'
otsun.MetallicLambertianLayer("Ag", file_Ag)
Example #24
0
#!/usr/bin/env python

# Description: Enters all subfolders in 'rootdir', opens all .FCStd files found, and exports the latest object created in each file as .stl
# Usage: Run as macro script from FreeCAD (e.g. from 'Macro' menu).
# Note: Tested on Mac OSX Yosemite only.

import os
import glob
import FreeCAD
import Mesh

rootdir = '/Users/mstoelen/Git/GummiArm/printables'  # point to printables folder

for subdir, dirs, files in os.walk(rootdir):
    for filename in glob.glob(os.path.join(subdir, '*.FCStd')):
        document = FreeCAD.openDocument(filename)
        objects = [document.ActiveObject]
        outname = filename[:-5] + "stl"
        Mesh.export(objects, outname)
        FreeCAD.closeDocument(document.Name)
Example #25
0
 def myslotRestoredDocument(self, doc):
     "Fires when project has finished loading"
     docname = doc.Name
     if len(doc.FileName) > 0:
         from FCTeleport import Tools as TeleTools
         dir, job = TeleTools.isConversionRequired(doc)
         if dir != False:
             from PySide import QtGui
             mb = QtGui.QMessageBox()
             upgraded = "upgraded" if dir > 0 else "downgraded"
             older = "older" if dir > 0 else "newer"
             jobactions = [
                 t.brief_description for t in job.an_list_of_actions
             ]
             jobactions = '\n  '.join(jobactions)
             features = job.an_list_of_features
             if len(features) > 8:
                 features = features[0:5] + ['...'] + features[-2:]
             features = '\n  '.join(features)
             mb.setText(
                 "Project {docname} was created in {older} version of FreeCAD, and contains features that can be {upgraded} to current version.\n\n"
                 "Breaking changes involved:\n"
                 "  {jobactions}\n\n"
                 "Features to be altered:\n"
                 "  {features}\n\n".format(**vars()))
             mb.setWindowTitle("FCTeleport")
             btnCancel = mb.addButton(
                 QtGui.QMessageBox.StandardButton.Cancel)
             btnConvertOpen = mb.addButton(
                 "Open converted", QtGui.QMessageBox.ButtonRole.ActionRole)
             btnConvertOpen.setToolTip(
                 "Converts the project, saves it to a temporary location and opens it in FreeCAD. You need to save the converted file yourself."
             )
             btnConvertWrite = mb.addButton(
                 "Create converted file",
                 QtGui.QMessageBox.ButtonRole.ActionRole)
             btnConvertWrite.setToolTip(
                 "Converts the project, saves it next to the original file."
             )
             mb.setDefaultButton(btnConvertOpen)
             mb.exec_()
             if mb.clickedButton() is btnCancel:
                 return
             if mb.clickedButton() is btnConvertWrite:
                 file = TeleTools.convertProject(doc.FileName)
                 Utils.msgbox(
                     "FCTeleport",
                     "Created converted copy of the project here:\n{file}".
                     format(file=file))
             if mb.clickedButton() is btnConvertOpen:
                 import tempfile
                 f = tempfile.NamedTemporaryFile(suffix=".FCStd",
                                                 delete=False)
                 try:
                     f.file.close()
                     TeleTools.convertProject(doc.FileName,
                                              filename_out=f.name)
                     self.ignoreonce = True  #ugly hack. prevent teleport from scanning this file for porting, as it won't exist at that point
                     App.openDocument(f.name)
                 finally:
                     import os
                     os.remove(f.name)
Example #26
0
def load_document(document_path: Path) -> Document:
    document = App.openDocument(str(document_path))
    recompute_document(document)
    return document
Example #27
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 #28
0
numDoc = 0
numObj = 0
numError = 0
geometricList = []
vertexList = []
edgeList = []
executionList = []

for directory in os.walk('/home/travis/SlopedPlanesTest/Test'):
    # print 'directory ', directory
    for filename in directory[2]:
        # print 'filename ', filename
        if filename.endswith('.fcstd'):
            # print 'open'
            doc = FreeCAD.openDocument(directory[0] + '/' + filename)
            # print '######### ', doc.Name
            numDoc += 1

            for obj in doc.Objects:
                if hasattr(obj, 'Proxy'):
                    if obj.Proxy.Type == 'SlopedPlanes':
                        numObj += 1

                        oldShape = obj.Shape.copy()

                        obj.Proxy.faceList = []
                        for pyFace in obj.Proxy.Pyth:
                            pyFace.reset = True

                        obj.touch()
import math
import sys
from pathlib import Path

import pytest

FREECADPATH = 'G:\\program files\\FreeCAD 0.19\\bin'
sys.path.append(FREECADPATH)

import FreeCAD
import Part

filename_base_foundation = Path(__file__).absolute(
).parent.parent / 'test_files' / 'freecad' / 'base_foundation.FCStd'
document_base_foundation = FreeCAD.openDocument(str(filename_base_foundation))

punch_path = Path(__file__).absolute().parent.parent
sys.path.insert(0, str(punch_path))
import etabs_foundation


def test_make_foundation():
    bfs = []
    for o in document_base_foundation.Objects:
        if o.Proxy.Type == 'BaseFoundation':
            bfs.append(o)
    ret = etabs_foundation.make_foundation(base_foundations=bfs)
    assert True


if __name__ == '__main__':
Example #30
0
# -*- coding: utf-8 -*-

# Macro Begin: /home/tim/Documents/GitHub/replimat/src/FreeCAD/Render stl.FCMacro +++++++++++++++++++++++++++++++++++++++++++++++++
import FreeCAD
import Mesh

# Gui.runCommand('Std_DlgMacroRecord',0)
### Begin command Std_Open
FreeCAD.openDocument(
    '/home/tim/Documents/GitHub/replimat/src/FreeCAD/0.75in_x_1.5in_NPT_suction_pipe.FCStd'
)
# App.setActiveDocument("__75in_x_1_5in_NPT_suction_pipe")
# App.ActiveDocument=App.getDocument("__75in_x_1_5in_NPT_suction_pipe")
# Gui.ActiveDocument=Gui.getDocument("__75in_x_1_5in_NPT_suction_pipe")
### End command Std_Open
# Gui.runCommand('Std_PerspectiveCamera',1)
# Gui.runCommand('Std_Export',0)
# Gui.Selection.addSelection('__75in_x_1_5in_NPT_suction_pipe','Cut001','Face1',-2.99839,12.9209,21.7593)
### Begin command Std_Export
__objs__ = []
__objs__.append(
    FreeCAD.getDocument("__75in_x_1_5in_NPT_suction_pipe").getObject("Cut001"))
Mesh.export(
    __objs__,
    u"/home/tim/Documents/GitHub/replimat/src/FreeCAD/0.75in_x_1.5in_NPT_suction_pipe-0.75 NPT x 1.stl"
)

del __objs__
### End command Std_Export
# Macro End: /home/tim/Documents/GitHub/replimat/src/FreeCAD/Render stl.FCMacro +++++++++++++++++++++++++++++++++++++++++++++++++
Example #31
0
 def openFile(self):
     if self.obj.File:
         FreeCAD.openDocument(self.obj.File)
         FreeCADGui.Control.closeDialog()
Example #32
0
import sys
from pathlib import Path

import pytest

FREECADPATH = 'G:\\program files\\FreeCAD 0.19\\bin'
sys.path.append(FREECADPATH)

import FreeCAD
import Part

filename = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'strip.FCStd'
filename_strip_foundation = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'strip_foundation.FCStd'
filename_mat = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'mat.FCStd'
filename_base_foundation = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'base_foundation.FCStd'
document= FreeCAD.openDocument(str(filename))
document_mat= FreeCAD.openDocument(str(filename_mat))
document_base_foundation = FreeCAD.openDocument(str(filename_base_foundation))
document_strip_foundation = FreeCAD.openDocument(str(filename_strip_foundation))


punch_path = Path(__file__).absolute().parent.parent
sys.path.insert(0, str(punch_path))
import punch_funcs  

def test_sort_vertex():
    points = [[0,0], [1,1], [1,0], [0,1]]
    points = punch_funcs.sort_vertex(points)
    assert points == [[0, 0], [0, 1], [1, 1], [1, 0]]

def test_get_sort_points():
Example #33
0
import os
import subprocess
#from PySide import QtGui
#import FreeCADGui
print 12
import FreeCAD
print 13
import Arch, Draft, Drawing
#from building_func import *
print 0
FreeCAD.openDocument("/home/ambu/Documents/Drawing-FreeCAD/project.fcstd")
print 1
App.setActiveDocument("project")
print 2
# Storing all objects (i.e parts of building like column, beams and slabs)
# in obj_list
#obj_list = FreeCAD.ActiveDocument.Objects

# Adding object 'Compound' in active document. The Compound object stores
# all parts of the building
#App.activeDocument().addObject("Part::Compound","Compound")

# Links all the objects present in obj_list to Compound
#App.activeDocument().Compound.Links = obj_list

# Adding the object 'Page' in active document
#App.ActiveDocument.addObject('Drawing::FeaturePage','Page')

# Choose the specific template
#App.ActiveDocument.Page.Template = App.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg'
Example #34
0
#FREECADPATH = 'C:/Program Files/FreeCAD 0.19/bin/'
FREECADPATH = '/home/rboshra/miniconda3/envs/fcenv/lib'
sys.path.append(FREECADPATH)
import FreeCAD
import Sketcher
import Part

data = scipy.io.loadmat('Generic Circular.mat', simplify_cells=True)

x_mm = data['strctGridModel']['m_afGridHolesX']
y_mm = data['strctGridModel']['m_afGridHolesY']
hole_radius = data['strctGridModel']['m_strctGridParams'][
    'm_fGridHoleDiameterMM'] / 2

FreeCAD.openDocument('grid_template.FCStd')

App.getDocument('grid_template').getObject('Body').newObject(
    'Sketcher::SketchObject', 'Sketch003')
App.getDocument('grid_template').getObject('Sketch003').Support = (
    App.getDocument('grid_template').getObject('Pocket'), [
        'Face3',
    ])
App.getDocument('grid_template').getObject('Sketch003').MapMode = 'FlatFace'
App.ActiveDocument.recompute()

holeNum = 0
for x, y in zip(x_mm, y_mm):
    App.getDocument('grid_template').getObject('Sketch003').addGeometry(
        Part.Circle(App.Vector(x, y, 0), App.Vector(0, 0, 1), hole_radius),
        False)
 def setUpClass(cls):
     global doc
     doc = FreeCAD.openDocument(FreeCAD.getHomePath() + 'Mod/Path/PathTests/test_geomop.fcstd')
Example #36
0
    def __init__(self, length, name, axis='x', cx=False, cy=False, cz=False):
        doc = FreeCAD.ActiveDocument
        self.length = length
        self.name = name
        self.axis = axis
        self.cx = cx
        self.cy = cy
        self.cz = cz
        # filepath
        path = os.getcwd()
        #logging.debug(path)
        self.skpath = path + '/../../freecad/comps/'
        doc_sk = FreeCAD.openDocument(self.skpath + self.skfilename)

        list_obj_alumprofile = []
        for obj in doc_sk.Objects:

            #if (hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
            #    and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 ):
            #   # len(obj.Shape.Faces) > 0 to avoid sketches
            #    list_obj_alumprofile.append(obj)
            if len(obj.Shape.Faces) == 0:
                orig_alumsk = obj

        FreeCAD.ActiveDocument = doc
        self.Sk = doc.addObject("Sketcher::SketchObject", 'sk_' + name)
        self.Sk.Geometry = orig_alumsk.Geometry
        print(orig_alumsk.Geometry)
        print(orig_alumsk.Constraints)
        self.Sk.Constraints = orig_alumsk.Constraints
        self.Sk.ViewObject.Visibility = False

        FreeCAD.closeDocument(doc_sk.Name)
        FreeCAD.ActiveDocument = doc  #otherwise, clone will not work

        # The sketch is on plane XY, facing Z
        if axis == 'x':
            self.Dir = (length, 0, 0)
            # rotation on Y
            rot = FreeCAD.Rotation(VY, 90)
            if cx == True:
                xpos = -self.length / 2.0
            else:
                xpos = 0
            if cy == True:
                ypos = 0
            else:
                ypos = self.ALU_Wh  # half of the aluminum profile width
            if cz == True:
                zpos = 0
            else:
                zpos = self.ALU_Wh
        elif axis == 'y':
            self.Dir = (0, length, 0)
            # rotation on X
            rot = FreeCAD.Rotation(VX, -90)
            if cx == True:
                xpos = 0
            else:
                xpos = self.ALU_Wh
            if cy == True:
                ypos = -self.length / 2.0
            else:
                ypos = 0
            if cz == True:
                zpos = 0
            else:
                zpos = self.ALU_Wh
        elif axis == 'z':
            self.Dir = (0, 0, length)
            # no rotation
            rot = FreeCAD.Rotation(VZ, 0)
            if cx == True:
                xpos = 0
            else:
                xpos = self.ALU_Wh
            if cy == True:
                ypos = 0
            else:
                ypos = self.ALU_Wh
            if cz == True:
                zpos = -self.length / 2.0
            else:
                zpos = 0
        else:
            logging.debug("wrong argument")

        self.Sk.Placement.Rotation = rot
        self.Sk.Placement.Base = FreeCAD.Vector(xpos, ypos, zpos)

        alu_extr = doc.addObject("Part::Extrusion", name)
        alu_extr.Base = self.Sk
        alu_extr.Dir = self.Dir
        alu_extr.Solid = True

        self.fco = alu_extr  # the FreeCad Object
import sys
from pathlib import Path

# path to FreeCAD.so
FREECADPATH = 'G:\\program files\\FreeCAD 0.19\\bin'
sys.path.append(FREECADPATH)
import FreeCAD
import pytest

filename = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'strip.FCStd'
filename_mat = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'mat.FCStd'
filename_kazemi = Path(__file__).absolute().parent.parent / 'test_files' / 'freecad' / 'kazemi.FCStd'
document= FreeCAD.openDocument(str(filename))
document_mat= FreeCAD.openDocument(str(filename_mat))
document_kazemi= FreeCAD.openDocument(str(filename_kazemi))

punch_path = Path(__file__).absolute().parent.parent
sys.path.insert(0, str(punch_path))

from safe_read_write_f2k import FreecadReadwriteModel as FRW
from safe_read_write_f2k import Safe, Safe12

def test_export_freecad_slabs():
    rw = FRW(doc=document_kazemi)
    slabs = rw.export_freecad_slabs()
    rw.safe.write()
    assert len(slabs) == 33

def test_export_freecad_wall_loads():
    input_f2k_path = Path('~\input.f2k').expanduser()
    input_f2k_path.touch()
Example #38
0
    with open(output_file, 'w') as f:
        f.write(f"{aperture_collector_Th * 1E-6} # Collector Th aperture in m2\n")
        f.write(f"{power_emitted_by_m2} # Source power emitted by m2\n")
        f.write(f"{number_of_rays} # Rays emitted per sun position\n")
        f.write("# phi theta efficiency_from_source_Th\n")
        for value in values:
            (ph, th, efficiency_from_source_Th) = value
            f.write(f"{ph:.3f} {th:.3f} {efficiency_from_source_Th:.6f}\n")


if __name__ == '__main__':
    # ---
    # Load freecad file
    # ---
    freecad_file = 'LFR.FCStd'
    FreeCAD.openDocument(freecad_file)
    doc = FreeCAD.ActiveDocument

    # ---
    # Definition of materials
    # ---
    otsun.ReflectorSpecularLayer("Mir1", 0.95)
    otsun.ReflectorSpecularLayer("Mir2", 0.91)
    otsun.AbsorberSimpleLayer("Abs", 0.95)
    otsun.TransparentSimpleLayer("Trans", 0.965)

    # ---
    # Definition of parameters for the simulation
    # ---
    # Angles
    phi_ini = 0.0
Example #39
0
def open_document(path):
    return FreeCAD.openDocument(path)
Example #40
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()
import FreeCAD
import Mesh
import Part
import importDWG

projects = [
  "open_air_case_frame",
  "foot",
]

objects = []
for project in projects:
  FreeCAD.openDocument("./projects/"+project+".fcstd")
  FreeCAD.setActiveDocument(project)

  objects.append(FreeCAD.getDocument(project).getObject("Group"))

  Mesh.export(objects, u"./exports/"+project+".obj")
  Mesh.export(objects, u"./exports/"+project+".amf")
  Part.export(objects, u"./exports/"+project+".iges")
  importDWG.export(objects, u"./exports/"+project+".dwg")

  del objects
Example #42
0
import math
import sys
from pathlib import Path

import pytest

FREECADPATH = 'G:\\program files\\FreeCAD 0.19\\bin'
sys.path.append(FREECADPATH)

import FreeCAD
import Part

filename_base_plate = Path(__file__).absolute(
).parent.parent / 'test_files' / 'freecad' / 'base_plate.FCStd'
document_base_plate = FreeCAD.openDocument(str(filename_base_plate))

punch_path = Path(__file__).absolute().parent.parent
sys.path.insert(0, str(punch_path))
import punch


def test_make_punch():
    foun = document_base_plate.Foundation
    col = document_base_plate.getObjectsByLabel('C1_Story1')[0]
    p = punch.make_punch(foun, col)
    p.Proxy.execute(p)
    assert True


if __name__ == '__main__':
    test_make_punch()
Example #43
0
 def setUpClass(cls):
     global doc  # pylint: disable=global-statement
     doc = FreeCAD.openDocument(FreeCAD.getHomePath() +
                                'Mod/Path/PathTests/test_geomop.fcstd')