Podstawy tworzenia skryptów FreeCAD
Tworzenie skryptów Python w środowisku FreeCAD
FreeCAD jest zbudowany od podstaw tak, aby być całkowicie kontrolowanym przez skrypty Python. Prawie wszystkie komponenty programu FreeCAD, takie jak interfejs, zawartość sceny, a nawet reprezentacja tej zawartości w widokach 3D, są dostępne z wbudowanego interpretera Pythona lub z własnych skryptów. W rezultacie, FreeCAD jest prawdopodobnie jedną z najgłębiej konfigurowalnych aplikacji inżynierskich dostępnych obecnie.
Jeśli nie znasz Pythona, zalecamy poszukać poradników w internecie i szybko zapoznać się z jego strukturą. Python jest bardzo łatwym językiem do nauki, zwłaszcza, że może być uruchamiany wewnątrz interpretera, gdzie proste polecenia, aż do kompletnych programów, mogą być wykonywane w locie, bez konieczności kompilowania czegokolwiek. FreeCAD posiada wbudowany interpreter Pythona. Jeśli nie widzisz okna oznaczonego jako konsola Pythona, jak pokazano poniżej, możesz go aktywować pod menu Widok → Panele → konsola Python.
Interpreter
Z poziomu interpretera masz dostęp do wszystkich zainstalowanych w systemie modułów Pythona, jak również do wbudowanych modułów FreeCAD oraz wszystkich dodatkowych modułów FreeCAD, które zainstalowałeś później. Poniższy zrzut ekranu przedstawia interpreter Pythona:
Z poziomu interpretera można wykonać kod Python i przeglądać dostępne klasy i funkcje. FreeCAD zapewnia bardzo poręczną przeglądarkę klas do eksploracji: Po wpisaniu nazwy znanej klasy, po której następuje kropka (co oznacza, że chcesz dodać coś z tej klasy), otwiera się okno przeglądarki klas, gdzie możesz poruszać się pomiędzy dostępnymi podklasami i metodami. Kiedy coś wybierzesz, wyświetli się powiązany tekst pomocniczy (jeśli istnieje):
Więc, zacznij od wpisania App.
albo Gui.
i zobacz co się stanie. Innym, bardziej ogólnym sposobem eksplorowania zawartości modułów i klas w Pythonie jest użycie polecenia print(dir())
. Na przykład, wpisanie print(dir())
wyświetli listę wszystkich modułów aktualnie załadowanych w FreeCAD. print(dir(App))
pokaże ci wszystko wewnątrz modułu App, itd.
Kolejną przydatną funkcją interpretera jest możliwość cofnięcia się przez całą historię poleceń i odtworzenia linii kodu, którą już wcześniej wpisałeś. Aby poruszać się po historii poleceń, wystarczy użyć klawisza Strzałka w górę lub Strzałka w dół.
Klikając prawym przyciskiem myszy w oknie interpretera, masz również kilka innych opcji, takich jak skopiowanie całej historii (przydatne, gdy chcesz eksperymentować z rzeczami przed utworzeniem pełnego skryptu), lub wstawienie nazwy pliku z pełną ścieżką.
Pomoc dla Pythona
W menu FreeCAD Pomoc znajdziesz wpis oznaczony Automatyczna dokumentacja modułów Python, który otworzy okno przeglądarki zawierające pełną, rzeczywistą dokumentację wszystkich modułów Pythona dostępnych dla interpretera FreeCAD, w tym modułów wbudowanych Pythona i FreeCAD, modułów zainstalowanych w systemie oraz modułów dodatkowych FreeCAD. Dostępna tam dokumentacja jest uzależniona od tego, ile wysiłku każdy programista wkłada w dokumentację swojego kodu, ale moduły Python mają reputację dość dobrze udokumentowanych. Okno Twojego FreeCAD musi pozostać otwarte, aby ten system dokumentacji mógł działać. Wprowadzenie do dokumentacji skryptowej Python zapewni Ci szybki link do sekcji wiki Centrum Power użytkownika.
Moduły wbudowane
Ponieważ FreeCAD został zaprojektowany tak, aby mógł być uruchamiany również bez graficznego interfejsu użytkownika (GUI), prawie cała jego funkcjonalność jest podzielona na dwie grupy: Podstawowa funkcjonalność, nazwana App
, oraz funkcjonalność GUI, nazwana Gui
. Te dwa moduły mogą być również dostępne ze skryptów poza interpreterem, odpowiednio o nazwach FreeCAD
i FreeCAD
.
- W module
App
znajdziesz wszystko, co jest związane z samą aplikacją, np. Metody otwierania lub zamykania plików oraz dokumentów, takie jak ustawianie aktywnego dokumentu lub lista ich zawartości.
- W module
Gui
znajdziesz narzędzia do uzyskiwania dostępu i zarządzania elementami Gui, takimi jak Środowiska pracy i ich paski narzędzi oraz, co ciekawsze, graficzną reprezentację całej zawartości FreeCAD.
Listowanie zawartości tych modułów nie jest zbyt przydatne, ponieważ rozwijają się one dość szybko w miarę rozwoju FreeCAD. Ale dwa dostarczone narzędzia do przeglądania (przeglądarka klasy i pomoc dla Pythona) powinny w każdej chwili dostarczyć Ci kompletną i aktualną dokumentację.
Obiekty App i Gui
As already mentioned, in FreeCAD everything is separated into core and representation. This includes the 3D objects. You can access defining properties of objects (called features in FreeCAD) via the App
module, and change the way they are represented on screen via the Gui
module. For example, a cube has properties that define it (like width, length, height) that are stored in an App
object, and representation properties (like faces color, drawing mode) that are stored in a corresponding Gui
object.
This way of doing things allows a very wide range of uses, like having algorithms work only on the definition part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis.
For every App
object in your document, there exists a corresponding Gui
object. In fact the document itself has both an App
and a Gui
object. This, of course, only applies when you run FreeCAD with its full interface. In the command-line version no GUI exists, so only App
objects are available. Note that the Gui
part of objects is re-generated every time an App
object is marked as 'to be recomputed' (for example when one of its parameters changes), so any changes made directly to the Gui
object may be lost.
To access the App
part of something, you type:
myObject = App.ActiveDocument.getObject("ObjectName")
where "ObjectName"
is the name of your object. You can also type:
myObject = App.ActiveDocument.ObjectName
To access the Gui
part of the same object, you type:
myViewObject = Gui.ActiveDocument.getObject("ObjectName")
where "ObjectName"
is the name of your object. You can also type:
myViewObject = App.ActiveDocument.ObjectName.ViewObject
If you are in command-line mode and have no GUI, the last line will return None
.
The Document objects
In FreeCAD all your work resides inside documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App
and Gui
objects. The App
object contains your actual geometry definitions, while the Gui
object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or from a different direction. These views are all part of your document's Gui
object.
To access the App
part of the currently open (active) document, you type:
myDocument = App.ActiveDocument
To create a new document, type:
myDocument = App.newDocument("Document Name")
To access the Gui
part of the currently open (active) document, you type:
myGuiDocument = Gui.ActiveDocument
To access the current view, you type:
myView = Gui.ActiveDocument.ActiveView
Using additional modules
The FreeCAD
and FreeCADGui
modules are only responsible for creating and managing objects in the FreeCAD document. They don't actually do anything more such as creating or modifying geometry. This is because that geometry can be of several types, and therefore requires additional modules, each responsible for managing a certain geometry type. For example, the Part Module, using the OpenCascade kernel, is able to create and manipulate BRep type geometry. Whereas the Mesh Module is able to build and modify mesh objects. In this manner FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types can easily be added in the future.
Creating objects
Each module has its own way of dealing with geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:
FreeCAD.ActiveDocument.supportedTypes()
will list all possible objects you can create. For example, let's create a mesh (handled by the Mesh
module) and a part (handled by the Part
module):
myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "myMeshName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature", "myPartName")
The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh)
and dir(myPart)
. Except for one thing, myMesh
has a Mesh
property and myPart
has a Shape
property. That is where the Mesh and Part data are stored. For example, let's create a Part
cube and store it in our myPart
object:
import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube
You could try storing the cube inside the Mesh
property of the myMesh
object, but it will return an error. That is because each properties is made to store only a certain type. In a Mesh
property, you can only save stuff created with the Mesh
module. Note that most modules also have a shortcut to add their geometry to the document:
import Part
cube = Part.makeBox(2, 2, 2)
Part.show(cube)
Modifying objects
Modifying an object is done in the same way:
import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube
Now let's change the shape by a bigger one:
biggercube = Part.makeBox(5, 5, 5)
myPart.Shape = biggercube
Querying objects
You can always look at the type of an object like this:
myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
print(myObj.TypeId)
or check if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):
print(myObj.isDerivedFrom("Part::Feature"))
Now you can really start playing with FreeCAD! For a complete list of available modules and their tools, visit the Category:API section.
- Tworzenie skryptów FreeCAD: Python, Wprowadzenie do środowiska Python, Poradnik: Tworzenie skryptów Python, Podstawy tworzenia skryptów FreeCAD
- Moduły: Moduły wbudowane, Jednostki miar, Ilość
- Środowiska pracy: Tworzenie Środowiska pracy, Polecenia Gui, Polecenia, Instalacja większej liczby Środowisk pracy
- Siatki i elementy: Skrytpy w Środowisku Siatek, v, Konwerska Mesh na Part, PythonOCC
- Obiekty parametryczne: Obiekty tworzone skryptami, Obsługa obrazu (Ikonka niestandardowa w widoku drzewa)
- Scenegraph: Coin (Inventor) scenegraph, Pivy
- Interfejs graficzny: Stworzenie interfejsu, Kompletne stworzenie interfejsu w środowisku Python (1, 2, 3, 4, 5), PySide, PySide examples początkujący, średniozaawansowany, zaawansowany
- Makrodefinicje: Makrodefinicje, Instalacja makrodefinicji
- Osadzanie programu: Osadzanie programu FreeCAD, Osadzanie GUI FreeCAD
- Pozostałe: Wyrażenia, Wycinki kodu, Funkcja kreślenia linii, Biblioteka matematyczna FreeCAD dla wektorów (deprecated)
- Węzły użytkowników: Centrum użytkownika, Centrum Power użytkowników, Centrum programisty