Extra python modules/es

El interprete de Python dentro de FreeCAD puede extenderse fácilmente añadiendo nuevos módulos a tu instalación de Python. Esos módulos se detectarán automáticamente y utilizarán por FreeCAD.

Todos los módulos de Python se pueden utilizar desde FreeCAD, pero algunos de ellos, listados abajo, tienen una importancia especial porque permiten a los programas de Python tener acceso completo a las funcionalidades principales de FreeCAD. También se pueden encontrar ejemplos de uso de dichos módulos en la página de Pedazos de código.

Nota: de los siguientes módulos, Pivy está ahora integrado por completo en cualquier paquete de instalación de FreeCAD, y PyQt4 también está integrado en el paquete de instalación de Windows.

PyQt4
Web: http://www.riverbankcomputing.co.uk/pyqt

PyQt (versión 4) es una biblioteca de vinculación de Python que permite a los programas acceder, crear o modificar interfaces Qt. Ya que la interfaz de FreeCAD está construida con Qt, la instalación de PyQt4 en tu sistema permitirá a los programas de Python dentro de FreeCAD acceder a todos los interfaces, modificar sus partes, crear nuevos complementos (widgets) o recoger información desde partes del interfaz.

PyQt se distribuye bajo un sistema de múltiples licencias, el mismo sistema que es utilizado por Qt. En resumen, existe una versión comercial y una versión libre GPL. Si quieres utilizarlo para crear aplicaciones comerciales (de código cerrado), necesitas comprar la licencia comercial, en otro caso puedes simplemente instalar y utilizar libremente la versión GPL.

Instalación
Antes de la instalación de PyQt4, obviamente necesitas un entorno de Python instalado y trabajando.

Linux

The simplest way to install PyQt4 is through your distribution's package manager. On Debian/Ubuntu systems, the package name is generally python-qt4, while on RPM-based systems it is named pyqt4. The necessary dependencies (Qt and SIP) will be taken care of automatically.

Windows

The program can be downloaded from here. You'll need to install the Qt and SIP libraries before installing pyqt4 (to be documented).

Usage
Once it is installed, you can check that everything is working by typing in FreeCAD python console:

import PyQt4

To access the FreeCAD interface, type:

from PyQt4 import QtCore,QtGui app = QtGui.qApp FreeCADWindow = app.activeWindow

Now you can start to explore the interface with the dir command. You can add new elements, like a custom widget, with commands like:

FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)

Documentation
More pyQt4 tutorials (including how to build interfaces with Qt Designer to use with python):

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html - the official PyQt4 API Reference

http://www.rkblog.rk.edu.pl/w/p/introduction-pyqt4/ - a simple introduction

http://www.zetcode.com/tutorials/pyqt4/ - very complete in-depth tutorial

Pivy
homepage: http://pivy.coin3d.org/

Pivy is a coin bindings library for python, officially supported by coin. Coin itself is a toolkit for building 3D applications in OpenGL. It is the toolkit that FreeCAD uses to draw its 3d Scene on the screen. Installing Pivy on your system will allow python programs to access the FreeCAD scenegraph, draw new objects on the scene and use the wide range of available Coin tools for drawing operations. Coin is based on the open Inventor scene description language. Pivy is used by the 2D drafting module of FreeCAD (and also by the complete module), so it is needed if you want to use any tool of those modules.

It is important to know that FreeCAD only uses coin for representation of objects on the screen, which is separated from the definition of objects. This means that pivy won't be able to modify existing objects, neither to create valid FreeCAD objects. But it can be used to draw all kind of temporary things on screen, such as axis, grids, manipulators, construction geometry, etc...

Pivy, as well as Coin, is released under a GPL license.

Debian & Ubuntu
Starting with Debian Squeeze and Ubuntu Lucid, pivy will be available directly from the official repositories, saving us a lot of hassle. In the meantime, you can either download one of the packages we made (for debian and ubuntu karmic) availables on the Download pages, or compile it yourself.

The best way to compile pivy easily is to grab the debian source package for pivy and make a package with debuild. It is the same source code from the official pivy site, but the debian people made several bug-fixing additions. It also compiles fine on ubuntu karmic: http://packages.debian.org/squeeze/python-pivy (download the .orig.gz and the .diff.gz file, then unzip both, then apply the .diff to the source: go to the unzipped pivy source folder, and apply the .diff patch: patch -p1 < ../pivy_0.5.0~svn765-2.diff then debuild to have pivy properly built into an official installable package. Then, just install the package with gdebi.

Other linux distributions
First get the latest sources from the project's repository: svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy Then you need a tool called SWIG to generate the C++ code for the Python bindings. It is recommended to use version 1.3.25 of SWIG, not the latest version, because at the moment pivy will only function correctly with 1.3.25. Download a 1.3.25 source tarball from http://www.swig.org. Then unpack it and from a command line do (as root): ./configure make make install (or checkinstall if you use it) It takes just a few seconds to build. After that go to the pivy sources and call python setup.py build which creates the source files. You may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix. After that, install by issuing (as root): python setup.py install (or checkinstall python setup.py install) That's it, pivy is installed.

Windows
Assuming your are using Visual Studio 2005 or later you should open a command prompt with 'Visual Studio 2005 Command prompt' from the Tools menu. If the Python interpreter is not yet in the system path do set PATH=path_to_python_2.5;%PATH%

To get pivy working you should get the latest sources from the project's repository: svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy Then you need a tool called SWIG to generate the C++ code for the Python bindings. It is recommended to use version 1.3.25 of SWIG, not the latest version, because at the moment pivy will only function correctly with 1.3.25. Download the binaries for 1.3.25 from http://www.swig.org. Then unpack it and from the command line add it to the system path set PATH=path_to_swig_1.3.25;%PATH% and set COINDIR to the appropriate path set COINDIR=path_to_coin

On Windows the pivy config file expects SoWin instead of SoQt as default. I didn't find an obvious way to build with SoQt, so I modified the file setup.py directly. In line 200 just remove the part 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (do not remove the closing parenthesis).

After that go to the pivy sources and call python setup.py build which creates the source files. You may run into a compiler error several header files couldn't be found. In this case adjust the INCLUDE variable set INCLUDE=%INCLUDE%;path_to_coin_include_dir and if the SoQt headers are not in the same place as the Coin headers also set INCLUDE=%INCLUDE%;path_to_soqt_include_dir and finally the Qt headers set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

If you are using the Express Edition of Visual Studio you may get a python keyerror exception. In this case you have to modify a few things in msvccompiler.py located in your python installation.

Go to line 122 and replace the line vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version with vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version Then retry again. If you get a second error like error: Python was built with Visual Studio 2003;... you must also replace line 128 self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") with self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0") Retry once again. If you get again an error like error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed. then you should check the environment variables DISTUTILS_USE_SDK and MSSDK with echo %DISTUTILS_USE_SDK% echo %MSSDK% If not yet set then just set it e.g. to 1 set DISTUTILS_USE_SDK=1 set MSSDK=1

Now, you may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix. After that copy the generated pivy directory to a place where the python interpreter in FreeCAD can find it.

Usage
To have Pivy access the FreeCAD scenegraph do the following:

from pivy import coin App.newDocument # Open a document and a view view = Gui.ActiveDocument.ActiveView FCSceneGraph = view.getSceneGraph # returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraph FCSceneGraph.addChild(coin.SoCube) # add a box to scene

You can now explore the FCSceneGraph with the dir command.

Documentation
Unfortunately documentation about pivy is still almost inexistant on the net. But you might find Coin documentation useful, since pivy simply translate Coin functions, nodes and methods in python, everything keeps the same name and properties, keeping in mind the difference of syntax between C and python:

http://doc.coin3d.org/Coin/classes.html - Coin3D API Reference

http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html - The Inventor Mentor - The "bible" of Inventor scene description language.

You can also look at the Draft.py file in the FreeCAD Mod/Draft folder, since it makes big use of pivy.