Python scripting tutorial/ro

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 window and check 2 boxes: Then go to and check: This will save you a lot of aggravation!
 * Redirect internal Python output to report view
 * Redirect internal Python errors to report view
 * Report view

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.



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 after each line, or by copying/pasting the entire code in a new Macro window.

Explorând FreeCAD
Let's start by creating a new empty document:

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.



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 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:

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:

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:

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:

Now let's explore the contents of our box:

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

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

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 are a very fundamental concept in any 3D application. It is a list of 3 numbers (x, y and z), describing a point or position in the 3D space. A lot of things can be done with vectors, such as additions, subtractions, projections and much more. In FreeCAD vectors work like this:

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:

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

Apicații și Interfață grafică
FreeCAD is made from the beginning to work as a command-line application, without its user interface. As a result, almost everything is separated between a "geometry" component and a "visual" component. When you work in command-line mode, the geometry part is present, but all the visual part is simply disabled. Almost any object in FreeCAD therefore is made of two parts, an Object and a ViewObject.

To illustrate the concept, see our cube object, the geometric properties of the cube, such as its dimensions, position, etc... are stored in the object, while its visual properties, such as its color, line thickness, etc... are stored in the viewobject. This corresponds to the "Data" and "View" tabs in the property window. The view object of an object is accessed like this:

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

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
Now, you must be wondering, what, other than "Part::Box", can I do? The FreeCAD base application is more or less an empty container. Without its modules, it can do little more than create new, empty documents. The true power of FreeCAD is in its faithful modules. Each of them adds not only new workbenches to the interface, but also new python commands and new object types. As a result, several different or even totally incompatible object types can coexist in the same document. The most important modules in FreeCAD, that we'll look at in this tutorial, are Part, Mesh, Sketcher or Draft.

Sketcher and Draft both use the Part module to create and handle their geometry, which are BRep while Mesh is totally independent, and handles its own objects. More about that below.

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

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:

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 are a very simple kind of 3D objects, used for example by Sketchup, Blender or 3D studio Max. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. But of course nothing prevents you from having a bigger plane face made of several coplanar triangles.

Meshes are simple, this can be a bad thing, but for many applications such as those mentioned above, it turns to be an advantage, because they are so simple that you can easily have millions of them in a single document. In FreeCAD, though, they have less use, and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. It was also used extensively as the main test module in the first month of FreeCAD's life.

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:

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 is the most powerful module of the whole FreeCAD. It allows to create and manipulate BRep objects. This kind of object, unlike meshes, can have a wide variety of components. To resume a bit, Brep means Boundary Representation. which means that they are defined by their surfaces, which enclose and define an inner volume. These surface can be a variety of things, such as plane faces or very complex NURBS surfaces. They also carry the concept of volume.

The Part module is based on the powerful OpenCasCade library, which allows a wide range of complex operations to be easily performed on those objects, such as boolean operations, filleting, 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:

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:

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, which also create Part objects, but add parameters to it, or even carry a whole new way to handle the Part geometry in them. Our box example above, is a perfect example of parametric object. All you need, to define the box, is to specify a couple of parameters, such as height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to 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:

Interfață
The FreeCAD user interface is made with Qt, a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars, buttons around the 3D view. Qt provides a module, called PySide, which allows python to access and modify Qt interfaces, such as FreeCAD. Let's try to fiddle with the Qt interface and produce a simple dialog:

See that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. We can therefore easily directly manipulate any part of the FreeCAD interface.

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!