Python scripting tutorial/pl: Difference between revisions

From FreeCAD Documentation
(Created page with "Inną wspólną cechą obiektów FreeCAD jest ich umiejscowienie. Każdy obiekt posiada właściwość {{PropertyData|Umiejscowienie}}, która zawiera {{PropertyData|Baze}} ''(położenie)'' i {{PropertyData|Obrót}} ''(orientacja)'' obiektu. Jest to łatwe do manipulowania, na przykład w celu przesunięcia naszego obiektu:")
(Created page with "Zanim przejdziemy dalej, musisz zrozumieć kilka ważnych pojęć.")
Line 122: Line 122:
}}
}}


Zanim przejdziemy dalej, musisz zrozumieć kilka ważnych pojęć.
Now you must understand a couple of important concepts before we get further.
{{Top}}
{{Top}}
==App and Gui==
==App and Gui==

Revision as of 18:34, 29 January 2024

Wprowadzenie

Python to język programowania, który jest stosunkowo łatwy do nauczenia i zrozumienia. Jest open-source i wieloplatformowy i może być używany do wielu celów: od prostych skryptów powłoki do bardzo złożonych programów. Ale jego najbardziej rozpowszechnionym zastosowaniem jest język skryptowy osadzony w innych aplikacjach. W ten sposób jest on używany wewnątrz FreeCAD. Z poziomu konsoli Python lub niestandardowych skryptów można kontrolować FreeCAD i wykonywać bardzo złożone operacje.

Na przykład, ze skryptu Python można:

  • Tworzyć nowe obiekty.
  • Modyfikować istniejące obiekty.
  • Modyfikować reprezentację 3D tych obiektów.
  • Modyfikować interfejs FreeCAD.

Istnieje kilka sposobów korzystania ze środowiska Python w FreeCAD:

  • Z Podstawy tworzenia skryptów FreeCAD, gdzie można wydawać polecenia w interfejsie w stylu "wiersza poleceń".
  • Z makrodefinicji, które są wygodnym sposobem na szybkie dodanie brakującego narzędzia do interfejsu FreeCAD.
  • Z zewnętrznych skryptów, które mogą być używane do tworzenia dość złożonych rozwiązań, nawet całych środowisk pracy.

W tym samouczku będziemy pracować nad kilkoma podstawowymi przykładami, aby zacząć, ale jest o wiele więcej dokumentacji na temat skryptów dostępnych na tej Wiki. Jeśli jesteś zupełnie nowy w środowisku Python i chcesz zrozumieć, jak ono działa, mamy również podstawowe wprowadzenie do środowiska Python.

Przed przystąpieniem do tworzenia skryptów w Pythonie, przejdź do Edycja → Preferencje ... → Ogólne → Widok raportu i zaznacz dwa pola:

  • Przekieruj wiadomości wewnętrzne środowiska Python do Widoku raportu.
  • Przekieruj błędy wewnętrzne środowiska Python do Widoku raportu.

Następnie przejdź do Widok → Panele i zaznacz:

  • Widoku raportu.

Pisanie kodu Python

Istnieją dwa sposoby pisania kodu Python w FreeCAD. W konsoli Python (wybierz z menu Widok → Panele → Konsola Python) lub w Edytorze makrodefinicji (wybierz z menu Makrodefinicje → Makrodefinicje ...). W konsoli piszesz komendy Python jedna po drugiej, wykonując je poprzez naciśnięcie Enter, podczas gdy makra mogą zawierać bardziej złożony kod składający się z kilku linii, wykonywany tylko wtedy, gdy makro jest wykonywane.

Konsola Python programu FreeCAD

W tym samouczku możesz użyć obu metod. Możesz skopiować i wkleić każdą linię w konsoli Python, a następnie nacisnąć Enter, lub skopiować i wkleić cały kod w nowym oknie Makrodefinicji.

Przewiń na górę strony

Poznaj program FreeCAD od środka

Zacznijmy od utworzenia nowego pustego dokumentu:

doc = FreeCAD.newDocument()

Jeśli wpiszesz to w konsoli FreeCAD Python, zauważysz, że jak tylko wpiszesz FreeCAD., pojawi się okno, pozwalające na szybkie autouzupełnianie reszty linii. Co więcej, każdy wpis na liście autouzupełniania ma etykietkę wyjaśniającą, co robi. Ułatwia to zapoznanie się z dostępnymi funkcjami. Zanim wybierzesz newDocument, zapoznaj się z innymi opcjami.

Mechanizm autouzupełniania dostępny w konsoli FreeCAD dla Python.

Teraz nasz nowy dokument zostanie utworzony. Jest to podobne do naciśnięcia przycisku Nowy na pasku narzędzi. W rzeczywistości większość przycisków w FreeCAD nie robi nic więcej niż wykonanie jednej lub więcej linii kodu Pythona. Co więcej, można ustawić opcję w Edycja → Preferencje → Python → Makrodefinicje na Pokaż polecenia skryptu w konsoli Python. Spowoduje to wypisanie w konsoli całego kodu Python wykonanego po naciśnięciu przycisków. Bardzo przydatne do nauki odtwarzania akcji w Pythonie.

Wróćmy teraz do naszego dokumentu i zobaczmy, co możemy z nim zrobić:

doc.

Zapoznaj się z dostępnymi opcjami. Zazwyczaj nazwy rozpoczynające się wielką literą są atrybutami, zawierają wartość, podczas gdy nazwy rozpoczynające się małą literą są funkcjami (zwanymi również metodami), "robią coś". Nazwy zaczynające się od podkreślenia są zwykle przeznaczone do wewnętrznego działania modułu i nie należy się nimi przejmować. Użyjmy jednej z metod, aby dodać nowy obiekt do naszego dokumentu:

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

Nic się nie dzieje. Dlaczego? Ponieważ FreeCAD został stworzony z myślą o dużym obrazie. Pewnego dnia będzie pracował z setkami złożonych obiektów, z których wszystkie będą od siebie zależne. Dokonanie gdzieś małej zmiany może mieć duży wpływ. Może być konieczne ponowne obliczenie całego dokumentu, co może zająć dużo czasu. Z tego powodu prawie żadne polecenie nie aktualizuje sceny automatycznie. Trzeba to robić samodzielnie:

doc.recompute()

Teraz pojawił się nasz prostopadłościan. Wiele przycisków dodających obiekty w FreeCAD wykonuje w rzeczywistości dwie czynności: dodanie obiektu i ponowne obliczenie. Jeśli włączyłeś opcję Pokaż polecenia skryptu w konsoli Python powyżej, spróbuj dodać kulę za pomocą przycisku GUI. Zobaczysz dwie linie kodu Python wykonywane jedna po drugiej.

Teraz przyjrzyjmy się zawartości naszego prostopadłościanu:

box.

Od razu zobaczysz kilka bardzo interesujących rzeczy, takich jak:

box.Height

Spowoduje to wyświetlenie bieżącej wysokości naszego prostopadłościanu. Teraz spróbujmy to zmienić:

box.Height = 5

Jeśli wybierzesz swój prostopadłościan za pomocą myszy, zobaczysz, że w Edytorze właściwości, na karcie Dane, pojawi się nasza właściwość DANEWysokość. Wszystkie właściwości obiektu FreeCAD, które się tam pojawiają (a także w zakładce Widok, więcej o tym później), są również bezpośrednio dostępne w Python, poprzez ich nazwy, tak jak zrobiliśmy to z właściwością DANEWysokość. Spróbuj zmienić inne wymiary prostopadłościanu.

Przewiń na górę strony

Wektory i umiejscowienia

Wektory to bardzo podstawowe pojęcie w każdej aplikacji 3D. Wektor to lista 3 liczb (x, y i z) opisujących punkt lub pozycję w przestrzeni 3D. Z wektorami można zrobić wiele rzeczy, takich jak dodawanie, odejmowanie, rzutowanie i wiele więcej. W FreeCAD wektory działają w następujący sposób:

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

Inną wspólną cechą obiektów FreeCAD jest ich umiejscowienie. Każdy obiekt posiada właściwość DANEUmiejscowienie, która zawiera DANEBaze (położenie) i DANEObrót (orientacja) obiektu. Jest to łatwe do manipulowania, na przykład w celu przesunięcia naszego obiektu:

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

Zanim przejdziemy dalej, musisz zrozumieć kilka ważnych pojęć.

Przewiń na górę strony

App and Gui

FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an Object, its "geometry" component, and a ViewObject, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled.

To illustrate the concept let's look at 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 editor. The view object of an object is accessed like this:

vo = box.ViewObject

Now you can also change the properties on the View tab:

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

When you start FreeCAD, the Python console already loads two 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 however. 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.

Przewiń na górę strony

Modules

The true power of FreeCAD lies in its faithful modules, with their respective workbenches. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and 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 and Draft.

Sketcher and Draft both use the Part module to create and handle their geometry. 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:

doc.supportedTypes()

The different FreeCAD modules 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.

Przewiń na górę strony

Mesh module

Meshes are a very simple kind of 3D object, used for example by Sketchup, Blender and 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. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles.

Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. The Mesh module 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 (and as we'll see below, for Part objects also). 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.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 create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces.

Read more about mesh scripting...

Przewiń na górę strony

Moduł Część

The Part module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate BRep objects. BREP stands for "Boundary Representation". A BREP object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BREP objects can have a wide variety of components from planar faces to very complex NURBS surfaces.

The Part module is based on the powerful OpenCasCade library, which allows a wide range of complex operations to be 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:

import Part
myshape = Part.makeSphere(10)
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 adds a shape to it, so you can shorten the last three lines to:

Part.show(myshape)

By exploring the contents of myshape, you will notice many interesting subcomponents such as Faces, Edges, Vertexes, Solids and 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...

Przewiń na górę strony

Moduł rysunku Roboczego

FreeCAD features many more modules, such as Sketcher and Draft, that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters 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 2D parametric object types (which are all Part objects) such as lines and circles, and also provides some generic functions that not only work on Draft objects, but on any Part object. To explore what is available, simply do:

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

Przewiń na górę strony

Interfejs

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

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

Notice 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. It is possible to manipulate any part of the FreeCAD interface.

Qt is a very powerful interface system that allows you to do very complex things. It also has some 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 few lines of Python code.

Read more about PySide here...

Przewiń na górę strony

Makrodefinicje

Now that you have a good understanding of the basics, where are we going to keep our Python scripts, and how are we going to launch them inside FreeCAD? There is an easy mechanism for that, called Macros. A macro is a Python script that can be added to a toolbar and launched via a mouse click. FreeCAD provides you with a simple text editor (Macro → Macros... → Create) where you can write or paste scripts. Once the script is done, use Tools → Customize... → Macros to define a button for it that can be added to toolbars.

Skrypty zewnętrzne

An alternative method for creating, saving, and running your own Python scripts is to create them outside FreeCAD, using an editor of your choice (for example, Vim). To run your Python script inside FreeCAD, be sure to save it with the .py extension.

Then use File → Open to open your script. It will load into a new tab in the Main view area. You can run your script by clicking the Execute macro button. Any errors or script output will be shown in the Report view.

When you make and save any modifications to your already-loaded script, a dialog box will appear asking whether you want to reload the modified script into FreeCAD.

You can continue to the FreeCAD Scripting Basics page, or you can access that page and other relevant pages at the Power users hub.

Przewiń na górę strony