Tutorial de programare Python

From FreeCAD Documentation
Revision as of 20:42, 15 August 2018 by Luc (talk | contribs)
Tutorial
Topic
Programming
Level
Intermediate
Time to complete
Authors
FreeCAD version
Example files
See also
None


Python este un limbaj de programare, foarte simplu de utilizat și foarte rapid de învățat. Este open-source, multi-platformă și poate fi folosit singur pentru o gamă largă de lucruri, de la programarea scripturilor simple shell la programele foarte complexe. Dar una dintre cele mai răspândite utilizări este ca un limbaj de scripting, deoarece este ușor de încorporat în alte aplicații. Exact așa este folosit în interiorul FreeCAD. Din consola Python sau din scripturile personalizate, puteți încerca FreeCAD și o puteți face să efectueze acțiuni foarte complexe pentru care nu există încă un instrument grafic de interfață cu utilizatorul.

Dintr-un script Python, de exemplu, puteți:
  • crea obiecte noi
  • modifica obiectele existente
  • modifica reprezentarea 3D a acestor obiecte
  • modifica interfața FreeCAD

Există, de asemenea, mai multe moduri diferite de a folosi Python în FreeCAD:

  • Din FreeCAD python interpreter, unde puteți emite comenzi simple ca într-o interfață "command line"-style interface
  • Din macros, care sunt o modalitate convenabilă de a adăuga rapid o unealtă lipsă la interfața FreeCAD
  • De la scripturi externe, care pot fi folosite pentru a programa lucruri mult mai complexe. ca întreg sistemul de ateliere Workbenches.

În acest tutorial, vom lucra pentru început pe câteva exemple simple, dar există, de asemenea, mult mai multă documentație documentation about python scripting disponibilă pe acest wiki. Dacă sunteți total nou la Python și doriți să înțelegeți cum funcționează, avem de asemenea o bază introduction to Python.

Important! Before proceeding with Python scripting, go to Edit->Prefences->General->Output window and check 2 boxes:

  • Redirect internal Python output to report view
  • Redirect internal Python errors to report view

Then go to View->Panels and check:

  • Report view

This will save you a lot of aggravation!

Scrierea codului python

There are two easy ways to write python code in FreeCAD: From the python console (available from the View -> Panels -> Python console menu) or from the Macro editor (Tools -> Macros). In the console, you write python commands one by one, which are executed when you press return, while the macros can contain a more complex script made of several lines, which is executed only when the macro is executed.

The FreeCAD python console

In this tutorial, you will be able to use both methods, either by copying/pasting each line one by one in the python console and pressing Return after each line, or by copying/pasting the entire code in a new Macro window.

Explorând FreeCAD

Hai să începem prin crearea unui nou document vid:

doc = FreeCAD.newDocument()

If you type this in the FreeCAD python console, you will notice that as soon as you type "FreeCAD.", a windows pops up, allowing to quickly autocomplete the rest of your line. Even better, each entry in the autocomplete list has a tooltip explaining what it does. This makes it very easy to explore the functionality available. Before choosing "newDocument", have a look at the other options available.

The autocomplete mechanism of the FreeCAD python console

Now our new document will be created. This is similar to pressing the "new document" button on the toolbar. In fact, most buttons in FreeCAD do nothing else than executing a line or two of python code. Even better, you can set an option in Edit->Preferences->General->Macro to "show script commands in python console". This will print in the console all python code executed when you press buttons. Very useful to learn how to reproduce actions in python.

Now let's get back to our document. Let's see what we can do with it:

doc.

Explore the available options. Usually names that begin with a capital letter are attributes, they contain a value, while names that begin with small letter are functions (also called methods), they "do something". Names that begin with an underscore are usually there for the internal working of the module, and you shouldn't care about them. Let's use one of the methods to add a new object to our document:

box = doc.addObject("Part::Box","myBox")

Nothing happens. Why? Because FreeCAD is made for the big picture. One day, it will work with hundreds of complex objects, all depending one from another. Making a small change somewhere could have a big impact, you may need to recalculate the whole document, which could take a long time... For that reason, almost no command updates the scene automatically. You must do it manually:

doc.recompute()

See? Now our box appeared! Many of the buttons that add objects in FreeCAD actually do 2 things: add the object, and recompute. If you turned on the "show script commands in python console" option above, try now adding a sphere with the GUI button, you'll see the two lines of python code being executed one after the other.

What about the "Part::Box" will you ask? How can I know what other kind of objects can be added? It's all here:

doc.supportedTypes()

Now let's explore the contents of our box:

box.

You'll immediately see a couple of very interesting things such as:

box.Height

This will print the current height of our box. Now let's try to change that:

box.Height = 5

If you select your box with the mouse, you'll see that in the properties panel, in the "Data" tab, our "Height" property appears. All properties of a FreeCAD object that appear there (and also in the "View" tab, more about that later), are directly accessible by python too, by their names, like we did with the "Height" property. Try changing the other dimensions of that box.

Vectori și Plasamente

Vectors sunt un concept foarte fundamental în orice aplicație 3D. Este o listă cu 3 numere (x, y și z), care descriu un punct sau o poziție în spațiul 3D. O mulțime de lucruri se pot face cu vectori, cum ar fi adăugiri, scăderi, proiecții și much more. In FreeCAD vectorii lucrează cam așa:

myvec = FreeCAD.Vector(2,0,0)
myvec
myvec.x
myvec.y
othervec = FreeCAD.Vector(0,3,0)
sumvec = myvec.add(othervec)

Another common feature of FreeCAD objects is their placement. Each object has a Placement attributes, which contains the position (Base) and orientation (Rotation) of the object. It is easy to manipulate, for example to move our object:

box.Placement
box.Placement.Base
box.Placement.Base = sumvec
 
otherpla = FreeCAD.Placement()
box.Placement = otherpla

Now you must understand a couple of important concepts before we get further.

Apicații și Interfață grafică

FreeCAD de la început a fost conceput pentru a funcționa ca o aplicație pe linie de comandă, fără interfața sa de utilizator. Ca rezultat, aproape totul este separat între o componentă "geometrie" și o componentă "vizuală". Când lucrați în modul de comandă, partea de geometrie este prezentă, dar toată partea vizuală este pur și simplu dezactivată. Aproape orice obiect din FreeCAD este compus din două părți, an Object and a ViewObject.

Pentru a ilustra conceptul, a se vedea obiectul nostru cub, proprietățile geometrice ale cubului, cum ar fi dimensiunile, poziția etc., sunt stocate în obiect, în timp ce proprietățile sale vizuale, cum ar fi culoarea, grosimea liniei etc. sunt stocate în obiectul de vizualizare. Aceasta corespunde fișierelor "Data" și "Veww" din fereastra de proprietăți. Obiectul de vizualizare al unui obiect este accesat astfel:

vo = box.ViewObject

Now you can also change the properties of the "View" tab:

vo.Transparency = 80
vo.hide()
vo.show()

When you start FreeCAD, the python console already loads 2 base modules: FreeCAD and FreeCADGui (which can also be accessed by their shortcuts App and Gui). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both FreeCAD and FreeCADGui contain an ActiveDocument attribute, which is the currently opened document. FreeCAD.ActiveDocument and FreeCADGui.ActiveDocument are not the same object. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example, FreeCADGui.ActiveDocument contains ActiveView, which is the currently opened 3D view

Module

Acum, ar trebui să te întrebi ce, se poate face cu "Part::Box"? Aplicația de bază FreeCAD este mai mult sau mai puțin un container gol. Fără modulele sale, acesta nu poate face decât să creeze noi documente goale. Adevărata putere a FreeCAD este în modulele sale credincioase. Fiecare dintre ele adaugă la interfață nu numai noi aateliere de lucru, ci și noi comenzi python și tipuri noi de obiecte. Ca rezultat, mai multe tipuri de obiecte diferite sau chiar total incompatibile pot coexista în același document. Cele mai importante module din FreeCAD, pe care le vom analiza în acest tutorial, sunt Part, Mesh, Sketcher ori Draft.

Sketcher și Draft amândouă utilizează modulul Part pentru a crea și manipulageometria lor, care este Boundary Representation - BRep Mesh este total independentă și își ocupă propriile obiecte. Mai multe despre acestea sunt în cele de mai jos.

You can check all the available base object types for the current document like this:

doc.supportedTypes()

The different FreeCAD modules, although they added their object types to FreeCAD, are not automatically loaded in the python console. This is to avoid having a very slow startup. Modules are loaded only when you need them. So, for example, to explore what's inside the Part module:

import Part
Part.

But we'll talk more about the Part module below.

By now, you know a bit more about the different modules of FreeCAD: The core modules (FreeCAD, FreeCADGui), and the workbenches modules (Part, Mesh, Sketcher). The other important modules are the 3d scene module (pivy) and the interface module (pyside), we'll talk about them too below.

Now it's time to explore a bit deeper the important ones, which are the workbench modules.

Plase

Meshes sunt un tip foarte simplu de obiecte 3D, folosite de exemplu de Sketchup, Blender or 3D studio Max. Ele sunt compuse din 3 elemente: puncte (numite și vârfuri), linii (numite și margini) și fațete. În multe aplicații, inclusiv în FreeCAD, fațetele pot avea doar 3 noduri. Dar, desigur, nimic nu vă împiedică să aveți o față mai mare plană făcută din mai multe triunghiuri coplanare.

Mesh-urile sunt simple, acest lucru poate fi un lucru rău, însă pentru multe aplicații, cum ar fi cele menționate mai sus, se dovedește a fi un avantaj, deoarece acestea sunt atât de simple încât puteți avea cu ușurință milioane dintr-un singur document. În FreeCAD, totuși, acestea au mai puțină utilizare și sunt mai mult acolo, astfel încât să puteți importa obiecte în formate de plasă (.stl, .obj) din alte aplicații. De asemenea, a fost utilizat extensiv ca modul principal de testare în prima lună a vieții FreeCAD.

Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (like, we'll see below, for Part objects too). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object:

import Mesh
mymesh = Mesh.createSphere()
mymesh.
mymesh.Facets
mymesh.Points
 
meshobj = doc.addObject("Mesh::Feature","MyMesh")
meshobj.Mesh = mymesh
doc.recompute()

This is a standard example, that uses the createSphere() method to automatically create a sphere, but you can very well create custom meshes from scratch, by defining their vertices and faces.

Read more about mesh scripting...

Piese

The Part Module este modulul cel mai puternic al întregului FreeCAD. Permite crearea și manipularea obeictelor BRep. Acest tip de obiect, spre deosebire de Plase cu ochiuri, poate avea o mare varietate de componente. Pentru a rezuma, Brep înseamnă Boundary Representation-Reprezentarea limitelor, ceea ce înseamnă că ele sunt definite de către suprafețele lor, care cuprind și definesc un volum interior. Aceste suprafețe pot fi o varietate de lucruri, cum ar fi fațetele plane sau suprafețele NURBS foarte complexe. Ele poartă, de asemenea, conceptul de volum.

Modulul /Atelierul Piese se bazeză pe putrnica bilbiotecă OpenCasCade bibliotecă, care permite o gamă largă de operații complexe să fie ușor de realizat pe acele obiecte, cum ar fi operațiile booleene, filetarea, lofts etc.

The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object:

import Part
myshape = Part.makeSphere(10)
myshape.
myshape.Volume
myshape.Area

shapeobj = doc.addObject("Part::Feature","MyShape")
shapeobj.Shape = myshape
doc.recompute()

The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and add a shape to it, so you can skip the 3 last lines above:

Part.show(myshape)

By exploring the contents of myshape, you will notice many interesting available subcomponents such as Faces, Edges, Vertexes, Solids or Shells, and a wide range of geometry operations such as cut (subtraction), common (intersection) or fuse (union). The Topological data scripting page explains all that in detail.

Read more about part scripting...

Desen 2 D

FreeCAD features many more modules, such as Sketcher or Draft, care creează, de asemenea, obiecte Piese, dar adaugă parametri sau chiar abordează o nouă modalitate de a gestiona geometria pieselor în ele. Exemplul casetei de mai sus este un exemplu perfect de obiect parametric. Tot ce aveți nevoie, pentru a defini caseta, este să specificați câțiva parametri, cum ar fi înălțimea, lățimea și lungimea. Pe baza acestora, obiectul va calcula automat forma piesei sale. FreeCAD vă permite să create such objects in python.

The Draft Module adds a couple of 2D parametric objects types (which are all Part objects) such as lines and circles, and also provides some generic functions that work not only on Draft-made objects, but on any Part object. To explore what is available, simply do:

import Draft
Draft.
rec = Draft.makeRectangle(5,2)
mvec = FreeCAD.Vector(4,4,0)
Draft.move(rec,mvec)
Draft.move(box,mvec)

Interfață

The FreeCAD user interface is made with Qt, un sistem puternic de interfață grafică, responsabil pentru desenarea și manipularea tuturor comenzilor, meniurilor, barelor de instrumente, butoanelor în jurul vizualizării 3D. Qt oferă un modul, numit PySide, care permite Python-ului să acceseze și să modifice interfețele Qt, cum ar fi FreeCAD. Să încercăm să modificăm interfața Qt și să producem un dialog simplu:

from PySide import QtGui
QtGui.QMessageBox.information(None,"Apollo program","Houston, we have a problem")

Vedeți că dialogul care apare are pictograma FreeCAD din bara de instrumente, ceea ce înseamnă că Qt știe că ordinul a fost emis din interiorul aplicației FreeCAD. Prin urmare, putem manipula direct orice parte a interfeței FreeCAD.

Qt is a very powerful interface system, that allows you to do very complex things, but also has a couple of very easy-to use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a couple of lines of python.

Read more about PySide here...

Macro-uri

Acum, că aveți o bună înțelegere a principiilor de bază, unde vom păstra scripturile noastre Python și cum le vom lansa cu ușurință de pe FreeCAD? Există un mecanism ușor pentru acesta, numit Macros. O macrocomandă este pur și simplu un script python, care poate fi apoi adăugat la o bară de instrumente și poate fi lansat printr-un simplu click de mouse. FreeCAD vă oferă un editor simplu de text (Macro -> Macros -> Creare) unde puteți scrie sau lipi scripturi. După ce s-a terminat, Instrumentele -> Customize -> Macro-urile vă permit să definiți un buton pentru acesta, care poate fi adăugat la barele de instrumente.

Acum sunteți gata pentru mai multă programare/script FreeCAD în profunzime. Deplasați-vă la Power users hub!

Introduction to Python
FreeCAD Scripting Basics