Embedding FreeCAD/es: Difference between revisions

From FreeCAD Documentation
m (template fr)
(Updating to match new version of source page)
Line 1: Line 1:
FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.
FreeCAD tiene la asombrosa capacidad de poder importarse como un módulo de Python en otros programas o en una consola independiente de Python, junto con todos sus módulos y componentes. Incluso es posible importar el GUI de FreeCAD como módulo Python (aunque con algunas restricciones).


=== Usando FreeCAD sin interfaz gráfica de usuario GUI ===
=== Using FreeCAD without GUI ===

Una primera, directa, fácil y útil aplicación que puedes hacer de esto es para importar documentos de FreeCAD en tu programa. En el siguiente ejemplo, vamos a importar la geometría de la pieza de un documento de FreeCAD en [http://www.blender.org Blender]. Aquí está el archivo de guión completo. Espero que te impresione por su sencillez:


One first, direct, easy and useful application you can make of this is to import FreeCAD documents into your program. In the following example, we'll import the Part geometry of a FreeCAD document into [http://www.blender.org blender]. Here is the complete script. I hope you'll be impressed by its simplicity:<syntaxhighlight>
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
import Blender, sys
import Blender, sys
Line 39: Line 38:
if __name__=='__main__':
if __name__=='__main__':
main()
main()
</syntaxhighlight>The first, important part is to make sure python will find our FreeCAD library. Once it finds it, all FreeCAD modules such as Part, that we'll use too, will be available automatically. So we simply take the sys.path variable, which is where python searches for modules, and we append the FreeCAD lib path. This modification is only temporary, and will be lost when we'll close our python interpreter. Another way could be making a link to your FreeCAD library in one of the python search paths. I kept the path in a constant (FREECADPATH) so it'll be easier for another user of the script to configure it to his own system.


Once we are sure the library is loaded (the try/except sequence), we can now work with FreeCAD, the same way as we would inside FreeCAD's own python interpreter. We open the FreeCAD document that is passed to us by the main() function, and we make a list of its objects. Then, as we choosed only to care about Part geometry, we check if the Type property of each object contains "Part", then we tesselate it.
La primera parte, importante, es estar seguro de que Python encontrará nuestra biblioteca de FreeCAD. Una vez que la encuentra, todos los módulos de FreeCAD como el de Pieza (que también utilizaremos) estarán disponibles de forma automática. Así que, simplemente, tomamos la variable sys.path, que es donde Python busca sus módulos, y añadimos la ruta de acceso de FreeCAD lib. Esta modificación es sólo temporal, y se perderá cuando cerremos nuestro intérprete de Python. Otra forma podría ser hacer un enlace a tu librería de FreeCAD en una de las rutas de búsqueda de Python. Yo he puesto la ruta en una constante (FREECADPATH), por lo que será más fácil para otro usuario del archivo de guión adaptarlo a su propio sistema.


The tesselation produce a list of vertices and a list of faces defined by vertices indexes. This is perfect, since it is exactly the same way as blender defines meshes. So, our task is ridiculously simple, we just add both lists contents to the verts and faces of a blender mesh. When everything is done, we just redraw the screen, and that's it!
Una vez que estamos seguros de que la biblioteca se carga (la secuencia try/except), podemos trabajar con FreeCAD del mismo modo que lo haríamos en el propio intérprete de Python que tiene FreeCAD. Abrimos el documento de FreeCAD que nos pasa la función main(), y hacemos una lista de sus objetos. Luego, como hemos escogido ocuparnos sólo de la geometría de la Pieza, verificamos que la propiesdad Type de cada objeto contiene "Parte", y despues lo ''teselamos''.


Of course this script is very simple (in fact I made a more advanced [http://yorik.orgfree.com/scripts/import_freecad.py here]), you might want to extend it, for example importing mesh objects too, or importing Part geometry that has no faces, or import other file formats that FreeCAD can read. You might also want to export geometry to a FreeCAD document, which can be done the same way. You might also want to build a dialog, so the user can choose what to import, etc... The beauty of all this actually lies in the fact that you let FreeCAD do the ground work while presenting its results in the program of your choice.
El proceso de ''teselado'' elabora una lista de vértices y una lista de caras definidas por vértices índexados. Esto es perfecto, ya que es exactamente del mismo modo se definen las mallas en ''Blender''. Por lo tanto, nuestra tarea es ridículamente simple, sólo tienes que añadir los contenidos de ambas listas a los vértices y caras de una malla de ''Blender''. Cuando todo esté hecho, volvemos a dibujar la pantalla, y eso es todo!


=== Using FreeCAD with GUI ===
Por supuesto, como este archivo de guión es muy simple (de hecho hice uno más avanzados [http://yorik.orgfree.com/scripts/import_freecad.py aquí]), es posible que desees ampliarlo, por ejemplo añadiendo la importación de objetos malla, o importando geometría de piezas que no tenga caras, o importar otros formatos de archivo de los que puede leer FreeCAD. Es posible que también desees exportar la geometría a un documento de FreeCAD, lo cual se puede hacer de la misma manera. Es posible que también quieras construir un cuadro de diálogo, con el que el usuario pueda elegir qué importar, etc .. La belleza de todo esto reside realmente en el hecho de que tu dejas a FreeCAD hacer el trabajo en la sombra, mientras que la presentación de los resultados se hace en el programa de tu elección.


From version 4.2 on Qt has the intriguing ability to embed Qt-GUI-dependent plugins into non-Qt host applications and share the host's event loop.
=== Uso de FreeCAD con interfaz gráfica de usuario GUI ===
Desde la versión 4.2, Qt tiene capacidad para incrustar plugins Qt dependientes del interfaz gráfica de usuario GUI en aplicaciones host (anfitrión) no-Qt y compartir el bucle de eventos del host (anfitrión).


En concreto, para FreeCAD esto significa que puede ser importado (incrustado) con toda su GUI (interfaz de usuario) dentro de otra aplicación (host), con lo que desde la aplicación host se tiene el control total sobre FreeCAD.
Especially, for FreeCAD this means that it can be imported from within another application with its whole user interface where the host application has full control over FreeCAD, then.

El código en Python para lograr todo eso tiene sólo dos líneas


The whole python code to achieve that has only two lines<syntaxhighlight>
import FreeCADGui
import FreeCADGui
FreeCADGui.showMainWindow()
FreeCADGui.showMainWindow()
</syntaxhighlight>
If the host application is based on Qt then this solution should work on all platforms which Qt supports. However, the host should link the same Qt version as FreeCAD because otherwise you could run into unexpected runtime errors.


For non-Qt applications, however, there are a few limitations you must be aware of. This solution probably doesn't work together with all other toolkits.
Si la aplicación host se basa en Qt, entonces esta solución debería funcionar en todas las plataformas que soporte Qt. Sin embargo, el anfitrión debe vincularse a la misma versión de Qt que FreeCAD porque de lo contrario podrías obtener errores de ejecución inesperados.
For Windows it works as long as the host application is directly based on Win32 or any other toolkit that internally uses the Win32 API such as wxWidgets, MFC or WinForms. In order to get it working under X11 the host application must link the "glib" library.

Para aplicaciones que no son Qt, sin embargo, hay algunas limitaciones que debes tener en cuenta. Esta solución probablemente no funcionará con todos los demás toolkits.
Para Windows funcionará siempre y cuando la aplicación host se base directamente en Win32 o en cualquier otro kit que use internamente el API Win32 como wxWidgets, MFC o WinForms. Para hacerlo funcionar bajo X11, la aplicación host debe vincularse a la biblioteca "glib".

Ten en cuenta, por supuesto, que para cualquier aplicación de consola, esta solución no funciona porque no hay ningún bucle de eventos en ejecución.



Note, for any console application this solution of course doesn't work because there is no event loop running.
{{docnav/es|Scripted objects/es|Code snippets/es}}


{{docnav|Scripted objects|Code snippets}}
{{languages/es | {{en|Embedding FreeCAD}} {{fr|Embedding FreeCAD/fr}} {{it|Embedding FreeCAD/it}} {{se|Embedding FreeCAD/se}} {{ru|Embedding FreeCAD/ru}} }}


[[Category:Poweruser Documentation/es]]
[[Category:Poweruser Documentation]]
[[Category:Python Code]]


{{clear}}
[[Category:Python Code/es]]
<languages/>

Revision as of 20:03, 10 October 2014

FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.

Using FreeCAD without GUI

One first, direct, easy and useful application you can make of this is to import FreeCAD documents into your program. In the following example, we'll import the Part geometry of a FreeCAD document into blender. Here is the complete script. I hope you'll be impressed by its simplicity:

 FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
 import Blender, sys
 sys.path.append(FREECADPATH)
 
 def import_fcstd(filename):
    try:
        import FreeCAD
    except ValueError:
        Blender.Draw.PupMenu('Error%t|FreeCAD library not found. Please check the FREECADPATH variable in the import script is correct')
    else:
        scene = Blender.Scene.GetCurrent()
        import Part
        doc = FreeCAD.open(filename)
        objects = doc.Objects
        for ob in objects:
            if ob.Type[:4] == 'Part':
                shape = ob.Shape
                if shape.Faces:
                    mesh = Blender.Mesh.New()
                    rawdata = shape.tessellate(1)
                    for v in rawdata[0]:
                        mesh.verts.append((v.x,v.y,v.z))
                    for f in rawdata[1]:
                        mesh.faces.append.append(f)
                    scene.objects.new(mesh,ob.Name)
        Blender.Redraw()
 
 def main():
    Blender.Window.FileSelector(import_fcstd, 'IMPORT FCSTD', 
                        Blender.sys.makename(ext='.fcstd'))    
 
 # This lets you import the script without running it
 if __name__=='__main__':
    main()

The first, important part is to make sure python will find our FreeCAD library. Once it finds it, all FreeCAD modules such as Part, that we'll use too, will be available automatically. So we simply take the sys.path variable, which is where python searches for modules, and we append the FreeCAD lib path. This modification is only temporary, and will be lost when we'll close our python interpreter. Another way could be making a link to your FreeCAD library in one of the python search paths. I kept the path in a constant (FREECADPATH) so it'll be easier for another user of the script to configure it to his own system.

Once we are sure the library is loaded (the try/except sequence), we can now work with FreeCAD, the same way as we would inside FreeCAD's own python interpreter. We open the FreeCAD document that is passed to us by the main() function, and we make a list of its objects. Then, as we choosed only to care about Part geometry, we check if the Type property of each object contains "Part", then we tesselate it.

The tesselation produce a list of vertices and a list of faces defined by vertices indexes. This is perfect, since it is exactly the same way as blender defines meshes. So, our task is ridiculously simple, we just add both lists contents to the verts and faces of a blender mesh. When everything is done, we just redraw the screen, and that's it!

Of course this script is very simple (in fact I made a more advanced here), you might want to extend it, for example importing mesh objects too, or importing Part geometry that has no faces, or import other file formats that FreeCAD can read. You might also want to export geometry to a FreeCAD document, which can be done the same way. You might also want to build a dialog, so the user can choose what to import, etc... The beauty of all this actually lies in the fact that you let FreeCAD do the ground work while presenting its results in the program of your choice.

Using FreeCAD with GUI

From version 4.2 on Qt has the intriguing ability to embed Qt-GUI-dependent plugins into non-Qt host applications and share the host's event loop.

Especially, for FreeCAD this means that it can be imported from within another application with its whole user interface where the host application has full control over FreeCAD, then.

The whole python code to achieve that has only two lines

 
 import FreeCADGui 
 FreeCADGui.showMainWindow()

If the host application is based on Qt then this solution should work on all platforms which Qt supports. However, the host should link the same Qt version as FreeCAD because otherwise you could run into unexpected runtime errors.

For non-Qt applications, however, there are a few limitations you must be aware of. This solution probably doesn't work together with all other toolkits. For Windows it works as long as the host application is directly based on Win32 or any other toolkit that internally uses the Win32 API such as wxWidgets, MFC or WinForms. In order to get it working under X11 the host application must link the "glib" library.

Note, for any console application this solution of course doesn't work because there is no event loop running.

Scripted objects
Code snippets