Руководство по скриптам Python

From FreeCAD Documentation
Revision as of 14:00, 23 February 2019 by FuzzyBot (talk | contribs) (Updating to match new version of source page)
Introduction to Python
FreeCAD Scripting Basics
Руководство
Тема
Programming
Уровень
Intermediate
Время для завершения
Авторы
FreeCAD версия
Примеры файлов
Смотрите также
None


Python - это язык программирования, очень простой в использовании и изучении. Он является многоплатформенным языком с открытым исходным кодом и может использоваться для в разных областях - от программирования простых скриптов до очень сложных программ. Но он наиболее распространен как язык сценариев, из-за легкости внедрения в другие приложения. Именно так он используется внутри FreeCAD. Из python консоли или с помощью собственных скриптов вы можете управлять FreeCAD, заставляя его выполнять очень сложные действия, для которых еще нет GUI (графического пользовательского интерфейса)инструментов.

Например, из python сценария вы можете:

  • создать новые объекты
  • изменить существующие объекты
  • изменить трехмерное представление этих объектов
  • изменить интерфейс FreeCAD

Существует несколько способов использования python в FreeCAD:

  • Из Интерпретатора python в FreeCAD, где вы можете запускать простые команды, симулируя интерфейс командной строки
  • Из макросов, которые являются удобным способом быстрого добавления недостающего функционала в интерфейс FreeCAD
  • Из внешних скриптов, которые можно использовать для программирования более сложных вещей, таких как Верстаки.

В этом руководстве мы рассмотрим несколько простых примеров, которые помогут вам начать работу. В этой вики также имеется гораздо больше документации по python сценариям. Если вы абсолютный новичок в python и хотите понять, как это работает, у нас есть базовый курс Введение в Python.

"'Важно!'" Перед написанием Python сценариев, перейдите в окно Edit-> Prefences-> General-> Output и проверьте 2 пункта:

  • Перенаправить внутренний вывод Python в отчет
  • Перенаправить внутренние ошибки Python в отчет

Затем перейдите в View-> Panels и проверьте:

  • Отчет

Это сэкономит вам много нервов!

Написание python кода

Существует два простых способа написания Python кода в FreeCAD: в python консоли (меню «Вид-> Панели -> Консоль Python») или из редактора макросов (Инструменты -> Макросы). В консоли вы последовательно пишете python команды, которые выполняются при нажатии return. Макросы могут содержать более сложный много-строчный скрипт, который выполняется во время запуска макроса.

The FreeCAD python console

В этом руководстве описаны оба метода: либо путем копирования / вставки по одной строчке в python консоли и нажатия Return в конце строки, либо путем копирования / вставки всего кода в новое окно макроса.

Изучение FreeCAD

Начнем с создания нового пустого документа:

doc = FreeCAD.newDocument()

Если Вы вводите это в python консоли FreeCADа, то заметите, что как только Вы ввели "FreeCAD." (слово FreeCAD с последующей точкой), появится окно, позволяющее быстро автозаполнить продолжение строки. Даже лучше, каждый ввод в списке автодополнения содержит подсказку. Это облегчает раскрытие имеющейся функциональности. Перед выбором "newDocument", взгляните на другие доступные опции.

Механизм автозаполнения python консоли FreeCAD

Теперь наш новый документ будет создан. Это похоже на нажатие кнопки «новый документ» на панели инструментов. Фактически, большинство кнопок в FreeCAD ничего не делают, кроме выполнения строки или двух python кода. Еще лучше, вы можете установить параметр в Edit-> Preferences-> General-> Macro, чтобы «показать команды сценария в консоли python». Это будет выводить в консоль весь python код, который выполняется при нажатии кнопок. Очень полезно узнать, как воспроизводить действия в python.

Теперь вернёмся назад в документ. Посмотрим, что мы можем с ним сделать:

doc.

Изучим доступные варианты. Обычно имена, начинающиеся с заглавной буквы, это атрибуты, они содержат значения, а имена с маленькой буквы являются функциями (называемые так же методами), они "что-то делают". Имена, начинающиеся с подчёркиваний, обычно используются для внутренних нужд модуля, и Вам не следует обращать на них внимание. Используем один из методов для добавления в документ нового объекта:

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

Ничего не произошло. Почему? Потому что FreeCAD создан для больших проектов. Однажды он будет работать с сотнями сложных взаимосвязанных объектов. Возможно, что внесение небольшого изменения может иметь большое значение, вам может потребоваться пересчитать весь документ, что может занять много времени ... По этой причине почти никакая команда не обновляет сцену автоматически. Вы должны сделать это вручную:

doc.recompute()

Теперь наш куб появился в окне трёхмерного вида. Большинство кнопок панелей инструментов фактически делают две вещи: добавляют объект и выполняют рекомпиляцию. Если Вы включите в настройках опцию "Показывать команды скриптов в консоли python" и попробуете добавить сферу с соответствующей кнопкой, Вы увидите две строки python кода, выполняемые одна за другой.

Вы спросите, как насчет «Part :: Box»? Как мне узнать, как добавить другие объекты? Все здесь:

doc.supportedTypes()

Теперь рассмотрим содержимое нашего куба:

box.

Вы немедленно увидите несколько очень интересных вещей вроде этого:

box.Height

Это покажет текущую высоту нашего куба. Теперь попробуем её изменить:

box.Height = 5

Если вы выберете куб с помощью мыши, вы увидите, что на панели свойств на вкладке «Данные» появится параметр «Высота». Все свойства объекта FreeCAD, которые появляются там (а также на вкладке «Вид», подробнее об этом позже), напрямую доступны также для python по их именам, аналогично параметру «Высота». Попробуйте изменить другие размеры этого окна.

Vectors and Placements

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:

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.

App and Gui

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:

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

Modules

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

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 workbench 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.

Mesh

Meshes are a very simple kind of 3D object, 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. Of course, nothing prevents you from having a bigger plane face made 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.
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 also create custom meshes from scratch by defining their vertices and faces.

Read more about mesh scripting...

Part

The Part Module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate BRep objects. This kind of object, unlike meshes, can have a wide variety of components. Brep stands for Boundary Representation, which means that Brep objects are defined by their surfaces; those surfaces enclose and define an inner volume. A surface can be a variety of things such as plane faces or very complex NURBS surfaces.

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:

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 adds a shape to it, so you can shorten the last three lines above 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...

Draft

FreeCAD features many more modules, such as Sketcher and Draft, which 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 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)

Interface

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

Macros

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 easily from FreeCAD? There is an easy mechanism for that, called Macros. A macro is simply 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 → Customiz → Macros to define a button for it that can be added to toolbars.

Now you are ready for more in-depth FreeCAD scripting. Head on to the Power users hub!

Introduction to Python
FreeCAD Scripting Basics