Încorporarea FreeCAD

From FreeCAD Documentation
Revision as of 16:01, 19 August 2018 by Luc (talk | contribs) (Created page with "Bineînțeles, ați văzut că acest script este foarte simplu (de fapt am făcut unul mai avansat aici [http://yorik.orgfree.com/scripts/import_freecad.py here]),ați putea d...")

FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.


FreeCAD a la capacité incroyable de pouvoir être importé en tant que module Python dans d'autres programmes ou, dans une console Python autonome, avec tous ses modules et ses composants. Il est même possible d'importer l'interface graphique (GUI) de FreeCAD en tant que module python avec toutefois, quelques restrictions. Mais avec quelques restrictions.


FreeCAD are capacitatea uimitoare de a fi importabil ca modul python în alte programe sau într-o consolă python autonomă, împreună cu toate modulele și componentele sale. Este posibil chiar să importați interfața grafică GUI-ul FreeCAD ca modul python - cu some restrictions, dar cu anumite restricții.

Using FreeCAD without GUI

O primă aplicație directă, ușoară și utilă pe care o puteți face este importul documentelor FreeCAD în programul dvs. În următorul exemplu, vom importa geometria pieselor unui document FreeCAD în blender. Iată scenariul complet. Sper că veți fi impresionat de simplitatea sa:

FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
import Blender, sys
sys.path.append(FREECADPATH)
 
def import_fcstd(filename):
   try:
       import FreeCAD
   except ValueError:
       Blender.Draw.PupMenu('Error%t|FreeCAD library not found. Please check the FREECADPATH variable in the import script is correct')
   else:
       scene = Blender.Scene.GetCurrent()
       import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':
               shape = ob.Shape
               if shape.Faces:
                   mesh = Blender.Mesh.New()
                   rawdata = shape.tessellate(1)
                   for v in rawdata[0]:
                       mesh.verts.append((v.x,v.y,v.z))
                   for f in rawdata[1]:
                       mesh.faces.append.append(f)
                   scene.objects.new(mesh,ob.Name)
       Blender.Redraw()

def main():
   Blender.Window.FileSelector(import_fcstd, 'IMPORT FCSTD', 
                        Blender.sys.makename(ext='.fcstd'))    
 
# This lets you import the script without running it
if __name__=='__main__':
   main()

Prima parte importantă este să vă asigurați că Python va găsi biblioteca noastră FreeCAD. Odată ce o găsește, toate modulele FreeCAD, cum ar fi Part, pe care o vom folosi, vor fi disponibile automat. Așa că luăm pur și simplu variabila sys.path, care este unde Python caută module și adăugăm calea FreCAD.Lib. Această modificare este doar temporară și se va pierde atunci când închidem interpretorul nostru python. Un alt mod ar putea fi să faceți o legătură cu biblioteca dvs. FreeCAD într-una din căile de căutare python. Am păstrat calea într-o constantă (FREECADPATH) astfel încât un alt utilizator al scriptului îi va fi mai ușor să configureze propriul sistem

Odată ce suntem siguri că biblioteca este încărcată (secvența try/except), acum putem lucra cu FreeCAD, la fel ca și cum am fi în interiorul interpretului Python al FreeCAD. Deschidem documentul FreeCAD care ne este transmis prin funcția principală main() și facem o listă a obiectelor sale. Apoi, pe măsură ce alegem doar să ne pese de geometria piesei, verificăm dacă proprietatea Type a fiecărui obiect conține "Part", apoi o mozaicăm (tessellation).

Mozaicarea (Tessellation) produce o listă de vârfuri(vertex) și o listă de fasțete definite de indici de vârfuri. Acest lucru este perfect, deoarece este exact același mod în care programul Blender definește ochiurile de plasă. Deci, sarcina noastră este ridicol de simplă, adăugăm ambele conținuturi ale listelor la vârfurile și fețetele unei rețele de tip Blender. Când totul este realizat, noi redesenăm ecranul și gata ”c'est fini” !

Bineînțeles, ați văzut că acest script este foarte simplu (de fapt am făcut unul mai avansat aici here),ați putea dori să-l extindeți, de exemplu importarea obiectelor de tip plasă, sau importarea ”Part Geometry” care nu are fațete sau importul altor formate de fișiere pe care FreeCAD le poate citi. De asemenea, ați putea dori să exportați forme geometrice într-un document FreeCAD, care se poate face în același mod. S-ar putea să doriți, de asemenea, să construiți un dialog, astfel încât utilizatorul să poată alege ce să importe, etc.... Frumusețea tuturor acestor lucruri constă de fapt că l-ai lăsat pe FreeCAD să efectueze în totalitate, prezentându-și în același timp rezultatele în programul pe care l-ai ales .

Using FreeCAD with GUI

From version 4.2 on Qt has the intriguing ability to embed Qt-GUI-dependent plugins into non-Qt host applications and share the host's event loop.

Especially, for FreeCAD this means that it can be imported from within another application with its whole user interface where the host application has full control over FreeCAD, then.

The whole python code to achieve that has only two lines

 
import FreeCADGui 
FreeCADGui.showMainWindow()

If the host application is based on Qt then this solution should work on all platforms which Qt supports. However, the host should link the same Qt version as FreeCAD because otherwise you could run into unexpected runtime errors.

For non-Qt applications, however, there are a few limitations you must be aware of. This solution probably doesn't work together with all other toolkits. For Windows it works as long as the host application is directly based on Win32 or any other toolkit that internally uses the Win32 API such as wxWidgets, MFC or WinForms. In order to get it working under X11 the host application must link the "glib" library.

Note, for any console application this solution of course doesn't work because there is no event loop running.

Caveats

Although it is possible to import FreeCAD to an external Python interpreter, this is not a common usage scenario and requires some care. Generally, it is better to use the Python included with FreeCAD, run FreeCAD via command line, or as a subprocess. See Start up and Configuration for more on the last two options.

Since the FreeCAD Python module is compiled from C++ (rather than being a pure Python module), it can only be imported from a compatible Python interpreter. Generally this means that the Python interpreter must be compiled with the same C compiler as was used to build FreeCAD. Information about the compiler used to build a Python interpreter (including the one built with FreeCAD) can be found as follows:

>>> import sys
>>> sys.version
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'


Scripted objects
Code snippets