Python scripting tutorial/es: Difference between revisions

From FreeCAD Documentation
(Created page with "Puedes comprobar todos los tipos de objeto base disponibles para el documento actual así:")
(Created page with "Los módulos Croquizador y Boceto ambos utilizan el módulo Piezas para crear y manejar sus geometrías, las c...")
Line 137: Line 137:
Now you must surely wonder, what else 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 creating 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 Module|Part]], [[Mesh Module|Mesh]], [[Sketcher Workbench|Sketcher]] or [[Draft Module|Draft]].
Now you must surely wonder, what else 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 creating 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 Module|Part]], [[Mesh Module|Mesh]], [[Sketcher Workbench|Sketcher]] or [[Draft Module|Draft]].


[[Sketcher Workbench|Sketcher]] and [[Draft Module|Draft]] both use the [[Part Module|Part]] module to create and handle their geometry, which are BRep while [[Mesh Module|Mesh]] is totally independent, and handles its own objects. More about that below.
Los módulos [[Sketcher Workbench/es|Croquizador]] y [[Draft Module/es|Boceto]] ambos utilizan el módulo [[Part Module/es|Piezas]] para crear y manejar sus geometrías, las cuales son mientras que el módulo [[Mesh Module/es|Mallas]] es totalmente independiente, y maneja sus propios objetos. Comentaremos algo más en adelante.


Puedes comprobar todos los tipos de objeto base disponibles para el documento actual así:
Puedes comprobar todos los tipos de objeto base disponibles para el documento actual así:

Revision as of 19:53, 3 November 2014

Python es un lenguaje de programación, muy simple de utilizar y muy rápido de aprender. Es de código libre, multi plataforma, y puede utilizarse para una gran variedad de cosas, desde la programación de archivos de guión simples a programas muy complejos. Pero uno de sus usos más extendidos es como lenguaje de archivos de guión, ya que es sencillo de embeber en otras aplicaciones. Así es exactamente como se utiliza dentro de FreeCAD. Desde la consola de Python, o desde tus archivos de guión personalizados, puedes pilotar FreeCAD, y hacer que ejecute acciones muy complejas para las cuales aún no exista herramientas en la interfaz gráfica de usuario.

Por ejemplo, desde un archivo de guión de Python, puedes:

  • Crear nuevos objetos.
  • Modificar los objetos existentes.
  • Modificar la representación 3D de dichos objetos
  • Modificar la interfaz de FreeCAD

También existen diversas formas de utilizar Python en FreeCAD:

  • Desde el Interprete de Python de FreeCAD, donde puedes dictar comandos como en una interfaz del tipo de línea de comandos
  • Desde Macros, que son una forma conveniente de añadir una herramienta que no exista a la interfaz de FreeCAD
  • Desde archivos de guión externos, que pueden utilizarse para programar cosas mucho más complejas. Como Entornos completos.

En este tutorial, trabajaremos en varios ejemplos simples para que puedas iniciarte, pero existe mucha más documentación sobre los archivos de guión de Python disponible en esta wiki. Si eres totalmente nuevo en Python y quieres comprender cómo funciona, también tenemos una básica Introducción a Python.

Important! Before proceeding with Python scripting, go to Edit->Prefences->General->Output window and check 2 boxes:

  • Redirect internal Python output to report view
  • Redirect internal Python errors to report view

Then go to View->Views and check:

  • Report view

This will save you a lot of aggravation!

Escribiendo código en Python

Existen dos modos sencillos de escribir código de Python en FreeCAD: Desde la consola de Python (disponible en el menú Vista -> Vistas -> Consola de Python) o desde el editor de macros (Herramientas -> Macros). En la consola, escribes comandos de Python uno a uno, que son ejecutados al presionar Enter, mientras que las macros pueden contener archivos de guión más completos formados por varias líneas, que se ejecutan sólo cuando la macro es ejecutada.

La consola de Python de FreeCAD

En este tutorial, serás capaz de utilizar ambos métodos, ya sea copiando y pegando cada línea una a una en la consola de Python y presionando Return después de cada línea, o copiando y pegando el código entero en una ventana de macro nueva.

Explorando FreeCAD

Vamos a empezar creando un nuevo documento vacío:

doc = FreeCAD.newDocument()

Si escribes esto en la consola de Python de FreeCAD, notaras que en cuanto escribas "FreeCAD.", una ventana aparece, permitiendo rápidamente autocompletar el resto de la línea. Aún mejor, cada entrada en la lista de autocompletar tiene una ayuda explicando lo que hace. Esto hace muy sencillo explorar las funcionalidades disponibles. Antes de seleccionar "newDocument", mira las otras opciones disponibles.

El mecanismo de autocompletar de la consola de Python de FreeCAD

Ahora nuestro nuevo documento se creará. Esto es similar a presionar el botón "Nuevo documento" en la barra de herramientas. En realidad, la mayoría de botones en FreeCAD no hacen nada más que ejecutar una línea o dos de código en Python. Aún mejor, puedes establecer una opción en Editar -> Preferencias -> General -> Macro para "mostrar los comandos de los archivos de guión en la consola de Python". Esto mostrará en la consola todo el código de Python ejecutado cuando presionas los botones. Muy útil para aprender como reproducir acciones en Python.

Volvamos ahora a nuestro documento. Vamos a ver que podemos hacer con él:

doc.

Explora las opciones disponibles. Normalmente los nombres que comienzan con una letra mayúscula son atributos, que contienen un valor, mientras que los nombres que empiezan con una letra minúscula son funciones (también llamados métodos), que hacen "algo". Los nombres que comienzan con un guión bajo están ahí normalmente para el funcionamiento interno del módulo, y no deberías preocuparte de ellos. Vamos a utilizar uno de los métodos para añadir un nuevo objeto a nuestro documento:

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

No pasa nada. Por qué? Es debido a que FreeCAD está pensado para realizar trabajos complejos. Un día, trabajará con cientos de objetos complejos, todos dependiendo unos de otros. Hacer un pequeño cambio en cualquier parte podría tener un gran impacto,necesitaras recalcular el documento completo, que puede llevar bastante tiempo... Por ese motivo, casi ningún comando actualiza la escena automáticamente. Debes hacerlo manualmente:

doc.recompute()

Ves? Ahora aparece nuestro cubo! Muchos de los botones que añaden objetos en FreeCAD en realidad hacen dos cosas: Añadir el objeto, y recalcular. Si activas la opción "mostrar los comandos de los archivos de guión en la consola de Python", prueba a añadir una esfera con el botón de la interfaz, verás las dos líneas de código de Python siendo ejecutadas una tras la otra.

Qué quieres saber sobre el "Part::Box"? Cómo puedo saber que otros tipos de objetos puedo añadir? Está todo aquí:

doc.supportedTypes()

Ahora vamos a explorar el contenido de nuestro cubo:

box.

Verás automáticamente varias cosas interesantes como:

box.Height

Esto mostrará la altura actual de nuestro cubo. Ahora vamos a intentar cambiarla:

box.Height = 5

Si seleccionas tu cubo con el ratón, verás que en el panel de propiedades, en la pestaña de "Datos", nuestra propiedad "Height" aparece. Todas las propiedades de un objeto de FreeCAD que aparecen aquí (y también en la pestaña "Vista", de la que hablaremos más adelante), son directamente accesibles también desde Python, por sus nombres, como hicimos con la propiedad "Height". Prueba cambiando las otras dimensiones del cubo.

Vectores y ubicaciones

Los vectores son un concepto muy fundamental en cualquier aplicación 3D. Son una lista de 3 números (X, Y y Z), describiendo un punto o posición en el espacio 3D. Un montón de cosas se pueden hacer con los vectores, como sumas, restas, proyecciones y mucho más. En FreeCAD los vectores funcionan así:

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

Otra característica de los objetos de FreeCAD es su ubicación. Cada objeto tiene atributos de Ubicación, que contienen la posición (Base) y orientación (Rotación) del objeto. Son sencillos de manejar, por ejemplo para mover nuestro objeto:

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

Ahora deberías comprender varios conceptos importantes antes de continuar avanzando.

App y Gui

FreeCAD está creado desde el principio para ser una aplicación de línea de comando, sin su interfaz de usuario. Como resultado, prácticamente todo está separado entre una componente "geométrica" y una componente "visual". Cuando trabajas en modo línea de comando, la parte geométrica está presente, pero todas las partes visuales están sencillamente desactivadas. Prácticamente cualquier objeto en FreeCAD por lo tanto está formado por dos partes, un Object y un ViewObject.

Para ilustrar el concepto, mira nuestro objeto cubo, las propiedades geométricas del cubo, como sus dimensiones, posición, etc. son almacenadas en el Objeto, mientras que sus propiedades visuales, como su color, espesor de línea, etc. se almacenan en el viewobject. Esto se corresponde con las pestañas "Datos" y "Vista" en la ventana de propiedades. El viewobject de un objeto es accesible así:

vo = box.ViewObject

Ahora también puedes cambiar las propiedades de la pestaña "Vista":

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

Cuando inicias FreeCAD, la consola de Python carga 2 módulos base: FreeCAD y FreeCADGui (que también son accesibles por sus diminutivos App y Gui). Ellos contienen toda clase de funcionalidades genéricas para trabajar con documentos y sus objetos. Para ilustrar nuestro concepto, observa que ambos FreeCAD y FreeCADGui contienen un atributo ActiveDocument, el cual es el documento abierto actualmente. FreeCAD.ActiveDocument y FreeCADGui.ActiveDocument no son el mismo objeto. Son los dos componentes de un documento de FreeCAD, y contienen diferentes atributos y métodos. Por ejemplo, FreeCADGui.ActiveDocument contiene ActiveView, que es la vista 3D abierta actualmente.

Modules

Now you must surely wonder, what else 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 creating 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.

Los módulos Croquizador y Boceto ambos utilizan el módulo Piezas para crear y manejar sus geometrías, las cuales son mientras que el módulo Mallas es totalmente independiente, y maneja sus propios objetos. Comentaremos algo más en adelante.

Puedes comprobar todos los tipos de objeto base disponibles para el documento actual así:

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 workbenches modules (Part, Mesh, Sketcher). The other important modules are the 3d scene module (pivy) and the interface module (pyqt), 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 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 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 extensively used as the main test module in the first month of life of FreeCAD.

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:

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

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 add a shape to it, so you can skip the 3 last lines above:

Part.show(myshape)

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

Draft

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:

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, buttons around the 3D view. Qt provides a module, called PyQt, 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 PyQt4 import QtGui
QtGui.QMessageBox.information(None,"Apollo program","Houston, we have a problem")

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 pyqt 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 then be added to a toolbar and be launched from a simple mouse click. FreeCAD provides you with a simple text editor (Macro -> Macros -> Create) where you can write or paste scripts. Once it is done, the Tools -> Customize -> Macros allow you 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