Manual/es

From FreeCAD Documentation
Revision as of 15:58, 23 August 2011 by Splineman (talk | contribs)

Este es el manual de FreeCAD. Incluye las partes esenciales de la Wiki de documentación de FreeCAD. Está creado principalmente para ser impreso como un gran documento, de modo que, si lo estas leyendo online, posiblemente prefieras dirigirte directamente a la versión de la Ayuda en línea, que es más sencilla de manejar.


150
150

Bienvenido a la ayuda en línea de FreeCAD

Este documento ha sido creado automáticamente a partir del contenido de la documentación oficial de la wiki de FreeCAD, que puede leerse online. Dado que la wiki se mantiene activamente y se desarrolla continuamente por la comunidad de desarrolladores y usuarios de FreeCAD, puedes encontrar que la versión online contiene más información o más nueva que este documento. Allí también encontrarás traducciones en curso de esta documentación en varios idiomas. Sin embargo, esperamos que encuentres aquí toda la información que necesitas. En caso de que tengas preguntas para las que no encuentres respuesta en este documento, echa un vistazo al Foro de FreeCAD, donde tal vez puedas encontrar respuesta a tu pregunta, o alguien que pueda ayudarte.

Como utilizar

Este documento está dividido en varias secciones: introducción, uso, scripting y desarrollo, las tres últimas se dirigen específicamente a las tres amplias categorías de usuarios de FreeCAD: usuarios finales, que simplemente quieren usar el programa, usuarios avanzados, que están interesados por las capacidades de scripting de FreeCAD y les gustaría personalizar algunos de sus aspectos, y desarrolladores, que consideran FreeCAD como una base para desarrollar sus propias aplicaciones. Si eres completamente nuevo en FreeCAD, te sugerimos que empieces simplemente por la introducción.

Many pages of this wiki are also grouped into an easier to read Manual. If you are new to FreeCAD, we suggest you start reading the manual.

Contribuir

Como habrás experimentado en ocasiones, ¡programadores son realmente malos escritores de ayuda! Para ellos, todo está completamente claro porque lo han hecho así. Por eso es vital que los usuarios experimentados nos ayuden a escribir y revisar la documentación. Sí, ¡nos referimos a ti! ¿Cómo, te preguntarás? Sólo tienes que ir a sección de usuarios de la wiki. Necesitarás una cuenta en el wiki de FreeCAD para entrar. Pide en el foro o en el IRC channel permiso para escribir en el wiki (el wiki está protegido contra la escritura para evitar el spam) y crearemos una cuenta para ti. Actualmente, la cuenta de la wiki está separada de la cuenta del foro, pero crearemos la cuenta de la wiki con el mismo nombre que tu cuenta del foro. Entonces podrás empezar a editar. Además, echa un vistazo a esta página para ver más formas de ayudar a FreeCAD.

Introducción

FreeCAD es un modelador 3D paramétrico de propósito general CAD, cuyo desarrollo es completamente código abierto (Licencia LGPL). FreeCAD está orientado directamente a la ingeniería mecánica y al diseño de productos, pero también se adapta a una gama más amplia de usos en torno a la ingeniería, como la arquitectura, el análisis de elementos finitos, la impresión 3D y otras tareas.

FreeCAD presenta herramientas similares a CATIA, SolidWorks ó Solid Edge, y por lo tanto tambien cae dentro de la categoría de Diseño asistido por computadora, PLM, CAx y CAE. Es un modelado basado en características paramétricas con una arquitectura de software modular que permite ofrecer funciones adicionales sin modificar el sistema principal.

Al igual que muchos modeladores de CAD, tiene muchos componentes 2D para esbozar formas planas o crear dibujos de producción. Sin embargo, el dibujo 2D directo (como Inkscape o AutoCAD LT) no es el foco, ni tampoco la animación o la edición de mallas (como Blender, Maya, Autodesk 3ds Max, o Cinema 4D). Sin embargo, gracias a su amplia adaptabilidad, FreeCAD podría ser útil en un área mucho más amplia que su enfoque actual.

FreeCAD hace un uso intensivo de las bibliotecas de código abierto que existen en el campo de la Computación cientifica. Entre ellas están Open Cascade Technology (OCCT), un potente kernel de CAD; Coin3D, un conjunto de herramientas para el desarrollo de gráficos 3D compatible con Open Inventor; Qt, el mundialmente famoso marco de interfaz de usuario; y Python, un moderno lenguaje de scripting. El propio FreeCAD también puede ser utilizado como una biblioteca por otros programas.

FreeCAD también es Multiplataforma, y actualmente funciona en sistemas Linux/Unix, Windows y Mac OSX con el mismo aspecto y funcionalidad en todas las plataformas.

Para más información sobre las capacidades de FreeCAD, echa un vistazo a la lista de características, a la últimas notas de la versión, y a los artículos comenzar, o ve más capturas de pantalla.

Acerca del proyecto FreeCAD

El proyecto FreeCAD se inició en 2001, como se describe en su página historia.

FreeCAD es mantenido y desarrollado por una comunidad de entusiastas desarrolladores y usuarios (ver la página contribuidoress). Ellos trabajan en FreeCAD voluntariamente, en su tiempo libre. No pueden garantizar que FreeCAD contenga todo lo que puedas desear, pero harán lo posible. La comunidad se reúne en el Foro FreeCAD, donde se discuten la mayoría de las ideas y decisiones. ¡Siéntete libre de unirte a nosotros allí!

About the FPA

The FreeCAD project is also supported by a non-profit organization, the FreeCAD project association (FPA). The FPA is an independent body created by some FreeCAD veterans in 2021 to collect donations and other resources to support the project and its community, to help protect that community and allow it to continue developing in the best conditions, and to represent the project against other bodies such as companies and institutions.


Esta es una lista extensa, pero no completa, de las características que FreeCAD implementa.

Notas de la versión

Características clave

  • A complete Open CASCADE Technology-based geometry kernel allowing complex 3D operations on complex shape types, with native support for concepts like Boundary Representation (BREP), Non-uniform rational basis spline (NURBS) curves and surfaces, a wide range of geometric entities, boolean operations and fillets, and built-in support of STEP and IGES formats
  • A full parametric model. All FreeCAD objects are natively parametric, meaning their shape can be based on properties or even depend on other objects. All changes are recalculated on demand, and recorded by an undo/redo stack. New object types can be added easily, and can even be fully programmed in Python.
  • A modular architecture that allows plugin extensions (modules) to add functionality to the core application. An extension can be as complex as a whole new application programmed in C++ or as simple as a Python script or self-recorded macro. You have complete access to almost any part of FreeCAD from the built-in Python interpreter, macros or external scripts, be it geometry creation and transformation, the 2D or 3D representation of that geometry (scenegraph) or even the FreeCAD interface.
  • Import/export to standard formats such as STEP, IGES, OBJ, STL, DXF, SVG, DAE, IFC or OFF, NASTRAN, VRML in addition to FreeCAD's native FCStd file format. The level of compatibility between FreeCAD and a given file format can vary, since it depends on the module that implements it.
  • A Sketcher with integrated constraint-solver, allowing you to sketch geometry-constrained 2D shapes. The constrained 2D shapes built with Sketcher may then be used as a base to build other objects throughout FreeCAD.
  • A technical drawing module with options for detail views, cross sectional views, dimensioning and others, allowing you to generate 2D views of existing 3D models. The module then produces ready-to-export SVG or PDF files.
  • An Architecture module that allows Building Information Modeling (BIM)-like workflow, with Industry Foundation Classes (IFC) compatibility.
  • A Path module dedicated to mechanical machining for Computer Aided Manufacturing (CAM). Using the Path module you may output, display and adjust the G code used to control the target machine.
  • An Integrated Spreadsheet and an expression parser which may be used to drive formula-based models and organize model data in a central location.

Características generales

  • multiplataforma. Se ejecuta y se comporta exactamente de la misma manera en Windows, Linux y macOS.
  • completa aplicación de interfaz gráfica de usuario (GUI). FreeCAD cuenta con una completa interfaz gráfica de usuario basada en el famoso entorno Qt, con un visualizador 3D basado en Open Inventor, que permite un rápido renderizado de escenas 3D y una representación gráfica de escenas muy accesible.
  • ejecuta como una aplicación de línea de comandos, con menos requerimientos de memoria. En el modo de línea de comandos, FreeCAD se ejecuta sin su interfaz gráfica GUI, pero con todas sus herramientas de geometría. Puede ser, por ejemplo, utilizado como servidor para producir contenidos para otras aplicaciones.
  • puede ser importado como un módulo de Python. FreeCAD puede ser importado en cualquier aplicación que pueda ejecutar scripts de Python. Como en el modo de línea de comandos, la parte de la interfaz de FreeCAD no está disponible, pero todas las herramientas de geometría son accesibles.
  • concepto de ambiente de trabajo: En la interfaz de FreeCAD, las herramientas se agrupan en entornos de trabajo (Ambiente de trabajo). Esto permite mostrar sólo las herramientas utilizadas para llevar a cabo una cierta tarea, manteniendo el espacio de trabajo ordenado y acondicionado, y que la aplicación se cargue rápidamente.
  • plugin/módulo marco para la carga tardía de características/tipos de datos. FreeCAD está dividido en una aplicación central con módulos que se cargan sólo cuando se necesitan. Casi todas las herramientas y tipos de geometría se almacenan en módulos. Los módulos se comportan como plugins; además de la carga tardía, se pueden añadir o eliminar módulos individuales de una instalación existente de FreeCAD.
  • objetos de documentos asociativos paramétricos. Todos los objetos de un documento de FreeCAD pueden ser definidos por parámetros. Esos parámetros pueden ser modificados y recalculados en cualquier momento. Dado que las relaciones entre los objetos se mantienen, la modificación de un objeto se propagará automáticamente a cualquier objeto dependiente.
  • creación primitiva paramétrica. Los objetos primitivos como la caja, la esfera, el cilindro, etc. pueden ser creados especificando sus restricciones geométricas.
  • operaciones de modificación gráfica. FreeCAD puede realizar traslación, rotación, escalado, espejado, desplazamiento (ya sea trivial o como se describe en Jung/Shin/Choi) o conversión de formas, en cualquier plano del espacio tridimensional.
  • 'Geometría sólida constructiva (operaciones booleanas). FreeCAD puede hacer operaciones constructivas de geometría sólida (unión, diferencia, intersección).
  • creación gráfica de geometría plana. Se pueden crear gráficamente líneas, hilos, rectángulos, B-splines y arcos circulares o elípticos en cualquier plano del espacio 3D.
  • modelado con rectas o revueltas extrusiones, secciones y redondeos.
  • Componentes topológicos como vertices, bordes, hilos y planos.
  • probando y reparando. FreeCAD tiene herramientas para probar mallas (prueba de sólidos, prueba de no-dos-móviles, prueba de auto-intercesión) y para reparar mallas (llenado de agujeros, orientación uniforme).
  • Anotaciones. FreeCAD puede insertar anotaciones para el texto o las dimensiones.
  • Deshacer/Rehacer marco. Todo en FreeCAD es deshacer/rehacer, con acceso de usuario a la pila de deshacer. Se pueden deshacer varios pasos a la vez.
  • orientado a la transacción. La pila de deshacer/rehacer almacena las transacciones de documentos, no las acciones individuales, permitiendo que cada herramienta defina exactamente lo que debe deshacerse o rehacerse.
  • marco de trabajo Guión incorporado. FreeCAD cuenta con un intérprete Python incorporado, con una API que cubre casi cualquier parte de la aplicación, la interfaz, la geometría y la representación de esta geometría en el visor 3D. El intérprete puede ejecutar tanto scripts complejos como comandos individuales; se pueden programar módulos enteros completamente en Python.
  • Consola de Python incorporada. El intérprete de Python incluye una consola con resaltado de sintaxis, autocompletado y un navegador de clases. Los comandos de Python pueden ser emitidos directamente en FreeCAD y devolver inmediatamente los resultados, permitiendo a los escritores de scripts probar la funcionalidad sobre la marcha, explorar el contenido de los módulos de FreeCAD y aprender fácilmente sobre los aspectos internos de FreeCAD.
  • refleja la interacción del usuario. Todo lo que el usuario hace en la interfaz de FreeCAD ejecuta código Python, que puede imprimirse en la consola y registrarse en macros.
  • Capacidades completas de grabación y edición de macro. Los comandos de Python emitidos cuando el usuario manipula la interfaz pueden ser grabados, editados si es necesario, y guardados para ser reproducidos más tarde.
  • Formato compuesto (basado en ZIP) para guardar documentos. Los documentos de FreeCAD se guardan con una extensión .FCStd. El documento puede contener muchos tipos diferentes de información como geometría, scripts o iconos en miniatura. El archivo es en sí mismo un contenedor zip; un archivo FreeCAD guardado ya ha sido comprimido.
  • Interfaz gráfica de usuario totalmente personalizable/scriptible. La interfaz basada en Qt de FreeCAD es totalmente accesible a través del intérprete de Python. Aparte de las simples funciones que FreeCAD proporciona a los ambientes de trabajo, todo el framework Qt es accesible. El usuario puede realizar cualquier operación en la GUI como crear, añadir, acoplar, modificar o eliminar widgets y barras de herramientas.
  • miniaturas. (actualmente sólo en sistemas Linux) Los iconos de los documentos de FreeCAD muestran el contenido del archivo en la mayoría de las aplicaciones de gestión de archivos, como el Nautilus de Gnome.
  • Instalador MSI modular. El instalador de FreeCAD permite instalaciones flexibles en sistemas Windows. También se soportan paquetes para sistemas Ubuntu.

Extra Workbenches

Usuarios talentosos han creado varios Ambiente de trabajo externos personalizados.


Instalación

Instalación en Windows


Standard Installation

La forma más fácil de instalar FreeCAD en Windows es usando el paquete de instalación descargable de arriba. Esta página describe el uso y las características del NSIS Instalador para más opciones de instalación.

Si desea descargar una versión en desarrollo (que puede ser inestable), mira la página Descargas.

Después de descargar el archivo .exe (NSIS Installer), haga doble clic en él para iniciar el proceso de instalación.

Abajo hay más información sobre algunas opciones técnicas. Sin embargo, la mayoría de los usuarios no necesitan más que los anteriores archivos .exe. Continuar a Empieza después de que la instalación se haya completado.

Installation for all users of the Windows system

By default FreeCAD will be installed for the user that executes the installer. If this user only has user permissions, the default installation path is:

C:\Users\<username>\AppData\Local\Programs\FreeCAD X.YY

If the installer is executed by an admin user, or you execute it as admin, you can choose if FreeCAD should be installed for all users of the system or just for you. The default is for all users.

If installed for all users, the default installation path is:

C:\Program Files\FreeCAD X.YY

Silent Installation

To install FreeCAD silently, you can execute the installer from the command line:

FreeCAD-~.exe /S

Default settings will be used for all options. A custom installation path can be specified in this manner:

FreeCAD-~.exe /S /D=A path to FreeCAD with spaces

By default, even with silent installations, there will be a short popup when the installer is checked for corruption. This so-called cyclic redundancy check only takes a few seconds at most. To disable this corruption check:

FreeCAD-~.exe /S /NCRC

Note that this /NCRC flag is not recommended since the corruption check assures that the installer was e.g. completely downloaded.

Chocolatey

Using the Chocolatey package manager is currently not recommended as that repository is no longer kept up-to-date.

Desinstalación

To uninstall FreeCAD it is preferable to use the Windows tools for uninstalling software. Alternatively you can execute the uninstaller directly. This is the file:

Uninstall-FreeCAD.exe

You can find it in the folder where FreeCAD is installed.

The uninstaller can also be executed silently using the command line:

Uninstall-FreeCAD.exe /S

Note that (silent) uninstallation will fail if there is a running instance of FreeCAD, even if that instance is not the version being uninstalled.


Instalación en Unix/Linux


Vista general

La instalación de FreeCAD en los sistemas Linux más conocidos ha sido aprobada por la comunidad, y FreeCAD debería estar disponible directamente a través del gestor de paquetes disponible en su distribución. El equipo de FreeCAD también proporciona algunos:

Ubuntu y sistemas basados en Ubuntu

Muchas distribuciones de Linux están basadas en Ubuntu y comparten sus repositorios. Además de las variantes oficiales (Kubuntu, Lubuntu y Xubuntu), existen derivados no oficiales como Linux Mint, Voyager y otros. Las opciones de instalación que se indican a continuación (expandir) deberían ser compatibles con estos sistemas.

Versión oficial

FreeCAD está disponible en el repositorio del Universo Ubuntu, y puede ser instalado a través del Centro de Software o desde la terminal:

sudo apt install freecad

Nota: el paquete del Universo Ubuntu puede estar desactualizado, ya que el paquete puede ir por detrás del último código fuente estable. En este caso, se sugiere instalar el paquete desde el -estable PPA abajo. Además, se puede instalar el paquete -diario para probar la rama de desarrollo.

Versión estable PPA

Warning: The FreeCAD PPA is currently unmaintained and looking for volunteers. Please use an alternative (snap, appimage) until the issue is fixed!

El Archivo de Paquetes Personales (APP) para la versión estable de FreeCAD es mantenido por la comunidad de FreeCAD en el Launchpad. El repositorio de Launchpad se llama FreeCAD Lanzamientos estables .

GUI

Instale el PPA estable a través de la Interfaz Gráfica de Usuario (GUI):

1. Navegue a Ubuntu Software → Software y actualizaciones → Fuentes de software → Otro software
2. Haga clic en Y, y luego copie y pegue la siguiente línea
ppa:freecad-maintainers/freecad-stable
3. Añade la fuente, cierra el diálogo y recarga tus fuentes de software, si se te pide.

Ahora puedes encontrar e instalar la última versión estable de FreeCAD desde el Centro de Software Ubuntu.

CLI

Instale el APP estable a través de la Interfaz de Línea de Comando (CLI):

1. Añade la APP a tus fuentes de software:
sudo add-apt-repository ppa:freecad-maintainers/freecad-stable
2. Recuperar las listas de paquetes actualizadas:
sudo apt update
3. Entonces instala FreeCAD junto con su documentación offline:
sudo apt install freecad freecad-doc

Nota: debido a problemas de empaquetado, en ciertas versiones de Ubuntu el paquete freecad-doc ha colisionado con la instalación de FreeCAD o una de sus dependencias; si este es el caso, retire el paquete freecad-doc y sólo instale el paquete freecad. Si el paquete freecad-doc no existe, entonces ignóralo.

Comprobando la instalación

4. Una vez que tenga el APP estable añadido a sus fuentes usando uno de los métodos anteriores, el paquete freecad instalará esta versión de PPA sobre la proporcionada por el repositorio del Universo Ubuntu. Puede ver las versiones disponibles con el siguiente comando apt-cache:
apt-cache policy freecad
La emisión debe ser similar a la siguiente (por supuesto la información de la versión variará):
freecad:
  Installed: (none)
  Candidate: 2:0.18.4+dfsg1~201911060029~ubuntu18.04.1
  Version table:
     2:0.18.4+dfsg1~201911060029~ubuntu18.04.1 500
        500 http://ppa.launchpad.net/freecad-maintainers/freecad-stable/ubuntu bionic/main amd64 Packages
     0.16.6712+dfsg1-1ubuntu2 500
        500 http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
ubuntu@ubuntu:~$ apt-cache policy freecad-doc
5. Invoca la versión estable (PPA) de FreeCAD desde el GUI o CLI. Este último método es el siguiente:
./freecad

Desarrollo APP (Diario)

Como FreeCAD está en constante desarrollo, puede que desee instalar el paquete diario para estar al tanto de las últimas mejoras y correcciones de errores. El repositorio también está alojado en Launchpad y se llama freecad-daily.

Esta versión se compila diariamente desde el repositorio maestro oficial. Por favor, tened cuidado de que aunque contenga nuevas características y correcciones de errores, también puede tener nuevos errores y ser inestable.

Añade la APP diaria a tus fuentes de software, actualiza las listas de paquetes e instala el paquete diario:

sudo add-apt-repository ppa:freecad-maintainers/freecad-daily
sudo apt-get update
sudo apt-get install freecad-daily

Todos los días puedes actualizarte con las últimas novedades:

sudo apt-get update
sudo apt-get install freecad-daily

Nota: en algunos casos el nuevo código o las dependencias añadidas a FreeCAD causarán errores de empaquetado; si esto ocurre, no se generará un paquete diario hasta que los mantenedores solucionen manualmente los problemas. Si desea continuar probando el último código, debería obtener el código fuente y compilar FreeCAD directamente; para instrucciones vea compilar.

Ejecute la versión diaria (APP) de FreeCAD:

freecad-daily

Nota: Es posible instalar los paquetes -estable y -diario en el mismo sistema. Esto es útil si desea trabajar con una versión estable, y aún así poder probar las últimas características en desarrollo. Fíjese que el ejecutable de la versión diaria es freecad-daily, pero el de la versión estable es sólo freecad.

Debian y otros sistemas basados en Debian

A partir de Debian Lenny, FreeCAD está disponible directamente de los repositorios de software Debian y puede ser installado vía synaptic o simplemente con:

sudo apt-get install freecad

OpenSUSE

FreeCAD se instala típicamente con YAST (abbr. Otra herramienta de configuración) la herramienta de configuración del sistema operativo Linux, o en cualquier terminal/consola (se requieren derechos de root) con:

zypper install FreeCAD

Nota: Este procedimiento sólo cubre la instalación de versiones del programa FreeCAD estables, dependiendo de los enlaces instalados a los repositorios de paquetes de programas de su versión de SO. El paquete openSUSE puede estar desactualizado ya que el paquete puede estar atrasado con respecto al último código fuente estable. En este caso, se sugiere instalar el paquete manualmente desde los repositorios de fuentes indicados abajo (Expandir).

Se ofrece un vasto programa de lanzamiento de paquetes de FreeCAD. Por favor, visite para una encuesta:

Estudio de los depósitos en openSUSE

Generalmente para seleccionar la distribución correcta de openSUSE que se necesita es necesario hacer clic en el botón particular View.

Estable

La versión del paquete estable: Repositorios estables en openSUSE. La versión correcta de la distribución de openSUSE debe ser seleccionada en la parte inferior de la página web.

Nota: openSUSE tiene varias opciones para elegir al descargar FreeCAD. Para ver estas opciones, visite Encuesta sobre los repositorios estables en openSUSE.

Desarrollo

El último desarrollo es también conocido como inestable: Listados de repositorios inestables en openSUSE

Se recomienda tomar los paquetes binarios directamente. Luego seleccione la distribución correcta para su sistema operativo openSUSE instalado.

Gentoo

FreeCAD se puede construir/instalar simplemente ejecutando:

emerge freecad

Fedora

FreeCAD ha sido incluido en los paquetes oficiales de Fedora desde Fedora 20. Se puede instalar desde la línea de comandos con:

sudo dnf install freecad

En los antiguos lanzamientos de Fedora, eso era:

sudo yum install freecad

También se pueden utilizar los gestores de paquetes guiados. Busca por "freecad". La versión oficial del paquete de lanzamiento tiende a estar muy por detrás de los lanzamientos de FreeCAD. Paquete: freecad muestra las versiones incluidas en los repositorios de Fedora a lo largo del tiempo y las versiones.

Se pueden obtener versiones más actuales descargando una de las .AppImage... lanzamientos desde el depósito de github. Estas funcionan bien en Fedora.

Si quieres estar al día con las últimas novedades diarias, FreeCAD también está disponible en copr. Para instalar la construcción desde allí, en una sesión de terminal, entra:

sudo dnf copr enable @freecad/nightly
sudo dnf install freecad

Eso deja a la copr repositorio activo, así que

sudo dnf upgrade

o equivalente, se actualizará a la última versión de FreeCAD, junto con las actualizaciones de cualquiera de los otros repositorios activos. Si quieres algo un poco más estable, puedes deshabilitar @freecad/nightly de nuevo después de la instalación inicial. El copr El depósito sólo guarda las construcciones de las últimas 2 semanas. Esta no es una solución si quieres elegir una versión antigua específica.

También hay instrucciones disponibles en Compila FreeCAD tú mismo, incluyendo un script específico para Fedora. Con un pequeño cambio, para comprobar el commit específico de git, cualquier versión desde FreeCAD 0.15 puede ser construida en cualquier distribución desde Fedora 21.

Arch

Instalando FreeCAD en Arch Linux y derivados (ex. Manjaro):

pacman -S freecad

Otros

Si averiguas que tu sistema incorpora FreeCAD pero no está incluido en esta página, por favor dínoslo en los foros!

Diversos paquetes de FreeCAD alternativos, no oficiales están disponibles en la red, por ejemplo para sistemas como Slackware o Fedora. Una búsqueda en la red puede darte rápidamente algunos resultados.

Instalación en otros sistemas Linux/Unix

Muchas distribuciones comunes de Linux ahora incluyen un FreeCAD precompilado como parte de los paquetes estándar. Esto está a menudo desactualizado, pero es un lugar para empezar. Revise los administradores de paquetes estándar de su sistema. Una de las siguientes listas (parciales) de comandos podría instalar la versión oficial de FreeCAD para su distribución desde la terminal. Estos probablemente necesitan privilegios de administrador.

apt-get install freecad
dnf install freecad
emerge freecad
slackpkg install freecad
yum install freecad
zypper install freecad
pacman -Sy freecad

El nombre del paquete es sensible a las mayúsculas y minúsculas, así que prueba con "FreeCAD" y "freecad". Si eso no funciona para usted, ya sea porque su administrador de paquetes no tiene una versión precompilada de FreeCAD disponible, o porque la versión disponible es demasiado vieja para sus necesidades, puede intentar instalar los paquetes Flatpak o Snap o descargar uno de los .AppImage ... lanzamientos desde el depósito de github. Estas también tienden a funcionar en la mayoría de las distribuciones de Linux x86_64, sin ninguna instalación especial. Sólo asegúrate de que el archivo descargado esté marcado como ejecutable, y luego ejecútalo.

Si eso todavía no es lo suficientemente bueno, y no puedes localizar otra fuente de un paquete precompilado para tu situación, necesitarás Compilar FreeCAD tú mismo.

Próximo paso

Una vez tengas instalado FreeCAD, es hora de dar tus primeros pasos!


Instalación en Mac


FreeCAD puede instalarse en macOS desde un paquete .dmg que puedes arrastrar y soltar en tu carpeta de aplicaciones:

If you would like to download a development version, which may be unstable, see the Weekly builds download page.

También puede utilizar un gestor de paquetes como HomeBrew para mantener su software actualizado. Las instrucciones para instalar HomeBrew pueden verse aquí. Cuando HomeBrew esté instalado puedes simplemente instalar FreeCAD 0.18.4 a través de tu terminal bash con

brew install --cask freecad

y para utilizar la última versión disponible (0.19pre) en HomeBrew puede ejecutar

brew install freecad

Si hay algún problema con el HomeBrew Cask o Formula, puede informar de ello a aquí.

Esta página describe el uso y las características del instalador de FreeCAD. También incluye instrucciones de desinstalación. Una vez instalado, puedes empezar!

Instalación simple

El instalador de FreeCAD se proporciona como un paquete de aplicaciones (.app) incluido en un archivo de imagen de disco.

Puedes descargar el último instalador desde la página Descarga. Una vez descargado el archivo, sólo tienes que montar la imagen de disco y arrastrarla a la carpeta de aplicaciones o a una carpeta de tu elección.

Eso es todo.Solo da clic sobre app para ejecutar FreeCAD. Si tu tienes este mensaje "FreeCAD can't be open as it is from unidentified developer." Abre la carpeta (Application) y da clic derecho sobre app luego da clic en abrir y acepta abrir la aplicación.

Desinstalación

Actualmente no hay un desinstalador para FreeCAD instalado con el paquete dmg. Para eliminar completamente FreeCAD y todos los componentes instalados, arrastre los siguientes archivos y carpetas a la Papelera:

  • En /Aplicaciones:
    • FreeCAD

Si instalaste FreeCAD con homebrew simplemente usa el comando brew uninstall freecad. Eso es todo.


Descubriendo FreeCAD


FreeCAD es una 3D aplicación de modelado paramétrico. Esta primeramente hecha para diseño mecánico, pero también sirve a muchos otros usos donde donde necesitas modelado 3D con precisión y control sobre historial de modelado.

FreeCAD se ha estado desarrollando desde 2002, y ofrece una amplia lista de características. Todavía faltan capacidades, pero es lo suficientemente potente para el uso de aficionados y pequeños talleres. Hay una comunidad en rápido crecimiento de usuarios entusiastas que participan en el foro de FreeCAD, y se pueden encontrar muchos ejemplos de proyectos de calidad desarrollados con FreeCAD allí. Véase también, FreeCAD utilizado en producción.

Como todos los proyectos de software libre, FreeCAD depende de su comunidad para crecer, obtener características y corregir errores. No olvide esto cuando use FreeCAD; si le gusta, puede donar y ayudar a FreeCAD de varias maneras, como escribir documentación y hacer traducciones.

Ver también:

Instalación

En primer lugar, descarga e instala FreeCAD. Consulte la página Descargar para obtener información sobre las versiones y actualizaciones actuales, y las instrucciones de instalación para tu sistema operativo (Windows, Linux o Mac). Hay paquetes de instalación listos para Windows (.msi), Debian y Ubuntu (.deb), openSUSE (.rpm), y Mac OSX. FreeCAD está disponible en los gestores de paquetes de muchas otras distribuciones de Linux. También está disponible un ejecutable AppImage independiente, que se ejecutará en los sistemas Linux de 64 bits más recientes. Como FreeCAD es de código abierto, también puedes obtener el código fuente y compilar por ti mismo.

Explorando la interfaz

La interfaz estándar de FreeCAD

Vea una explicación completa en Interfaz.

1. El área_de_visión_principal, que puede contener diferentes ventanas con pestañas, principalmente la vista_3D.
2. La Vista_3D, que muestra los objetos geométricos del documento.
3. La vista_árbol (parte de la Vista combo), mostrando la jerarquía y el historial de construcción de los objetos del documento; también puede mostrar el panel de tareas para los comandos activos.
4. El editor de propiedades (parte de la Vista combo), que permite ver y modificar las propiedades de los objetos seleccionados.
5. La vista de selección, que indica los objetos o subelementos de los objetos (vértices, bordes, caras) que están seleccionados.
6. La vista_de_informe (o ventana de salida), donde se muestran los mensajes, advertencias y errores.
7. La Consola Python, donde se imprimen todos los comandos ejecutados, y donde se puede introducir el código Python.
8. La barra de estado, donde aparecen algunos mensajes y tooltips.
9. El área de la barra de herramientas, donde están acopladas las barras de herramientas.
10. El seleccionador de bancos ambientes de trabajo, donde se selecciona el ambiente de trabajo activo.
11. El menú estándar, que contiene las operaciones básicas del programa.

El concepto principal detras de la interface de Freecad es que esta separado en Ambientes de trabajos. Un Ambiente de trabajo es una colección de herramientas adecuadas para una tarea especifica, tal como trabajar con mallas, o dibujar objetos 2D, o Croquis restringido. Puedes cambiar el ambiente de trabajo actual con el selector de ambientes de trabajo. Puedes personalizar la herramientas incuidas en cada ambiente de trabajo, agregar herramientas de otros ambiente de trabajo o incluso herramientas propias, que nosotros llamamos macros. Puntos de inicio ampliamente utilizados son Ambiente de trabajo DiseñoPieza and Ambiente de trabajo Pieza.

Cuando comienzas FreeCAD por primera vez, se te presenta la página de inicio. EEsto es lo que parece para la versión 0.18:

La página de inicio te permite saltar rápidamente a uno de los ambientes de trabajo más comunes, abrir uno de los archivos recientes, o ver las últimas noticias del mundo de FreeCAD. Puedes cambiar el ambientes de trabajo por defecto en las preferencias.

Navegando en el espacio 3D

FreeCAD tiene tres diferentes Modos de navegación disponibles, que se pueden establecer en las preferencias del diálogo de configuración o cambiar pulsando el botón derecho en la vista 3D. Para ver más detalles sobre los modos mira la página Modos de navegación. Para el modo de navegación por defecto Navegación CAD(Puedes cambiar rapidamente el actual modo de navegación dado clic derecho en un area vaci de la vista 3D):

También tiene varias vistas preconfiguradas (vista superior, vista frontal, etc.) disponibles en el menú Ver, en la barra de herramientas Ver, y, por atajos numéricos (1, 2, etc...). Dado clic derecho sobre un objeto o sobre un area vacia de la vista 3D, tienes acceso directo a algunas operaciones comunes, tal como configurar una vista particular, o ubicar un objeto en la vista de árbol.

Primeros paso con FreeCAD

El enfoque de FreeCAD es permitirte hacer modelos 3D de alta presición, para mantener un control ajustado sobre estos modelos(ser capaz de retroceder dentro del historial de modelado y cambiar parametros), y eventualmente construir estos modelos (impresion 3D, mecanizado CNC o incluso sitio de construción). Es por lo tanto muy diferente de algunas otras aplicaciones 3D hechas para otros propositos, tal como animacion o juegos. Su curva de aprendizaje puede ser doloroza, especialmente si este es tu primer contacto con modelado 3D. Si esta atorado en algun punto, no olvides que la amigable comunidad de usuarios en el Foro de FreeCAD podrian sacarte en poco tiempo.

El ambiente de trabajo que empezaras a utilizar depende sobre el tipo de trabajo que necesitas hacer: Si tu vas a trabajar sobre modelos mecanicos, o más generalmente hablando cualquier objecto de pequeña escala, tu podrias probablemente querer probar el Ambiente de trabajo DiseñoPiezas. Si vas a trabajar en 2D, entonces cambia a el Ambiente de trabajo Borrador o el Ambiente de trabajo Croquizador si necesitas acotaciones. si tu quieres hacer BIM, ejecuta el Ambiente de trabajo Arquitectura. Si estas trabajando con diseño de barcos, allí esta un Ambiente de trabajo Navío para tí. Y si tu vienes del mundo de OpenSCAD prueba el Ambiente de trabajo OpenSCAD. También hay disponibles muchos Ambientes de trabajo externos desarrollados por la comunidad.

Tú puedes cambiar de ambiente de trabajo en el momento que quieras, y también personalizar tu Ambiente de trabajo favoritos agregando herramientas de otros Ambiente de trabajos.

Trabajando con el Ambiente de trabajo DiseñoPiezas y Ambiente de trabajo Croquizador

El Ambiente de trabajo diseño de parte esta especialmente hecho para hacer objetos complejos, iniciando a partir de simples formas, y agregando o removiendo piezas (que nosotros llamamos "características"),hasta que obtienes tu objeto final.Todas las características que tu apliques durante el proceso modelado seran almacenadas en una vista separada llamada vista de árbol, el cual contiene los otros objetos de tu documento.Puedes pensar que los objetos de diseño de parte son como una sucesión de operaciones, cada una aplicada al resultado del que lo precede, formando una gran cadena. Dentro de la vista de árbol, puedes ver el objeto final, pero puedes expandirla y contraer todos los estados que lo preceden, y cambiar cualquiera de sus parámetros, el cual automáticamente actualiza el objeto final.

El Ambiente de trabajo diseño de parte es fuertemente utilizado por otros Ambiente de trabajo, el Ambiente de trabajo Croquizador. El Boceto te permite dibujar formas 2D, las cuales son definidas aplicando cotas a las formas 2D. Por ejemplo, tal vez quieras dibujar un rectángulo y colocar el tamaño de lado a lado de una cota de longitud a una esquina de los lados. Ese lado entonces no puede ser cambiar el tamaño mas(al menos que la cota sea cambiada).

Esas formas 2D hechas con Boceto son utilizadas mucho en el banco de trabajo diseño de parte, por ejemplo para crear volúmenes 3D, o para dibujar áreas sobre una de las caras de tu objeto que luego sera ahuecado a partir del del volumen principal. Este es un flujo de trabajo típico de diseño de parte:

  1. Crear un boceto nuevo
  2. Crea un dibujo con forma cerrada(asegurarse que todos los puntos están cerrados)
  3. Cerrar el boceto
  4. Expandir el boceto a un solido 3D utilizando la herramienta de rellenado.
  5. Selecciona una cara del solido
  6. Crea un segundo boceto (Esta vez sera dibujado sobre la cara seleccionada)
  7. Dibuja una forma cerrada
  8. Cierra el boceto
  9. Crea un vaciado a partir del segundo boceto, sobre el primer objeto

El cual te da un objeto como este:

En cualquier momento, puedes seleccionar el origen del croquis y modificarlo, o cambiar los parametros de extrusión de la plataforma u operaciones de baciado, las cuales actualizarán el objeto final.

Trabajando con el Ambiente de trabajo Borrador y el Ambiente de trabajo Arquitectura

El Ambiente de trabajo Borrador y Ambiente de trabajo Arquitectura se comportan un poco diferente que los otros bancos de trabajo de arriba, a pesar que ellos siguen las mismas reglas, las cuales son comunes de todo FreeCAD. En breve, mientras el Boceto y diseño de parte están hechas primeramente para diseñar piezas sencillas, borrador y arquitectura son hechos para facilitar tu trabajo cuando están trabajando con varios, objetos sencillos.

El Ambiente de trabajo Borrador le ofrece herramientas 2D un poco similares a las que puede encontrar en aplicaciones CAD 2D tradicionales como AutoCAD. Sin embargo, el dibujo en 2D está muy lejos del alcance de FreeCAD, no espere encontrar allí la gama completa de herramientas que ofrecen estas aplicaciones dedicadas. La mayoría de las herramientas Borrador funcionan no solo en un plano 2D sino también en el espacio 3D completo, y se benefician de los sistemas auxiliares especiales tales como Planos de trabajo y Atrapar objeto.

El Ambiente de trabajo Arquitectura agrega herramientas modelado de información de construcción (BIM) a FreeCAD, lo que le permite construir modelos arquitectónicos con objetos paramétricos. El Ambiente de trabajo Arquitectura se basa mucho en otros módulos, como Borrador y Croquizador. Todas las herramientas de borrador están también presentes en el ambiente de trabajo de Arquitectura, y la mayoría de las herramientas de Arquitectura hacen uso de los sistemas de ayuda de Borrador.

Un flujo de trabajo típico con los ambientes de trabajo Arquitectura y Borrador podría ser:

  1. Dibuja un par de líneas con la herramienta línea de Borrador
  2. Selecciona cada línea y presione la herramienta Muro para construir un muro en cada una de ellas
  3. Une las paredes seleccionándolas y presionando la herramienta Arquitectura Add
  4. Crea un objeto de piso y mueve tus muros dentro desde la vista de árbol
  5. Crea un objeto de construcción y mueve tu piso dentro desde la vista de árbol
  6. Crea una ventana haciendo clic en la herramienta Ventana, selecciona un ajuste preestablecido en su panel y luego haz clic en una cara de un muro
  7. Añade dimensiones configurando primero el plano de trabajo si es necesario, luego usando la herramienta Borrador Dimension

El cual te dará esto:

Más en la Tutorialespágina.

Complementos, Macro y Ambiente de trabajo Externos

El principio de Complementos se basa en el desarrollo de un complemento del ambiente de trabajo. Cualquier usuario puede desarrollar una función que considere que falta para sus propias necesidades o, en última instancia, para la comunidad. Con el foro, el usuario puede solicitar una opinión, una ayuda en el foro. Puede compartir, o no, el objeto de su desarrollo según las normas de derechos de autor a definir. Libre para ella/él. Para desarrollar, el usuario dispone de funciones de guiones.

Hay dos tipos de complementos:

  1. Macros: breves fragmentos de código Python que proporcionan una nueva herramienta o funcionalidad. Las macros suelen empezar como una forma de simplificar o automatizar la tarea de dibujar o editar un objeto concreto. Si muchas de estas macros se reúnen dentro de un directorio, todo el directorio puede ser distribuido como un nuevo ambiente de trabajo.
  2. Ambientes de trabajo externos: colecciones de herramientas programadas en Python o C++ que extienden FreeCAD de forma importante. Si un ambiente de trabajo está suficientemente desarrollado y está bien documentado, puede ser incluido como uno de los ambientes de trabajo base en FreeCAD. En Ambientes de trabajo externos, encontrarás el principio y una lista de las bibliotecas existentes.

Guión

Y finalmente, una de las características más poderosas de FreeCAD es el entorno scripting. Desde la consola python integrada (o desde cualquier otro script python externo), se puede acceder a casi cualquier parte de FreeCAD, crear o modificar la geometría, modificar la representación de esos objetos en la escena 3D o acceder y modificar la interfaz de FreeCAD. El script Python también se puede utilizar en macros, que proporcionan un método sencillo para crear comandos personalizados.

¿Qué hay de nuevo


Trabajando con FreeCAD

Navegación 3D


Overview

Vista general

La Navegación Ratón de FreeCAD consiste en los comandos utilizados para navegar visualmente por el espacio tridimensional e interactuar con los objetos mostrados. Actualmente hay 3 esquemas diferentes de navegación con el ratón en FreeCAD. El estilo de navegación por defecto se denomina "Navegación CAD", y es muy simple y práctico, pero FreeCAD también tiene dos estilos de navegación alternativos modelados según la navegación de Inventor y Blender.

For more information about selecting objects see Selection methods.

For more information about manipulating objects see Std TransformManip.

Selecting a navigation style

  • En el Editor de Preferencias, sección Display, pestaña Vista 3D;
  • Pulsando con el botón derecho en un área vacía de la vista 3D y seleccionando Estilo de navegación en el menú contextual.

Available navigation styles

With all navigation styles, unless selecting objects from a sketch in edit mode, you must hold Ctrl to select multiple objects.

Navegación de Blender

The Blender navigation style was modeled after Blender.

En la Navegación de Blender, no se puede hacer un encuadre sólo con el ratón. Para hacer un encuadre, debes mantener presionada la tecla SHIFT.

Selección Encuadre Zoom Rotar vista
Selección shift+Encuadre o Zoom Rotar vista
Presiona el botón izquierdo del ratón sobre el objeto que quieras seleccionar. Mantén presionada la tecla de mayúsculas (shift) y pulsa el botón del medio del ratón, o mantenga presionados los botones Izquierda y Derecha y mueva. Utiliza la rueda del ratón para alejar o acercar la vista. Pulsa y arrastra con el botón del medio del ratón.


Select Pan Zoom Rotate view
Shift+
Press the left mouse button over an object you want to select. Hold Shift and the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, and then move the pointer.

Use the mouse wheel to zoom in and out. Hold the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, and then move the pointer. |Zoom_text=Use the mouse wheel to zoom in and out. |Rotate_view_text=Hold the middle mouse button, then move the pointer. }}

CAD navigation

Navegación CAD

Este es el estilo de navegación por defecto y permite al usuario un control simple de la vista, y no requiere el uso del teclado con la excepción de la realización de selecciones múltiples.

Select Pan Zoom Rotate view
First method
Rotate view
Alternate method
Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Clicking the middle mouse button re-centers the view on the location of the cursor.

Hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

If the buttons are released before you stop the mouse motion, the view continues spinning, if this is enabled.

A double click with the middle mouse button sets a new center of rotation.

Hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

With this method the middle mouse button may be released after the right mouse button is held pressed.

Users who use the mouse with their right hand may find this method easier than the first method.

Ctrl+ Ctrl+Shift+ Shift+
Pan mode: hold the Ctrl key, press the right mouse button once, then move the pointer. Zoom mode: hold the Ctrl and Shift keys, press the right mouse button once, then move the pointer. Rotate mode: hold the Shift key, press the right mouse button once, then move the pointer.

Navegación Gestual

This style was tailored for use with a touchscreen and pen. Nevertheless, it can also be used with a mouse, and is recommended for use when using a Mac with a trackpad.

This navigation style was tailored for usability with touchscreen and pen, but is very usable with mouse too.

Select Pan Zoom Rotate view Tilt view
Press the left mouse button over an object you want to select. Hold the right mouse button, then move the pointer. Use the mouse wheel to zoom in and out. Hold the left mouse button, then move the pointer.

In Sketcher and other edit modes, this behavior is disabled. Hold Alt when pressing the mouse button to enter rotation mode.

To set the camera's focus point for rotation, click a point with the middle mouse button. Alternatively, aim the cursor at a point and press H on the keyboard.

Hold both left and right mouse buttons, and then move the pointer sideways.
Tap to select. Drag with two fingers.

Alternatively, tap and hold, then drag. This simulates the pan with the right mouse button.

Drag two fingers (pinch) closer or farther apart. Drag with one finger to rotate.

Hold Alt when in the Sketcher.

Rotate the imaginary line formed by two touch points.

On v0.18 this method is disabled by default. To enable, go to Edit → Preferences → Display, and untick "Disable touchscreen tilt gesture" checkbox.

Alternatively, tap and hold, then drag. This simulates the pan with the right mouse button. |Zoom_text=Use the mouse wheel to zoom in and out. |Zoom_gesture_text=Drag two fingers (pinch) closer or farther apart. |Rotate_view_text=Hold the left mouse button, then move the pointer. In Sketcher and other edit modes, this behavior is disabled. Hold Alt when pressing the mouse button to enter rotation mode.

To set the camera's focus point for rotation, click a point with the middle mouse button. Alternatively, aim the cursor at a point and press H on the keyboard. |Rotate_view_gesture_text=Drag with one finger to rotate.

Hold Alt when in the Sketcher. |Tilt_view_text=Hold both left and right mouse buttons, then move the pointer sideways. |Tilt_view_gesture_text=Rotate the imaginary line formed by two touch points.

This method is disabled by default. To enable, go to Edit → Preferences → Display → Navigation, and uncheck the "Disable touchscreen tilt gesture" checkbox. }}

Navegación Maya-Gestual

In Maya-Gesture Navigation, panning, zooming, and rotating the view require the Alt key together with a mouse button; therefore, a three-button mouse is required. It's also possible to use gestures as this style was developed over the Gesture navigation style.

Selección Pan Zoom Rotar la vista
{KEY+ {KEY+ {KEY+
{{{Select_text}}} {{{Pan_text}}} {{{Zoom_text}}} {{{Rotate_view_text}}}

|Select_text=Presione el botón izquierdo del ratón sobre un objeto que desee seleccionar. |Pan_text=Mantenga pulsados Alt y el botón central del ratón, luego mueva el puntero. |Zoom_text=Mantenga pulsados Alt y el botón derecho del ratón, luego mueva el puntero.

Alternatively, use the mouse wheel to zoom in and out. |Rotate_view_text=Hold Alt and the left mouse button, then move the pointer. }}

OpenCascade

The OpenCascade navigation style was modeled after OpenCascade.

Select Pan Zoom Rotate view
Ctrl+ Ctrl+ Ctrl+


Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Alternatively, hold Ctrl and the left mouse button, then move the pointer.

Hold Ctrl and the right mouse button, then move the pointer.

OpenInventor navigation

Navegación de Inventor

La navegación de OpenInventor (antes Inventor) fue modelada según Open Inventor. Para seleccionar los objetos, debe mantener pulsada la tecla Ctrl.

Este modo no está basado en el Autodesk Inventor.

Select Pan Zoom Rotate view
Shift+
Hold Shift, then press the left mouse button over an object you want to select.

Hold Ctrl instead to select multiple objects.

Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Alternatively, hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

Hold the left mouse button, then move the pointer.

OpenSCAD navigation

The OpenSCAD navigation style was modeled after OpenSCAD.

introduced in version 0.20

Select Pan Zoom Rotate view
Shift+
Press the left mouse button over an object you want to select.

version 0.21 and below Hold Ctrl and Shift when pressing the mouse button to drag an object in a sketch in edit mode.

Hold the right mouse button, then move the pointer. Hold the middle mouse button, then move the pointer.

Alternatively, hold Shift and the right mouse button, then move the pointer.

Hold the left mouse button, then move the pointer.

Alternatively, and when a sketch is in edit mode, hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

Navegación Revit

The Revit navigation style was modeled after Revit.

Select Pan Zoom Rotate view
Shift+


Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, then move the pointer.

Use the mouse wheel to zoom in and out. Hold Shift and the middle mouse button, then move the pointer.

Alternatively, hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

TinkerCAD navigation

The TinkerCAD navigation style was modeled after TinkerCAD.

introduced in version 0.20

Select Pan Zoom Rotate view
Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out. Press the right mouse button, then move the pointer.

Navegación Touchpad

With the Touchpad navigation style, panning, zooming, and rotating the view require a modifier key together with the touchpad. This style can also be used with a mouse.

En la Navegación Touchpad, ni el barrido, ni el acercamiento, ni la rotación de vista son operaciones exclusivas del ratón (o del touchpad).

Select Pan Zoom Rotate View
to Select shift+to Pan PgUp / PgDn alt+to Rotate
Press the left mouse button over an object you want to select. Hold shift and move the object around. Use PgUp and PgDn to zoom in and out. Hold alt and move the pointer.
or or
shift+ctrl+to Zoom shift+ctrl+to ROtate
Hold down both the shift and the ctrl keys, press the left mouse button, and move the pointer. Hold down both the shift and the ctrl keys and move the pointer.


Select Pan Zoom Rotate view
Shift+ PageUp, PageDown Alt+
Press the left mouse button over an object you want to select. Hold Shift, then move the pointer. Use PageUp and PageDown to zoom in and out. Hold Alt, then move the pointer.
Ctrl+Shift+ Shift+
Alternatively, hold Shift and Ctrl, then move the pointer. Alternatively, hold Shift and the left button, then move the pointer.

Soporte de Hardware

FreeCAD también soporta algún Dispositivo de entrada 3D.

Problemas en Mac OS X

Recientemente hemos recibido reportes en el foro de usuarios Mac que esas combinaciones de ratón y tecla no funcionan como se espera. Desafortunadamente, ninguno de los desarrolladores posee una Mac, tampoco otros contribuidores regulares. Necesitamos de tu ayuda para determinar que combinaciones de ratón y tecla funcionan para poder actualizar este wiki.

Developing a custom navigation

The tutorial Adding a new mouse navigation option to FreeCAD orients developers who want to develop a custom mouse navigation option. Familiarity with the C++ syntax is required.


El documento de FreeCAD


Un documento FreeCAD contiene todos los objetos de la escena. Puede contener grupos y objetos hechos con cualquier entorno de trabajo. Por lo tanto, puedes cambiar entre los entornos de trabajo, y seguir trabajando en el mismo documento. El documento es lo que se guarda en el disco al guardar tu trabajo. También puedes abrir varios documentos al mismo tiempo en FreeCAD, y abrir varias vistas del mismo documento.

En el documento, los objetos se pueden mover e incorporar a grupos, y cada objeto tiene un nombre único, exclusivo. La gestión de grupos, objetos y nombres de objeto se hace principalmente en la vista de árbol. También se puede hacer, por supuesto, como todo en FreeCAD, desde el intérprete de Python. En la vista de árbol, se pueden crear grupos, mover objetos a grupos, eliminar objetos o grupos,... haciendo clic con el botón derecho del ratón en la vista en árbol o en un objeto, cambiar el nombre de los objetos haciendo doble clic sobre sus nombres,... o posiblemente otras operaciones, en función del entorno de trabajo en curso.

Los objetos dentro de un documento FreeCAD pueden ser de diferentes tipos. Cada entorno de trabajo puede crear sus propios tipos de objetos, por ejemplo, el Entorno de trabajo de mallas crea objetos de malla, el Entorno de trabajo de piezas crear objetos de piezas, el Entorno de croquizado 2D también crea objetos Pieza, etc

Si hay uno o más documentos abiertos en FreeCAD, siempre alguno de ellos, y sólo uno, será el documento activo. Ese es el documento que aparece en la vista 3D actual, el documento con el que se está trabajando actualmente.

Aplicación e interfaz de usuario

Como casi todo lo demás en FreeCAD, la interfaz de usuario (GUI) del entorno de trabajo de piezas está separada de la aplicación base de piezas. Esto también es válido para los documentos. Los documentos también están hechos de dos partes: el documento de la aplicación, que contiene nuestros objetos, y el documento Vista, que contiene la representación en pantalla de nuestros objetos.

Piensa en ello como dos espacios, donde los objetos están definidos. Sus parámetros constructivos (¿es un cubo? ¿Un cono? ¿Qué tamaño? ...) se almacenan en el documento de aplicación, mientras que su representación gráfica (¿es dibujado con línea negra? ¿Con las caras azules? ...) se almacena en el documento Vista. ¿Por qué? Porque FreeCAD también puede ser utilizado sin interfaz gráfica, por ejemplo dentro de otros programas y, aún así, tenemos que ser capaces de manipular nuestros objetos, incluso si no se dibujan en la pantalla.

Otra cosa que está contenida en el documento Vista son las vistas 3D. Un documento puede tener varias vistas abiertas, así que puedes inspeccionar tu documento desde varios puntos de vista al mismo tiempo. Tal vez te gustaría ver una vista superior y una vista frontal de tu trabajo, al mismo tiempo. De ese modo, tendrías dos puntos de vista del mismo documento, ambos almacenados en el documento Vista. Crear puntos de vista nuevos o cerrar vistas se puede hacer desde el menú Vista o haciendo clic derecho en la pestaña de una vista.

Archivos de guión

Los documentos se pueden crear fácilmente, acceder y modificar desde el intérprete de Python. Por ejemplo:

FreeCAD.ActiveDocument

devolverá el documento activo actual

FreeCAD.ActiveDocument.Blob

accedería a un objeto llamado "Blob" dentro de tu documento

FreeCADGui.ActiveDocument

devolvería el documento vista asociado al documento actual

FreeCADGui.ActiveDocument.Blob

accedería a la parte representación gráfica (vista) de nuestro objeto Blob

FreeCADGui.ActiveDocument.ActiveView

devolverá la vista actual


Definiendo las preferencias de usuario


Introducción

Para iniciar el Editor de preferencias seleccione la opción Edición → Preferencias... del menú. En Mac OS la opción Preferencias... aparece en el menú FreeCAD (este es el lugar por defecto para las preferencias en Mac).

FreeCAD utiliza un concepto de ambiente de trabajo, donde cada ambiente de trabajo es responsable de tareas y funciones específicas. Un ambiente de trabajo puede tener sus propias preferencias. Estas sólo aparecerán en el editor de Preferencias si el ambiente de trabajo ha sido cargado en la sesión actual de FreeCAD. Ver Ambiente de trabajo más abajo para más información.

To preserve resources, FreeCAD does not automatically load all available workbenches. See Workbenches for more information. For a list of workbench related preferences see Workbench related preferences.

Si no hay ningún ambiente de trabajo cargado, aparecen cuatro secciones en el editor de Preferencias: General, Pantalla, Ambientes de trabajo, y Importación-Exportación. Cualquier ambiente de trabajo que haya sido cargado, y tenga sus propias preferencias, aparecerá debajo de estos.

Pressing the Reset button in the lower left corner of the Preferences dialog opens a menu (introduced in version 0.22) with options to reset preferences to their default values. You can reset the current tab, the current group, or all preferences. In version 0.21 and below the button will reset all preferences.

Some advanced preferences can only be changed in the Parameter editor. The Fine-tuning page lists some of them.

Configuración general

Esta sección de preferencias tiene 7 pestañas: General, Documento, Selección, Editor, Ventana de salida, Macro y Unidades.

In version 0.21 and below the seventh tab, Help, is only available if the Help Addon has been installed.

General

On the General tab you can specify the following:

Name Description
Language Language of the application's user interface.
Default unit system Unit system for all parts of the application. introduced in version 0.22: Used as the default for the document unit system of new documents.
Number of decimals The number of decimals that should be shown for numbers and dimensions.
Ignore project unit system and use default introduced in version 0.22 If checked, project unit systems are ignored and do not override the default unit system.
Minimum fractional inch The minimum fractional inch that should be shown for numbers and dimensions. Only available for unit systems with fractional inches.
Number format introduced in version 0.20 Specifies the number format. The options are:
  • Operating system: The decimal separator defined by the operating system is used.
  • Selected language: The decimal separator of the selected FreeCAD interface language is used.
  • C/POSIX: A point is used as the decimal separator.
Substitute decimal separator introduced in version 0.20 If checked, the numerical keypad decimal separator will be substituted with the separator defined by the Number format setting. introduced in version 0.21: Notice that if this preference is enabled, using the numerical keypad decimal separator will always print a dot/period in the Python console and the Macro editor.
Theme Specifies a theme to customize the appearance of the user interface.
Size of toolbar icons Specifies the size of the toolbar icons. The options are:
  • Small (16px)
  • Medium (24px)
  • Large (32px)
  • Extra large (48px)
Tree view mode Defines how the tree view is shown in the user interface (restart required). The options are:
  • Combo View: Combines the tree view and the property view into one panel.
  • TreeView and PropertyView: Splits the tree view and the property view into separate panels.
  • Both: Shows all three panels. version 0.21 and below
Size of recent file list Specifies how many files should be listed in the recent files list.

Optionally, imported files can be excluded from this list, and exported files can be included. See Fine-tuning.

Enable tiled background If checked, the background of FreeCAD's main window will by default consist of tiles of this image:

This option only has an effect if no Style sheet is selected.

The image can be changed by adding the folders Gui/Images in the folder:

%APPDATA%/FreeCAD (on Windows),

$HOME/.FreeCAD (on Linux) or

$HOME/Library/Preferences/FreeCAD (on macOS).

Place a file named background.png in the Images folder, and uncheck/check this option to see the changed file.

Enable splash screen at start up If checked, a splash screen is shown when starting FreeCAD.

The splash screen image can be changed by placing a file named splash_image.png in the Images folder already mentioned under Enable tiled background.

Enable cursor blinking If checked the text cursor in the Python console and the Macro editor will blink.
Activate overlay handling introduced in version 0.22 If checked, docked windows can be handled as transparent overlays.
Preference packs introduced in version 0.20 Lists the available preference packs and also allows you to import, save, manage and revert them.

Documento

On the Document tab you can specify the following:

Name Description
Create new document at start up If checked, FreeCAD will create a new document when started.
Document save compression level Specifies the compression level for FCStd files. FCStd files are ZIP-compressed files. Therefore you can rename their suffix .FCStd to .zip and open them with a ZIP archive program.
Using Undo/Redo on documents If checked, all changes in documents are stored so that they can be undone/redone.
Maximum Undo/Redo steps Specifies how many Undo/Redo steps should be recorded.
Allow aborting recomputation If checked, recomputations can be aborted by pressing Esc. This may slightly increase the recomputation time.
Run AutoRecovery at startup If there is a recovery file available FreeCAD will automatically run a file recovery when it is started. This way files can be restored if a crash occurred.
Save AutoRecovery information every Specifies how often a recovery file is written.
Save thumbnail into project file when saving document If checked, a thumbnail will be stored when the document is saved. The thumbnail will for example be shown in the list of recent files in the Start Workbench. It is possible to select a Size between 128×128 and 512×512 pixels for the thumbnail. Common sizes are powers of two: 128, 256, 512.
Add the program logo to the generated thumbnail If checked, the FreeCAD program logo will be added to the thumbnail.
Maximum number of backup files to keep when resaving document If checked, backup files will be kept when saving the document. You can specify the number of backup files to keep. Backup files are previously saved versions of the document. The first backup file will have the file suffix .FCStd1, the second .FCStd2 and so on.
Use date and FCBak extension If checked, backup files will get the extension .FCbak and their file names get a date suffix according to the specified Date format. For a description of the date format see Date & time formats cheatsheet.

With the default settings a backup file will for example get this name TD-Cube.20200315-215654.FCBak (original filename is TD-Cube.FCStd).

Allow duplicate object labels in one document If checked, objects can have the same label.
Disable partial loading of external linked objects If partial loading of external linked objects is enabled, only the referenced objects and their dependencies will be loaded when the linked document is auto opened together with the main document. Such a partially loaded document cannot be edited. Double click the document icon in the tree view to reload it in full. A more detailed explanation of this feature can be found on the Assembly3 documentation page.
Author name All created documents will get the specified author name. Keep the author field blank if you do not want to include this information. If the option Set on save is checked, the field Last modified by will be set to the specified author when saving the file. This field can be viewed using the File → Project information menu option.
Company All created documents will get the specified company name.
Default license Specifies the license for new documents. For predefined licenses the License URL will automatically be set accordingly. Select Other for a custom license.
License URL Specifies an URL describing the license selected in Default license.

Selección

On the Selection tab you can specify the following:

Name Description
Auto switch to the 3D view containing the selected item Enables the Tree view SyncView mode.
Auto expand tree item when the corresponding object is selected in 3D view Enables the Tree view SyncSelection mode.
Preselect the object in 3D view when mouse over the tree item Enables the Tree view PreSelection mode.
Record selection in tree view in order to go back/forward using navigation button Enables the Tree view RecordSelection mode.
Add checkboxes for selection in document tree Each Tree view item will get a checkbox. This is for example useful for selecting multiple items on a touchscreen.

Cache

These preferences are related to the cache directory where FreeCAD stores temporary files.

On the Cache tab (introduced in version 0.20) you can specify the following:

Name Description
Location Specifies the path of the cache directory.
Check periodically at program start Controls the frequency with which the directory size is checked. The options are:
  • Always
  • Daily
  • Weekly
  • Monthly
  • Yearly
  • Never
Cache size limit Specifies the maximum size of the directory. You will be notified if a check is performed and the size exceeds this value. The options are:
  • 100 MB
  • 300 MB
  • 500 MB
  • 1 GB
  • 2 GB
  • 3 GB
Current cache size Shows the current size of the directory, if available. Press the Check now... button to update the value.

Notification Area

These preferences control the Notification Area and its notifications.

On the Notification Area tab (introduced in version 0.21) you can specify the following:

Name Description
Enable Notification Area If checked, the Notification Area will appear in the status bar.
Enable non-intrusive notifications If checked, non-intrusive notifications will appear next to the Notification Area in the status bar.
Errors If checked, errors will appear in the Notification Area.
Warnings If checked, warnings will appear in the Notification Area.
Maximum Duration Maximum duration during which notifications are shown (unless mouse buttons are clicked).
Minimum Duration Minimum duration (idem).
Maximum Number of Notifications Maximum number of notifications shown simultaneously.
Notification width Width of the Notification Area in pixels.
Hide when other window is activated If checked, open notifications will disappear when another window is activated.
Do not show when inactive If checked, notifications will not appear if the FreeCAD window is not the active window.
Maximum Messages (0 = no limit) The maximum number of messages kept in the list. Set to 0 for no limit.
Auto-remove User Notifications If checked, notifications will be removed from the message list when the Maximum Duration has elapsed.

Report view

These preferences control the behavior of the Report view. This panel can be opened using the View → Panels → Report view menu option.

On the Report view tab you can specify the following:

Name Description
Record normal messages If checked, normal messages will be recorded. They will be displayed in the Report view with the color set in Normal messages.
Record log messages If checked, log messages will be recorded. They will be displayed in the Report view with the color set in Log messages.
Record warnings If checked, warnings will be recorded. They will be displayed in the Report view with the color set in Warnings.
Record error messages If checked, error messages will be recorded. They will be displayed in the Report view with the color set in Errors.
Show report view on error If checked, the Report view will be shown automatically when an error is recorded.
Show report view on warning If checked, the Report view will be shown automatically when a warning is recorded.
Show report view on normal message If checked, the Report view will be shown automatically when a normal message is recorded.
Show report view on log message If checked, the Report view will be shown automatically when a log message is recorded.
Include a timecode for each entry If checked, each message and warning will receive a timecode.
Normal messages Specifies the font color for normal messages.
Log messages Specifies the font color for log messages.
Warnings Specifies the font color for warning messages.
Errors Specifies the font color for error messages.
Redirect internal Python output to report view If checked, internal Python output will be redirected from the Python console to the Report view.
Redirect internal Python errors to report view If checked, internal Python error messages will be redirected from the Python console to the Report view.

Help

On the Help tab you can specify the following:

Name Description
Help location Specifies the location of the Help files. The options are:
  • Online: Enter the URL or leave blank to use the automatic GitHub URL.
Translation suffix: If https://wiki.freecad.org/ is used, a language suffix can be specified. Use for example fr for the French translation. Must be blank for the GitHub URL.
  • From disk location: Enter the path where the downloaded FreeCAD documentation can be found. To download the documentation select the offline-documentation addon from the Workbenches list in the Addon Manager.
Display Specifies where the documentation should be displayed. The options are:
  • In a new FreeCAD tab: The documentation is displayed on a new tab in the Main view area.
  • In your default web browser: The documentation is displayed in the default web browser.
  • In a separate, embeddable, dialog: The documentation is displayed in a separate dialog. This dialog can be docked on top of the Combo view for example.
Custom stylesheet Specifies an optional custom stylesheet. Not used for the Wiki URL.

Configuración de la pantalla

This preferences section has three standard tabs: 3D View, Navigation and Colors. A fourth tab, Mesh view, is added if the Mesh Workbench has been loaded.

Vista 3D

On the 3D View tab you can specify the following:

Name Description
Show coordinate system in the corner If checked, the main coordinate system will be shown in the lower right corner of the 3D view.

The Relative size (introduced in version 0.20) defines the size of the representation as a percentage of the view size (the minimum of its height and width).

Show axis cross by default If checked, the axis cross will be shown by default in the 3D view.
Show counter of frames per second If checked, the time needed for the last operation and the resulting frame rate will be shown in the lower left corner of the 3D view.
Use software OpenGL If checked, OpenGL will use the CPU instead of the GPU. This option is useful for troubleshooting graphics card and driver problems. Changing this option requires a restart of the application.
Use OpenGL VBO (Vertex Buffer Object) If checked, Vertex Buffer Objects (VBO) will be used. A VBO is an OpenGL feature that provides methods for uploading vertex data (position, normal vector, color, etc.) to the graphics card. VBOs offer substantial performance gains because the data resides in the graphics memory rather than the system memory and so it can be rendered directly by the GPU. For more background info see Understanding OpenGL Objects.
Render Cache "Render Cache" or "Render Acceleration" is explained in more detail in FreeCAD assembly3 render-caching. The options are:
  • Auto: Let Coin3D decide where to cache (default).
  • Distributed: Manually turn on cache for all view provider root nodes.
  • Centralized: Manually turn off cache in all nodes of all view providers, and only cache at the scene graph root node. This offers the fastest rendering speed, but slower response to any scene changes.
Anti-Aliasing Specifies if and what type of multisample anti-aliasing is used
Transparent objects Specifies the render type of transparent objects. The options are:
  • One pass: Rendering is done in one pass (default). This can lead to triangular artifacts. If these occur the type Backface pass can be used to avoid them.
  • Backface pass: Rendering is done in two passes. Back-facing polygons are rendered in the first pass and front-facing polygons in the second pass.
Marker size Specifies the size of vertices (points) in the Sketcher Workbench. The clickable area of points can be additionally enlarged by increasing the Pick radius.
Pick radius (px) Sets the area for picking elements in the 3D view. Larger value makes it easier to pick things, but can make some small features impossible to select.
Eye to eye distance for stereo modes Specifies the eye-to-eye distance used for stereo projections. The specified value is a factor that will be multiplied with the bounding box size of the 3D object that is currently displayed.
Backlight color If checked, backlight is enabled with the defined color. Backlight is used for rendering the back sides of faces. Usually, you don't see them in solids, unless you slice one with a clipping plane, or if the faces aren't oriented correctly. It is only used for objects whose Lighting property (on the View tab) is set to One side. If disabled, the back side of the faces of those objects will be black.

The related Intensity setting specifies the intensity of the backlight.

Camera type Specifies the camera projection type. The options are:

Navegación

On the Navigation tab you can specify the following:

Name Description
Navigation cube If checked, the Navigation cube will be shown in the 3D view.

Steps by turn defines the number of steps required for a full rotation when using the Navigation cube rotation arrows.

If Rotate to nearest is checked, the 3D view is rotated to the nearest most logical position, based on the current orientation of the cube, when a cube face is clicked. Else clicking a face will always result in the same rotation. introduced in version 0.20

Cube size defines the size of the cube. introduced in version 0.20

Color sets the base color for all elements. introduced in version 0.21

Corner defines where the Navigation cube is displayed in the 3D view. The options are:

  • Top left
  • Top right
  • Bottom left
  • Bottom right

Font name specifies the font used for the cube's texts. introduced in version 0.21

Font size sets the size of the font used for the cube's texts. introduced in version 0.21

3D Navigation Specifies a mouse navigation style. To see the details of each style, select it and then press the Mouse... button.
Orbit style Specifies the rotation orbit style used when in rotation mode. The options are:
  • Turntable: Moving the mouse will divide the rotation in steps, rotations around the different axes are performed sequentially.
  • Trackball: Rotations around the different axes are performed simultaneously.
  • Free Turntable: Like Trackball, but if possible the rotation axis is kept collinear with the global 3D view axis. introduced in version 0.21
Rotation mode Defines the rotation center. The options are:
  • Window center
  • Drag at cursor
  • Object center
Default camera orientation Specifies the camera orientation for new documents. This setting is also used by the Std ViewHome command.
Camera zoom Affects the initial camera zoom level for new documents. The value you set is the diameter of a sphere that fits in 3D view. The default is 100 mm. It also sets the initial size of origin features (base planes in new PartDesign Bodies and Std Parts).
Enable animation If checked, and 3D Navigation is set to CAD, rotations can be animated. If the mouse is moved while the scroll wheel and the right mouse button are pressed, the view is rotated. If one keeps the mouse moving while releasing the right mouse button, the rotation will continue. To end this animation left-click with the mouse.
Zoom at cursor If checked, zoom operations will be performed at the position of the mouse pointer. Otherwise zoom operations will be performed at the center of the current view. The Zoom step defines how much will be zoomed. A zoom step of 1 means a factor of 7.5 for every zoom step.
Invert zoom If checked, the direction of zoom operations will be inverted.
Disable touchscreen tilt gesture If checked, and 3D Navigation is set to Gesture, the tilting gesture will be disabled for pinch-zooming (two-finger zooming).
Enable rotation center indication If checked, the rotation center of the view is shown when dragging. introduced in version 0.22

Colores

On the Colors tab you can specify the following:

Name Description
Enable preselection highlighting If checked, preselection is turned on and the specified color will be used for it. Preselection means that for example edges of objects will be highlighted while hovering over them with the mouse to indicate they can be selected.
Enable selection highlighting If checked, selection highlighting is turned on and the specified color will be used for it.
Simple color If selected, the background of the 3D view will have the specified color.
Linear gradient If selected, the background of the 3D view will have a vertical color gradient defined by the specified Top and Bottom colors. if enabled, a Middle color can also be specified. Press the button (introduced in version 0.21) to switch the top and bottom colors.
Radial gradient introduced in version 0.21 If selected, the background of the 3D view will have a radial color gradient defined by the specified Central and End colors. if enabled, a Midway color can also be specified. Press the button to switch the central and end colors.
Object being edited Specifies the background color for objects in the tree view that are currently edited.
Active container Specifies the background color for active containers in the tree view. For example an active PartDesign Body will get this color.

Vista de malla

This tab is only available if the Mesh Workbench has been loaded.

On the Mesh view tab you can specify the following:

Name Description
Default mesh color Specifies the default face color.
Default line color Specifies the default line color.
Mesh transparency Specifies the default mesh transparency.
Line transparency Specifies the default line transparency.
Two-side rendering If checked, the default value for the VistaLighting property is Two side instead of One side. Two side means the color of the interior side of faces is the same as the color of the exterior side. One side means their color is either the backlight color, if enabled, or black.
Show bounding-box for highlighted or selected meshes If checked, the default value for the VistaSelection Style property is BoundBox instead of Shape. BoundBox means a highlighted bounding box is displayed if meshes are highlighted or selected. Shape means the shape itself is then highlighted.
Define normal per vertex If checked, Phong shading is used, otherwise flat shading. Shading defines the appearance of surfaces. With flat shading the surface normals are not defined per vertex. This leads to an unrealistic appearance for curved surfaces. While Phong shading leads to a more realistic, smoother appearance.
Crease angle The crease angle is a threshold angle between two faces. It can only be set if the option Define normal per vertex is used.
If face angle ≥ crease angle, facet shading is used.
If face angle < crease angle, smooth shading is used.

Ambientes de trabajo

This preferences section has a single tab: Available Workbenches.

Ambiente de trabajo descarga

These preferences control workbench loading.

On the Available Workbenches tab you can specify the following:

Name Description
Workbench list The list displays all installed workbenches. The list can be reordered by drag and drop (introduced in version 0.21) and sorted by right-clicking the list and selecting Sort alphabetically (introduced in version 0.22). The order of the list also determines the order of the Workbench selector.
  • introduced in version 0.21: First checkbox in each row: If checked, the workbench will be available in the Workbench selector in the next FreeCAD session. The start up workbench cannot be unchecked. Unchecked workbenches are moved to the bottom of the list.
  • Auto-load: If checked, the workbench will auto-load when FreeCAD starts. Loading more workbenches will make the start up slower, but switching between workbenches that have already been loaded is faster.
  • Load: Press this button to load the workbench in the current FreeCAD session.
Start up workbench The workbench that is activated when FreeCAD starts.
Workbench selector position introduced in version 0.21 Defines where the Workbench selector appears. The options are:
  • Toolbar: In a dedicated toolbar.
  • Left corner: In the left corner of the menubar.
  • Right corner: In the right corner of the menubar.
Remember active workbench by tab If checked, FreeCAD will remember and restore the workbench that was active for each tab in the Main view area.

Python

This preferences section (introduced in version 0.21) has three tabs: Macro, Python console and Editor.

Macro

On the Macro tab you can specify the following:

Name Description
Run macros in local environment If checked, variables defined by macros are created as local variables, otherwise as global Python variables.
Macro path Specifies the path for macro files.
Record GUI commands If checked, recorded macros will also contain user interface commands.
Record as comment If checked, recorded macros will also contain user interface commands, but as comments. This is useful if you don't want to execute these commands when running the macro, but do want to see what has been done while recording.
Show script commands in python console If checked, the commands executed by macro scripts are shown in the Python console. This console can be opened using the View → Panels → Python console menu option.
Size of recent macro list Controls the number of recent macros to display in the menu.
Shortcut count Controls the number of recent macros that get dynamically assigned shortcuts.
Keyboard Modifiers Controls which keyboard modifiers are used for the shortcuts, example Ctrl+Shift+ creates shortcuts in the form of Ctrl+Shift+1, Ctrl+Shift+2, etc.

Python console

These preferences control the behavior of the Python console. This console can be opened using the View → Panels → Python console menu option.

Note that the color and font settings for the console are defined on the Editor tab.

On the Python console tab (introduced in version 0.20) you can specify the following:

Name Description
Enable word wrap If checked, words will be wrapped if they exceed the available horizontal space in the console.
Enable block cursor If checked, the cursor will have a block shape.
Save history If checked, Python history is saved across sessions.

Editor

These preferences control the behavior of the Macro editor. This editor can be opened using the Macro → Macros... → Edit or Create menu option.

The color and font settings are also used by the Python console.

On the Editor tab you can specify the following:

Name Description
Enable line numbers If checked, the code lines will be numbered.
Enable block cursor If checked, the cursor will have a block shape.
Tab size Specifies the tabulator raster (how many spaces). If it is for example set to 6, pressing Tab will jump to character 7 or 13 or 19 etc., depending on the current cursor position. This setting is only used if Keep tabs is selected.
Indent size Specifies how many spaces will be inserted when pressing Tab. This setting is only used if Insert spaces is selected.
Keep tabs If selected, pressing Tab will insert a tabulator with the raster defined by Tab size.
Insert spaces If selected, pressing Tab will insert the amount of spaces defined by Indent size.
Display Items Specifies the code type the color and font settings will be applied to. The result can be checked in the Preview field.
Family Specifies the font family that should be used for the selected code type.
Size Specifies the font size that should be used for the selected code type.
Color Specifies the color that should be used for the selected code type.

Addon Manager

This preferences section has a single tab: Addon manager options.

Addon manager options

These preferences control the behavior of the Addon manager.

On the Addon manager options tab (introduced in version 0.20) you can specify the following:

Name Description
Automatically check for updates at start (requires git) If checked, the Addon manager will check for updates when it is launched. Git must be installed for this to work.
Download Macro metadata (approximately 10MB) If checked, macro metadata is downloaded for display in the Addon manager's main addon listing. This data is cached locally.
Cache update frequency Controls the frequency with which the locally cached addon availability and metadata information is updated. The options are:
  • Manual (no automatic updates)
  • Daily
  • Weekly
Hide Addons marked Python 2 Only If checked, addons marked as "Python 2 Only" are not included in the listing. These addons are unlikely to work in the current FreeCAD version.
Hide Addons marked Obsolete If checked, addons marked as "Obsolete" are not included in the listing.
Hide Addons that require a newer version of FreeCAD If checked, addons that require a newer FreeCAD version are not included in the listing.
Custom repositories Custom repositories can be specified here.

To add a repository press the button. Both the Repository URL and the Branch, typically master or main, must be specifies in the dialog that opens. introduced in version 0.21

To remove a repository select it in the list and press the button. introduced in version 0.21

Proxy The Addon manager includes experimental support for proxies requiring authentication, set up as user-defined proxies.
Python executable (optional) The Addon manager attempts to determine the Python executable that should be used for the automatic pip-based installation of Python dependencies. To override this selection, the path to the executable can be set here.
git executable (optional) The Addon manager attempts to determine the git executable. To override this selection, the path to the executable can be set here. introduced in version 0.21
Show option to change branches (requires git) If checked, the Addon manager provides an interface on the addon's details screen that allows switching which git branch is currently checked out. This is intended for advanced users only, as it is possible that a non-primary-branch version of an addon may result in instability and compatibility issues. Git must be installed for this to work. Use with caution.
Disable git (fall back to ZIP downloads only) If checked, git downloads are disabled. introduced in version 0.21
Addon developer mode If checked, Addon manager options intended for developers of addons are activated. introduced in version 0.21

Configuración Importación-Exportación

The Import-Export preferences affect how files are imported and exported. They are described on the Import Export Preferences page.

Preferencias de l'ambiente de trabajo

Preferences for the built-in workbenches are linked below. These links are also listed in Category:Preferences. Some workbenches have no preferences.

El módulo Draft tiene su pantalla preferences

Scripting

See also: FreeCAD Scripting Basics.

For a scripting example see Std DlgParameter.

Relacionados


Personalizando la interfaz


Introducción

La interfaz de FreeCAD está basada en el moderno kit de herramientas Qt y tiene una organización a nivel de la técnica . Algunos aspectos de la interfaz pueden ser personalizados. Puedes, por ejemplo, añadir barras de herramientas personalizadas, con herramientas de varios ambientes de trabajo o herramientas definidas en macros, y puedes crear tus propios atajos de teclado. Pero los menús y las barras de herramientas por defecto que vienen con FreeCAD y sus ambientes de trabajo no se pueden cambiar.

introduced in version 0.21: The Workbenches tab is no longer available. Its functionality has been moved to the Available Workbenches tab in the Workbenches section of the Preferences Editor.

El cuadro diálogo Personalizar

Utilización

  1. Los comandos disponibles en el cuadro de diálogo Personalizar dependen de los ambientes de trabajo que se hayan cargado en la sesión actual de FreeCAD. Así que deberías cargar primero todos las ambientes de trabajo a cuyos comandos quieras tener acceso.
  2. Hay varias formas de invocar el Std DiálogoPersonalizar comando:
    • Seleccione la opción Herramientas → Personalizar... en el menú.
    • Haga clic con el botón derecho en un área de la barra de herramientas y elija Personalizar... en el menú contextual.
  3. Se abre el cuadro de diálogo Personalizar. Para más información, consulte Opciones.
  4. El botón Ayuda no funciona en este momento.
  5. Pulse el botón Cerrar para cerrar el cuadro de diálogo.

Opciones

En el cuadro de diálogo Personalizar están disponibles las siguientes pestañas:

Teclado

La pestaña del teclado

En esta pestaña se pueden definir atajos de teclado personalizados. Los atajos de teclado para los comandos de macros se pueden definir en la pestaña Macros.

Search

You can search for commands by entering at least 3 characters of their menu text or name in the search field. The search is case-insensitive.

It is also possible to search for shortcuts:

  • In the search field special keys in shortcuts must be entered as strings. For example to search for commands that use Ctrl in their shortcut enter ctrl (4 letters).
  • Add parenthesis to search for single character shortcuts, for example: (c).
  • Add a comma and space between the characters of multi-character shortcuts, for example: g, b, b.

Añadir un atajo personalizado

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
    • Optionally click the Command, Shortcut or Default column headings to reorder the list.
    • Optionally drag the splitter to the right of the panel to resize it.
  3. The Current shortcut box displays the current short cut, if available.
  4. Enter a new shortcut in the New shortcut input box. Shortcuts can be up to 4 inputs long. Each input is either a single character, a combination of one or more special keys or a combination of one or more special keys and a character. Use Backspace to correct mistakes.
  5. Other active commands (see Notes) that already use the shortcut will be listed in the Shortcut priority list.
  6. Press the Assign button to assign the new shortcut.
  7. If the Shortcut priority list contains more than one command: optionally change its order by selecting individual commands and pressing the Up button or the Down button. If active commands share the same shortcut, the shortcut will trigger the one that is highest in the list.

Remove a shortcut

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
  3. Press the Clear button.

Restore a default shortcut

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
  3. Press the Reset button.

Restore all default shortcuts

  1. Pulse el botón Reiniciar todo.

Notes

  • Shortcuts only work for active commands. Active commands are commands that appear in the standard menu, or in the menu of the active workbench, or commands that appear in a visible toolbar.

Inicio

Barras Herramientas

La pestaña Barras Herramientas

En esta pestaña se pueden crear y modificar barras de herramientas personalizadas.

Search

See Keyboard.

Seleccione el ambiente de trabajo

  1. In the dropdown list on the right select the workbench whose custom toolbars you want to modify. The Global option is there for custom toolbars that should be available in all workbenches.

Crear una barra herramientas

  1. Press the New... button.
  2. Enter a name in the dialog box that opens.
  3. Press the OK button.
  4. The new toolbar will appear in the panel on the right.

Renombrar una barra herramientas

  1. Select a toolbar in the panel on the right.
  2. Press the Rename... button.
  3. Enter a new name in the dialog box that opens.
  4. Press the OK button.

Eliminar una barra herramientas

  1. Select a toolbar in the panel on the right.
  2. Press the Delete button.

Desactivar una barra herramientas

  1. Uncheck the checkbox in front of the toolbar name in the panel on the right.
  2. A disabled toolbar will be invisible in the FreeCAD interface.

Añadir un comando

  1. At least one custom toolbar is required. See Create a toolbar.
  2. Select the correct toolbar in the panel on the right. If no toolbar is selected, the command will be added to the first toolbar in the list.
  3. Select a command category from the Category dropdown list. Macro commands that have been set up on the Macros tab appear in the Macros category.
  4. Select a command from the Commands panel, or select <Separator> to add a separator (a line between two toolbar buttons).
    • Optionally drag the splitter to the right of the panel to resize it.
  5. Press button.

Elimina un comando

  1. If required, expand the toolbar in the panel on the right.
  2. Select a command.
  3. Press button.

Cambiar la posición de un position comando

  1. If required, expand the toolbar in the panel on the right.
  2. Select a command.
  3. Press the button or the button.
  4. Optionally repeat this until the command is in the correct position.

Notes

  • Toolbars belonging to the current workbench are updated immediately, but after disabling/re-enabling a toolbar a workbench change is required (switch to a different workbench and then switch back).
  • To update global toolbars a workbench change (if commands have been added or removed) or a restart (if the order of a toolbar has changed or a toolbar was renamed) is required.

Inicio

Macros

La pestaña Macros

On this tab macro commands can be set up. Once set up, they can be added to custom toolbars. Macros installed with the Addon Manager are set up automatically, and added to a Global toolbar (see Toolbars), if you confirm the Add button popup during the installation process.

If you want to use a macro downloaded from a different source you will have to install it manually. See How to install macros for more information. Note that FreeCAD uses a dedicated folder for macros and only macros in that folder can be set up. Use the Std DlgMacroExecute command to find this folder on your system.

Añadir un macrocomando

  1. In the Macro dropdown list select a macro.
  2. Enter a Menu text. This will be the name used to identify the macro command and will also appear in the toolbar if there is no icon.
  3. Optionally enter a Tool tip. This text will appear near the location of the mouse when you hover the toolbar icon.
  4. Optionally enter a Status text. This text will appear in the status bar when you hover the toolbar icon.
  5. Optionally enter the wiki page for the macro, if available, in the What's this input box. Enter the page name, not the full URL.
  6. Optionally enter a shortcut in the Accelerator input box. See Keyboard for more information.
  7. To add an icon:
    1. Press the Pixmap ... button.
    2. The Choose Icon dialog box opens.
    3. If required press the Icon folders... button to add an icon folder.
    4. Select an icon from the panel. The Choose Icon dialog box closes automatically.
  8. Press the Add button.
  9. The macro command appears in the panel on the left.
  10. The macro command can now be selected on the Toolbars tab.

Elimina un macrocomando

  1. Select the macro command in the panel on the left.
  2. Press the Remove button.

Cambiar un macrocomando

  1. Double-click the macro command in the panel on the left.
  2. Make the required changes. Note that you cannot remove the icon, you can only replace it.
  3. Press the Replace button.

Inicio

Movimiento Bola Espacial

This tab is blank if no Spaceball is detected. See: 3Dconnexion input devices.

Inicio

Botones Bola Espacial

This tab is blank if no Spaceball is detected. See: 3Dconnexion input devices.

Inicio

Temas

FreeCAD supports complete theming of the interface, via .qss stylesheets. The qss format is very similar to the css format used in web pages, it basically adds methods to reference the different widgets and elements of the Qt interface. You can change the default theme (which simply takes the style defined by your desktop system) by selecting a style sheet in the FreeCAD preferences.

You can also create your own theme if you are not satisfied with the themes that are bundled with FreeCAD, for example by editing an existing style sheet. Your new style must be placed in a specific folder for it to be found by FreeCAD:

  • %APPDATA%/FreeCAD/Gui/Stylesheets (on Windows). The %APPDATA% folder can be retrieved by entering App.getUserAppDataDir() in the Python console.
  • $HOME/.FreeCAD/Gui/Stylesheets (on Linux).
  • $HOME/Library/Application Support/FreeCAD/Gui/Stylesheets (on macOS).

Inicio

Complementos

Los complementos ofrecen otra forma de personalizar la interfaz de uso. A continuación se muestran algunos complementos creados por usuarios de la comunidad de FreeCAD. Pueden descargarse a través del Gestor Complementos (nota: están listados en la pestaña ambientes de trabajo).

In the Workbenches category of the Addon Manager some addons by user triplus can be found:

Inicio

Propiedades de objetos


Introduction

Una propiedad es un pedazo de información, tal como un número o una cadena de texto, que se adjunta a un documento de FreeCAD o a un objeto en un documento. Las propiedades pueden ser vistas y modificadas (sólo si tienes permisos para ello) con el Editor de propiedades.

Las Propiedades juegan un papel muy importante en FreeCAD, ya que el programa fue concebido desde el principio para trabajar con objetos paramétricos, que son objetos definidos únicamente por sus propiedades.

En FreeCAD, los Archivos de guión para crear objetos personalizados por el usuario pueden tener propiedades de los siguientes tipos:


Boolean
Float
FloatList
FloatConstraint
Angle
Distance
Integer
IntegerConstraint
Percent
Enumeration
IntegerList
String
StringList
Link
LinkList
Matrix
Vector
VectorList
Placement
PlacementLink
Color
ColorList
Material
Path
File
FileIncluded
PartShape
FilletContour
Circle

Properties play a very important role in FreeCAD. As objects in FreeCAD are "parametric", this means that their behavior is defined by their properties, and how these properties are used as input for their class methods. See also FeaturePython Custom Properties and PropertyLink: InList and OutList

All property types

Custom scripted objects can use any of the property types defined in the base system:

Name Unit (if any) Remark
Acceleration m/s^2
AmountOfSubstance mol
Angle °
Area m^2
Bool
BoolList
Color
ColorList
CurrentDensity A/m^2 introduced in version 0.21
Density kg/m^3
Direction
DissipationRate m^2/s^3 introduced in version 0.21
Distance m
DynamicViscosity Pa*s introduced in version 0.21
ElectricalCapacitance F introduced in version 0.21
ElectricalConductance S introduced in version 0.21
ElectricalConductivity S/m introduced in version 0.21
ElectricalInductance H introduced in version 0.21
ElectricalResistance Ohm introduced in version 0.21
ElectricCharge C introduced in version 0.21
ElectricCurrent A introduced in version 0.21
ElectricPotential V introduced in version 0.20
Enumeration
ExpressionEngine
File
FileIncluded
Float
FloatConstraint
FloatList
Font
Force N
Frequency Hz
HeatFlux W/m^2 introduced in version 0.21
Integer
IntegerConstraint
IntegerList
IntegerSet
InverseArea 1/m^2 introduced in version 0.21
InverseLength 1/m introduced in version 0.21
InverseVolume 1/m^3 introduced in version 0.21
KinematicViscosity m^2/s introduced in version 0.21
Length m
Link
LinkChild
LinkGlobal
LinkHidden
LinkList
LinkListChild
LinkListGlobal
LinkListHidden
LinkSub
LinkSubChild
LinkSubGlobal
LinkSubHidden
LinkSubList
LinkSubListChild
LinkSubListGlobal
LinkSubListHidden
LuminousIntensity cd introduced in version 0.21
MagneticFieldStrength A/m introduced in version 0.21
MagneticFlux Wb or V*s introduced in version 0.21
MagneticFluxDensity T introduced in version 0.21
Magnetization A/m introduced in version 0.21
Map
Mass kg introduced in version 0.21
Material
MaterialList
Matrix
PartShape a Part property, is accessed as
Part::PropertyPartShape
Path
Percent
PersistentObject
Placement
PlacementLink
PlacementList
Position
Power W introduced in version 0.21
Precision
Pressure Pa
PythonObject
Quantity
QuantityConstraint
Rotation
ShearModulus Pa introduced in version 0.21
SpecificEnergy m^2/s^2 or J/kg introduced in version 0.21
SpecificHeat J/kg/K introduced in version 0.21
Speed m/s
Stiffness m/s^2
Stress Pa introduced in version 0.21
String
StringList
Temperature K introduced in version 0.21
ThermalConductivity W/m/K introduced in version 0.21
ThermalExpansionCoefficient 1/K introduced in version 0.21
ThermalTransferCoefficient W/m^2/K introduced in version 0.21
Time s introduced in version 0.21
UltimateTensileStrength Pa introduced in version 0.21
UUID
VacuumPermittivity s^4*A^2 / (m^3*kg)
Vector
VectorDistance
VectorList
Velocity m/s introduced in version 0.21
Volume l or m^3
VolumeFlowRate l/s or m^3/s introduced in version 0.21
VolumetricThermalExpansionCoefficient 1/K introduced in version 0.21
Work J introduced in version 0.21
XLink
XLinkList
XLinkSub
XLinkSubList
YieldStrength Pa introduced in version 0.21
YoungsModulus Pa introduced in version 0.21

Internally, the property name is prefixed with App::Property:

App::PropertyBool
App::PropertyFloat
App::PropertyFloatList
...

Remember that these are property types. A single object may have many properties of the same type, but with different names.

For example:

obj.addProperty("App::PropertyFloat", "Length")
obj.addProperty("App::PropertyFloat", "Width")
obj.addProperty("App::PropertyFloat", "Height")

This indicates an object with three properties of type "Float", named "Length", "Width", and "Height", respectively.

Scripting

See also: FreeCAD scripting basics

A scripted object is created first, and then properties are assigned.

obj = App.ActiveDocument.addObject("Part::Feature", "CustomObject")

obj.addProperty("App::PropertyFloat", "Velocity", "Parameter", "Body speed")
obj.addProperty("App::PropertyBool", "VelocityEnabled", "Parameter", "Enable body speed")

In general, Data properties are assigned by using the object's addProperty() method. On the other hand, View properties are normally provided automatically by the parent object from which the scripted object is derived.

For example:

  • Deriving from App::FeaturePython provides only 4 View properties: "Display Mode", "On Top When Selected", "Show In Tree", and "Visibility".
  • Deriving from Part::Feature provides 17 View properties: the previous four, plus "Angular Deflection", "Bounding Box", "Deviation", "Draw Style", "Lighting", "Line Color", "Line Width", "Point Color", "Point Size", "Selectable", "Selection Style", "Shape Color", and "Transparency".

Nevertheless, View properties can also be assigned using the view provider object's addProperty() method.

obj.ViewObject.addProperty("App::PropertyBool", "SuperVisibility", "Base", "Make the object glow")

Source code

In the source code, properties are located in various src/App/Property* files.

They are imported and initialized in src/App/Application.cpp.

#include "Property.h"
#include "PropertyContainer.h"
#include "PropertyUnits.h"
#include "PropertyFile.h"
#include "PropertyLinks.h"
#include "PropertyPythonObject.h"
#include "PropertyExpressionEngine.h"


Trabajando con los entornos


FreeCAD, al igual que muchas aplicaciones de diseño moderno como Revit o CATIA, se basa en el concepto de de trabajo. Un banco de trabajo puede considerarse como un conjunto de herramientas especialmente agrupadas para una determinada tarea. En un taller de muebles tradicional, se tendría una mesa de trabajo para el que trabaja con la madera, otra para el que trabaja con las piezas de metal, y quizá una tercera para el que monta todas las piezas juntas.

En FreeCAD se aplica el mismo concepto. Las herramientas se agrupan en bancos de trabajo según las tareas con las que están relacionadas.

Cuando pasas de un ambiente de trabajo a otro, las herramientas disponibles en la interfaz cambian. Barras de herramientas, barras de comandos y posiblemente otras partes de la interfaz cambian al nuevo banco de trabajo, pero el contenido de tu escena no cambia. Por ejemplo, puedes empezar a dibujar formas 2D con el Banco de trabajo Borradores y luego seguir trabajando en ellas con el Banco de trabajo Pieza.

Tenga en cuenta que a veces se hace referencia a un Banco de trabajo como un Módulo. Sin embargo, los Bancos de trabajo y los Módulos son entidades diferentes. Un Módulo es cualquier extensión de FreeCAD, mientras que un Banco de trabajo es un tipo especial de Módulo con una configuración de interfaz gráfica de usuario (barras herramientas y menús).

Bancos de trabajo incorporados

Current

Los siguientes bancos de trabajo se incluyen en cada instalación de FreeCAD:

  • Std Base. No se trata realmente de un banco de trabajo, sino de una categoría de comandos y herramientas "estándar" que pueden utilizarse en todos los bancos de trabajo.
  • The CAM Workbench is used to produce G-Code instructions. This workbench was called "Path Workbench" in version 0.21 and below.
  • El Banco de Trabajo de Ingeniería Inversa pretende proporcionar herramientas específicas para convertir formas/sólidos/mallas en características paramétricas compatibles con FreeCAD. Todavía está en desarrollo.
  • El Banco de Trabajo de Superficies proporciona herramientas para crear y modificar superficies. Es similar al constructor de formas de piezas Cara desde las aristas.

Obsolete

The following workbenches are no longer included after version 0.20:

Ambiente de trabajo externos

Los Ambientes de Trabajo de FreeCAD son fáciles de programar en Python, por lo que hay mucha gente desarrollando Ambientes de Trabajo adicionales fuera del área principal de desarrollo de FreeCAD.

Los Ambiente de trabajo externos página lista todo lo que se conoce en esta comunidad. La mayoría son fácilmente instalables desde dentro de FreeCAD, usando el Gerente de Addon, que se encuentra en el menú Herramientas → Gerente de Addon.


El entorno de Malla


El icono del Ambiente de trabajo Mesh

Introducción

El Ambiente de trabajo Mallas maneja triangle mesh. Mallas son un tipo especial de objeto 3D, compuesto por areas triangulares conectadas por sus vértices y aristas.

Muchas aplicaciones 3D, como Sketchup, Blender, Autodesk Maya y Autodesk 3ds Max utilizan mallas como tipo principal de objeto 3D. Dado que las mallas son objetos muy sencillos, que sólo contienen vértices (puntos), aristas y caras triangulares, son muy fáciles de crear, modificar, subdividir y estirar, y pueden pasarse fácilmente de una aplicación a otra sin pérdida de detalles. Además, como las mallas contienen datos muy simples, las aplicaciones 3D suelen poder gestionar cantidades muy grandes de ellas sin utilizar muchos recursos. Por estas razones, las mallas suelen ser el tipo de objeto 3D preferido para las aplicaciones que se ocupan de las películas, la animación y la creación de imágenes.

Sin embargo, en el campo de la ingeniería las mallas presentan una gran limitación: no pueden definir con precisión las superficies curvas. Por eso FreeCAD se basa en Brep en su lugar. El Mesh Workbench ofrece algunos comandos para manipular directamente las mallas, pero se utiliza más a menudo para importar datos de malla 3D y convertirlos en un sólido para su uso con el Ambiente de trabajo Piezas o Ambiente de trabajo DiseñoPiezas.

Herramientas

Todas las herramientas del ambiente de trabajo Malla se puede acceder a desde el menú Mallas. Casi todas están también disponibles en una de las barras de herramientas de malla.

  • Import Mesh: Importar mallas en varios formatos de archivo
  • Close hole: Fills selected holes in mesh objects.
  • Add triangle: Adds faces along a boundary of an open mesh object.
  • Booleano
    • Unión: Crea un objeto de malla que es la unión de dos objetos de malla.
    • Intersección: Crea un objeto de malla que es la intersección de dos objetos de malla.
    • Diferencia: Crea un objeto de malla que es la diferencia de dos objetos de malla.
  • Merge: Creates a mesh object by combining the meshes of two or more mesh objects.
  • Unwrap mesh: Creates a flat representation of a mesh object.
  • Unwrap face: Creates a flat representation of a face of a shape object.

Preferencias

Hay algunas preferencias de exportación relacionadas con los formatos de malla pero no son utilizadas por los comandos pertenecientes a este ambiente de trabajo. Son utilizadas por el comando Std Exportar.

Mesh Workbench preferences can be found in the following categories of the Preferences Editor:

Notas


El entorno de Pieza


El icono del Ambiente de trabajo Pieza

Introducción

Las sólidas capacidades de modelado de FreeCAD se basan en la OpenCASCADE (OCCT), un sistema CAD de calidad profesional que presenta una creación y manipulación avanzada de geometría 3D. El Ambiente de trabajo pieza es una capa que se encuentra en la parte superior de las bibliotecas de la OCCT, que da al usuario acceso a las primitivas y funciones geométricas de la OCCT. Esencialmente todas las funciones de dibujo 2D y 3D en cada ambiente de trabajo ( Borrador, Croquizador, DiseñoPieza, etc.), se basan en estas funciones expuestas por el ambiente de trabajo DiseñoPieza. Por lo tanto, el Ambiente de trabajo DiseñoPieza se considera el componente central de las capacidades de modelado de FreeCAD.

Una discusión más detallada sobre el ambiente de trabajo Pieza frente al ambiente de trabajo de DiseñoPieza se puede encontrar aquí: Pieza y DiseñoPieza.

Los objetos creados con el ambiente de trabajo de pieza son relativamente sencillos; están pensados para ser utilizados con operaciones booleanas (uniones y cortes) para construir formas más complejas. Este paradigma de modelado se conoce como la geometría sólida constructiva (CSG), y era la metodología tradicional usada en los primeros sistemas de CAD. Por otro lado, el Ambiente de trabajo DiseñoPieza proporciona un flujo de trabajo más moderno para construir formas: utiliza un boceto definido paramétricamente, que se extruye para formar un cuerpo sólido básico, que luego se modifica mediante transformaciones paramétricas (edición características), hasta obtener el objeto final.

Los objetos de las partes son más complejos que los objetos de malla creados con el Ambiente de trabajo Malla, ya que permiten operaciones más avanzadas como operaciones booleanas coherentes, historial de modificaciones y comportamiento paramétrico.

El ambiente de trabajo de pieza es la capa básica que expone las funciones de dibujo de la OCCT a todos los ambientes de trabajo de FreeCAD.

Herramientas

Las herramientas se encuentran en el menú Pieza o en el menú Medida.

Primitivas

Estas son las herramientas para crear primitivas de objetos.

  • Caja: Crea una caja.
  • Cono: Crea un cono.
  • Tube: Creates a tube.
  • Create primitives...: A tool to create one of the following primitives:
    • Plane: Creates a plane.
    • Box: Creates a box. This object can also be created with the Box tool.
    • Cylinder: Creates a cylinder. This object can also be created with the Cylinder tool.
    • Cone: Creates a cone. This object can also be created with the Cone tool.
    • Sphere: Creates a sphere. This object can also be created with the Sphere tool.
    • Ellipsoid: Creates a ellipsoid.
    • Torus: Creates a torus. This object can also be created with the Torus tool.
    • Prism: Creates a prism.
    • Wedge: Creates a wedge.
    • Helix: Creates a helix.
    • Spiral: Creates a spiral.
    • Circle: Creates a circular arc.
    • Ellipse: Creates an elliptical arc.
    • Point: Creates a point.
    • Line: Creates a line.
    • Regular polygon: Creates a regular polygon.

Creación y modificación

Estas son herramientas para crear nuevos objetos y modificar los existentes.

  • Revolve: Creates a solid by revolving an object (not a solid) around an axis.
  • Mirror: Mirrors the selected object across a mirror plane.
  • Fillet: Fillets (rounds) edges of an object.
  • Chamfer: Chamfers edges of an object.
  • Loft: Lofts from one profile to another.
  • Sweep: Sweeps one or more profiles along a path.
  • Sección: Crea una sección por la intersección de un objeto con un plano de sección.
  • Herramientas relleno:
    • 3D Relleno: Construye una forma paralela a cierta distancia de un original.
    • 2D Relleno: Construye un cable paralelo a cierta distancia de un original, o amplía/contrae una cara plana.

Booleano

Estas herramientas realizan operaciones booleanas.

  • Cut: Cuts (subtracts) one object from another.
  • Fuse: Fuses (unions) two or more objects.
  • Común: Extrae la parte común (intersección) de dos objetos.

Medida

Otras herramientas

  • Importar: Importa desde archivos *.IGES, *.STEP o *.BREP.
  • Exportar: Exporta a archivos *.IGES, *.STEP o *.BREP.
  • Invertir formas: Invierte las normales de todas las caras de los objetos seleccionados.
  • Derrotar: Elimina las características de un objeto.

Elementos del menú contextual

  • Apariencia: Determina la apariencia de un objeto completo (color, transparencia, etc.).

Establecer colores: Asigna colores a las caras individuales de los objetos.

Preferencias

  • Preferencias: Preferencias disponibles para las Herramientas de Pieza (el ambiente de trabajo de Pieza también utiliza las Preferencias de PartDesign).
  • Preferencias de importación-exportación: Preferencias disponibles para importar desde y exportar a diferentes formatos de archivo.
  • Ajuste fino: Algunos parámetros extra para afinar el comportamiento de la Parte.

Guión

Ver Guiones Pieza.

Tutoriales


El entorno de Dibujo


The Drawing Workbench is no longer included after version 0.20.
The TechDraw Workbench is its more advanced replacement.
El icono del Ambiente de trabajo Dibujar

Introducción

El módulo de Dibujo le permite poner su trabajo 3D en papel. Es decir, poner vistas de tus modelos en una ventana 2D e insertar esa ventana en un dibujo, por ejemplo una hoja con un borde, un título y tu logo y finalmente imprimir esa hoja.

Herramientas

Estas son las herramientas para la creación, configuración y exportación de hojas de dibujo 2D

  • Insertar una vista: Inserta una vista de los objetos seleccionados en la hoja de dibujo activa
  • Anotación: Añade una anotación a la hoja de dibujo actual
  • Clip: Adds a clip group to the current drawing sheet
  • Open Browser: Opens a preview of the current sheet in the browser
  • Ortho Views: Automatically creates orthographic views of an object on the current drawing sheet
  • Symbol: Adds the contents of a SVG file as a symbol on the current drawing sheet
  • Draft View: Inserts a special Draft view of the selected object in the current drawing sheet
  • Spreadsheet View: Inserts a view of a selected spreadsheet in the current drawing sheet
  • Project Shape: Creates a projection of the selected object (Source) in the 3D view.
  • Nota

La herramienta Borrador boceto es utilizada para objetos boceto. Tiene algunas capacidades adicionales sobre las herramientas de Dibujo, y soporta objetos específicos como Dimensiones de borrador.

Flujo de trabajo

El documento contiene un objeto de forma 3D (pierna) del que queremos producir un dibujo. Por lo tanto, se crea una "Página". Una página es instanciada desde una plantilla, por ejemplo, la plantilla "A3_Landscape". La plantilla es un documento SVG que puede contener un marco de página, un logotipo y otros elementos.

En esta página podemos insertar una o varias vistas. Cada vista tiene una posición en la página, un factor de escala y propiedades adicionales. Cada vez que la página o la vista o el objeto referenciado cambian, la página se regenera y la visualización de la página se actualiza.

Guión

Por el momento, el flujo de trabajo de la interfaz gráfica de usuario es muy limitado, por lo que la API de scripting es más interesante.

See the Drawing API example page for a description of the functions used to create drawing pages and views.

Plantillas

FreeCAD viene con un juego de plantillas básico, pero se pueden obtener más en la página Drawing templates/es.

Ampliación del módulo dibujo

Some notes on the programming side of the drawing module will be added to the Drawing Documentation page. This is to help quickly understand how the drawing module works, enabling programmers to rapidly start programming for it.

Tutoriales

Tutorial de dibujo

Macros

  • Macro Automatic drawing: Allows the user to get the view of his object in a drawing with 4 different position (front,top,iso,right). Needs some modification to be perfectly effective.
  • Macro CartoucheFC: This GUI macro to fill simply all fields of the cartridge of the plan implementation worksheet FreeCAD, the format of the date and the symbol of the projection mode adapt to the EU region or US selected.
  • Macro CartoucheFC 2: This GUI macro to fill simply all fields of the cartridge model 2 of the plan implementation worksheet FreeCAD.
  • Macro CartoucheFC Full: This GUI macro to fill simply all fields of the cartridge Misc templates Full of the plan implementation worksheet FreeCAD, the format of the date and the symbol of the projection mode adapt to the EU region or US selected.
  • Macro Corner shapes wizard/update: Pops up a dialog asking for the dimensions of your corner piece, then creates the object in the document and creates a page view with top, front and lateral views of the piece.

External links


El entorno de Renderizado


The Raytracing Workbench is no longer included after version 0.20.
The external Render Workbench should be used instead.
El icono del Ambiente de trabajo Trazado de rayos

Introducción

El Ambiente de trabajo Trazado de rayos es usado para generar imágenes fotorealistas de tus modelos al renderizarlos con un renderizador externo.

El Ambiente de trabajo trazado de rayos opera con plantillas, que son archivos de escena para un renderizador dado, incluyendo iluminación y posiblemente geometría adicional como son planos de suelo. Estos archivos de escena contienen apartados, en los que FreeCAD insertará la posición de la cámara, y la geometría e información de materiales de cada objeto que insertes en el proyecto. La escena modificada es exportada después al renderizador externo.

De momento, dos renderizadores son soportados povray y luxrender. Para poder renderizar directamente en FeeCAD, al menos uno de esos renderizadores debe estar instalado en tu sistema, y su ubicación debe ser configurada en las preferencias de trazado de rayos de FreeCAD. Si ningún renderizador está instalado, todavía puedes exportar un archivo de escena que puede ser utilizado por alguno de los renderizadores después, o en otra máquina.

The Raytracing workbench is essentially obsolete. New development is happening in the Render Workbench, which is intended as its replacement. This workbench is fully programmed in Python so it is much easier to extend than the current workbench which is programmed in C++. Nevertheless, the information in this page is generally useful for the new workbench, as both modules work basically in the same way.

Flujo de trabajo típico

  1. Crea o abre un proyecto FreeCAD, agrega algunos objetos basados en sólidos (por el momento no se soportan mallas)
  2. Crea un proyecto de trazado de rayos (luxrender o povray)
  3. Selecciona los objetos que desees agregar al proyecto de trazado de rayos y agrçegalos con la herramienta "Insertar Parte"
  4. Exporta el proyecto o renderízalo directamente



Workflow of the Raytracing Workbench; the workbench prepares a project file from a given template, and then calls an external program to produce the actual rendering of the scene. The external renderer can be used independently of FreeCAD.

Herramientas GUI

Project tools

These are the main tools for exporting your 3D work to external renderers.

  • New PovRay project: Insert new PovRay project in the document
  • New LuxRender project: Insert new LuxRender project in the document
  • Insert part: Insert a view of a Part in a raytracing project
  • Reset camera: Matches the camera position of a raytracing project to the current view
  • Export project: Exports a raytracing project to a scene file for rendering in an external renderer
  • Render: Renders a raytracing project with an external renderer

Utilities

These are helper tools to perform specific tasks manually.

Preferences

  • Preferences: Preferences available in for the Raytracing tools.

Tutorials

Creando el archivo povray manualmente

Las herramientas descritas anteriormente te permiten exportar la vista 3D actual y todos sus contenidos a un archivo Povray. Primero, debes de cargar o crear tu información de CAD y posicionar la orientación de vista 3D como desees. Después selecciona "Utilidades->Exportar Vista..." del menu de trazado de rayos.

Se te solicitará la ubicación para guardar el archivo *.pov resultante. Después de ello puedes abrirlo en Povray y renderizar:

Como siempre, en un renderizador puedes hacer imágenes grandes y bonitas:

Archivos de guión

See the Raytracing API example for information on writing scenes programmatically.

Enlaces

Sobre POV-Ray:

LuxRender

Future possible renderers to implement

Exporting to Kerkythea

Although direct export to the Kerkythea XML-File-Format is not supported yet, you can export your Objects as Mesh-Files (.obj) and then import them in Kerkythea.

  • if using Kerkythea for Linux, remember to install the WINE-Package (needed by Kerkythea for Linux to run)
  • you can convert your models with the help of the mesh workbench to meshes and then export these meshes as .obj-files
  • If your mesh-export resulted in errors (flip of normals, holes ...) you may try your luck with netfabb studio basic
Free for personal use, available for Windows, Linux and Mac OSX.
It has standard repair tools which will repair you model in most cases.
  • another good program for mesh analysing/repairing is Meshlab
Open Source, available for Windows, Linux and Mac OSX.
It has standard repair tools which will repair you model in most cases (fill holes, re-orient normals, etc.)
  • you can use "make compound" and then "make single copy" or you can fuse solids to group them before converting to meshes
  • remember to set in Kerkythea an import-factor of 0.001 for obj-modeler, since Kerkythea expects the obj-file to be in m (but standard units-scheme in FreeCAD is mm)
Within WIndows 7 64-bit Kerkythea does not seem to be able to save these settings.
So remember to do that each time you start Kerkythea
  • if importing multiple objects in Kerkythea you can use the "File → Merge" command in Kerkythea

Development

These pages refer to the new workbench, programmed in Python, meant to replace the current Raytracing Workbench.


Robot_Workbench/es
Draft_Workbench/es

El entorno de Imágenes


The Image Workbench is no longer included after version 0.20.
Its functionality has been integrated in Std Base. See Std Import and Std ViewLoadImage.
El icono del Ambiente de trabajo Imagen

Introducción

El Ambiente de trabajo Imagen gestiona diferentes tipos de imágenes bitmap, y te permite abrirlas en FreeCAD.

Herramientas

  • Abrir: abrir una imagen en un nuevo viewport.
  • Importar al plano: importar una imagen a un plano en la vista 3D.
  • Escalar: escalar una imagen importada a un plano.

Características

  • Como un Boceto, una imagen importada puede ser adjuntada a uno de los planos principales XY, XZ, o YZ, y se le da un desplazamiento positivo o negativo.
  • La imagen se importa con relación de 1 píxel a 1 milímetro.
  • La recomendación es que la imagen importada tenga una resolución razonable.

Workflow

Flujo de trabajo

Un uso principal de este ambientes de trabajo es trazar sobre la imagen, con las herramientas Borrador o Croquizador, para generar un cuerpo sólido basado en los contornos de la imagen.

Trazar sobre una imagen funciona mejor si la imagen tiene un pequeño relleno negativo, por ejemplo, -0,1 mm, desde el plano de trabajo. Esto significa que la imagen estará ligeramente por detrás del plano donde dibujas tu geometría 2D, por lo que no dibujarás sobre la propia imagen.

El relleno de la imagen puede establecerse durante la importación, o modificarse posteriormente a través de sus propiedades.


El entorno de Croquizado


El icono del Ambiente de trabajo Borrador

Introducción

El Ambiente de trabajo Borrador se centra principalmente en la creación y modificación de objetos 2D en FreeCAD. Pero no está restringido al plano XY del sistema global de coordenadas. Sus objetos pueden tener cualquier orientación y posición en el espacio 3D, y algunos objetos de Borrador pueden ser planos o no planos.

Los objetos Borrador se pueden utilizarse para elaboración general, similar a lo que se puede hacer con Inkscape o AutoCAD. Pero también pueden ser la base para la creación de objetos 3D en otros bancos de trabajo. Un Borrador Hilo puede definir la trayectoria de un Arquitectura Muro, un Borrador Polígono puede ser extruido con Pieza Extrudir, etc. Muchas de las Borrador herramientas de modificación pueden aplicarse a objetos 2D y 3D creados con otros ambientes de trabajo también. Puedes, por ejemplo, mover un Croquis o crear un Borrador OrthoArreglo a partir de un objeto Pieza.

The Draft Workbench also provides tools to define a working plane, a grid, and a snapping system to precisely control the position of geometry.

Si tu objetivo principal es la producción de dibujos 2D complejos y archivos DXF, y no necesitas el modelado 3D, FreeCAD puede no ser la elección correcta para ti. Es posible que desee considerar un programa de software dedicado para el dibujo técnico en su lugar, como LibreCAD o QCad.

The image shows the grid aligned with the XY plane.
On the left, in white, several planar objects.
On the right a non-planar Draft Wire used as the Path Object of a Draft PathArray.

Drafting

  • Line: creates a straight line.
  • Polyline: creates a polyline (also called wire), a sequence of several connected line segments.
  • Fillet: creates a fillet, a rounded corner, or a chamfer, a straight edge, between two Draft Lines.
  • Arc tools:
  • Arc: creates a circular arc from a center, a radius, a start angle and an aperture angle.
  • Arc by 3 points: creates a circular arc from three points that define its circumference.
  • Circle: creates a circle from a center and a radius.
  • Ellipse: creates an ellipse from two points defining a rectangle in which the ellipse will fit.
  • Rectangle: creates a rectangle from two points.
  • Polygon: creates a regular polygon from a center and a radius.
  • B-spline: creates a B-spline curve from several points.
  • Bézier tools:
  • Point: creates a simple point.
  • Facebinder: creates a surface object from selected faces.
  • ShapeString: creates a compound shape that represents a text string.

Annotation

  • Text: creates a multi-line text at a given point.
  • Dimension: creates a linear dimension, a radial dimension or an angular dimension.
  • Label: creates a multi-line text with a 2-segment leader line and an arrow.
  • Annotation styles...: allows you to define styles that affect the visual properties of annotation-like objects.

Modificación

  • Move: moves or copies selected objects from one point to another.
  • Rotate: rotates or copies selected objects around a center point by a given angle.
  • Scale: scales or copies selected objects around a base point.
  • Mirror: creates mirrored copies from selected objects.
  • Offset: offsets each segment of a selected object over a given distance, or creates an offset copy of the selected object.
  • Trimex: trims or extends a selected object.
  • Stretch: stretches objects by moving selected points.
  • Clone: creates linked copies, clones, of selected objects.
  • Array tools:
  • Array: creates an orthogonal array from a selected object. It can optionally create a Link array.
  • Polar array: creates an array from a selected object by placing copies along a circumference. It can optionally create a Link array.
  • Circular array: creates an array from a selected object by placing copies along concentric circumferences. It can optionally create a Link array.
  • Path array: creates an array from a selected object by placing copies along a path.
  • Point array: creates an array from a selected object by placing copies at the points from a point compound.
  • Edit: puts selected objects in Draft Edit mode. In this mode the properties of objects can be edited graphically.
  • Subelement highlight: temporarily highlights selected objects, or the base objects of selected objects.
  • Upgrade: upgrades selected objects.

Borrador Bandeja

La Borrador Bandeja Barra herramienta aparece cuando se inicia el ambiente de trabajo, y permite seleccionar el plano de trabajo, junto con algunas propiedades visuales como el color de la línea, el color de la forma, el ancho de la línea, el tamaño del texto y el grupo automático.

  • Set style: sets the default style for new objects. Also available in the menu: Draft → Utilities → Set style.
  • Toggle construction mode: switches Draft construction mode on or off. Also available in the menu: Draft → Utilities → Toggle construction mode.

Borrador Widget escala de anotacion

With the Draft annotation scale widget the Draft annotation scale can be specified.

Borrador Widget Atrapar

The Draft snap widget can be used as an alternative for the Draft snap toolbar.

Borrador Barra de herramientas Atrapar

La barra de herramientas Borrador Atrapar permite seleccionar el modo de ajuste actual. Su botón se mantiene pulsado cuando un modo está activo.

  • Snap lock: enables or disables snapping globally.
  • Snap angle: snaps to the special cardinal points on circular edges, at multiples of 30° and 45°.
  • Snap extension: snaps to an imaginary line that extends beyond the endpoints of straight edges.
  • Snap parallel: snaps to an imaginary line parallel to straight edges.
  • Snap special: snaps to special points defined by the object.
  • Snap near: snaps to the nearest point on faces and edges.
  • Snap ortho: snaps to imaginary lines that cross the previous point at multiples of 45°.
  • Snap grid: snaps to the intersections of grid lines.

Borrador Herramientas de utilidad

Herramientas adicionales

Herramientas adicionales disponibles desde el menú Bosquejo → Utilidades, o a través del menú contextual del botón derecho, dependiendo de los objeto seleccionados.

  • Heal: heals problematic Draft objects found in very old files.

Características adicionales

  • Restricción: limitar el puntero a movimientos horizontales o verticales en relación con un punto previo.
  • Ajuste: colocar nuevos puntos en lugares especiales de los objetos existentes o en la cuadrícula.
  • Modo de construcción: Permite crear geometrías separadas del resto, simplemente activándolas y desactivándolas.
  • Plano de trabajo: permite seleccionar una superficie sobre la que construir las formas.

Menú contextual de vista de árbol

The following additional options are available in the Tree view context menu:

Default options

For most Draft objects the following option is available:

If there is an active document the context menu contains an additional sub-menu:

  • Utilities: a subset of the tools available in the main Draft Utilities menu.

Opciones contenedor capas

For a Draft LayerContainer these additional options are available:

Opciones capa

For a Draft Layer these additional options are available:

Text options

For a Draft Text and a Draft Label that contains one or more hyperlinks, to a local or remote file or an URL, this additional option is available:

  • Open hyperlinks: the hyperlinks are opened in the appropriate application (as defined by the OS). There is a warning in the case of multiple hyperlinks. introduced in version 0.22

Opciones Hilos

For a Draft Line and a Draft Wire this additional option is available:

  • Flatten: flattens the wire on the current Draft working plane. This option does not work properly in version 0.19 and below.

Plano trabajo opciones proxy

For a Draft WorkingPlaneProxy these additional options are available:

  • Write objects state: updates the VistaVisibility Map property of the working plane proxy with the current visibility state of objects in the document.

3D vista menú contextual

The following additional options are available in the 3D view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu:

  • Utilities: a subset of the tools available in the main Draft Utilities menu.

Text options

See above.

Herramientas obsoletas

  • Drawing: inserts views of selected objects into a drawing page. Not available in version 0.21 and above.

Preferencias

Formatos de archivo

Son funciones para abrir, importar o exportar otros formatos de archivo. Abrir abrirá un nuevo documento con el contenido del archivo, mientras que importar añadirá el contenido del archivo al documento actual. Exportar guardará los objetos seleccionados en un archivo. Si no se selecciona nada, se exportarán todos los objetos. Tenga en cuenta que el propósito del Módulo Borrador es trabajar con objetos 2D, por lo que esas rutinas de importación se centran sólo en objetos 2D, y aunque los formatos DXF y OCA también soportan definiciones de objetos en el espacio 3D (los objetos no son necesariamente planos), no importarán objetos volumétricos como mallas, superficies 3D, etc., sino líneas, círculos, textos o formas planas. Los formatos de archivo actualmente soportados son: El módulo Borrador proporciona a FreeCAD importadores y exportadores para los siguientes formatos de archivo:

Pruebas unitarias

Véase también: Ambiente de trabajo Prueba.

Para ejecutar las pruebas unitarias del banco de trabajo, ejecute lo siguiente desde el terminal del sistema operativo.

freecad -t TestDraft

Guionización

Las herramientas de Bosquejo pueden utilizarse en macros y desde la Python consola utilizando la Bosquejo API.

El ambiente de trabajo incluye un módulo para crear muestras de todos los objetos en un nuevo documento. introducido en la versión 0.19

Utilícelo para comprobar que todos los objetos se producen correctamente.

import drafttests.draft_test_objects as dto
doc = dto.create_test_file()

Inspeccionar el código de este módulo es útil para entender cómo utilizar la interfaz de programación.

Tutoriales


Archivos de guión y macros

Macros


Introducción

Macros son una forma conveniente de reproducir acciones complejas en FreeCAD. Simplemente grabas las acciones mientras las realizas, luego guardas esas acciones con un nombre, y las reproduces cuando quieras. Como las macros son en realidad una lista de comandos Python, también puedes editarlas, y crear scripts muy complejos.

Mientras que los scripts de Python normalmente tienen la extensión .py, las macros de FreeCAD deben tener la extensión .FCMacro. Una colección de macros escritas por usuarios experimentados se encuentra en la página recipes macros.

Vea el Centro de usuarios avanzados para aprender más sobre el lenguaje de programación Python, y sobre la escritura de macros. En particular, deberías empezar con estas páginas:

¿Cómo funciona?

Activa la salida de la consola en el menú Edición → Preferencias → General → Macro → Mostrar comandos de scripts en la consola de python. Verás que en FreeCAD, cada acción que realizas, como pulsar un botón, da salida a un comando de Python. Esos comandos son los que se pueden grabar en una macro. La herramienta principal para hacer macros es la barra de herramientas de macros: . En ella tienes 4 botones: Grabar, detener la grabación, editar y reproducir la macro actual.

Su uso es muy sencillo: Pulsa el botón de grabar, se te pedirá que des un nombre a tu macro, y luego realiza algunas acciones. Cuando hayas terminado, pulsa el botón de parar la grabación, y tus acciones se guardarán. Ahora puedes acceder al diálogo de la macro con el botón de edición.

Diálogo de macros, que enumera las macros disponibles en el sistema

Allí puedes gestionar tus macros, borrarlas, editarlas, duplicarlas, instalarlas o crear otras nuevas desde cero. Si editas una macro, se abrirá en una ventana del editor donde puedes hacer cambios en su código. Se pueden instalar nuevas macros utilizando el botón Complementos..., que enlaza con el Gestor Complementos.

Ejemplo

Pulsa el botón de grabar, dale un nombre, digamos "cilindro de 10x10, entonces, en el Entorno de Pieza, crea un cilindro con radio = 10 y altura = 10. A continuación, pulsa el botón "Detener la sesión de grabación de la macro". En el letrero de diálogo de edición macros, puedes ver el código Python que se ha registrado, y, si lo deseas, realizar modificaciones en él. Para ejecutar la macro, basta con pulsar el botón de ejecutar en la barra de herramientas mientras la macro se encuentra en el editor. Tu macro siempre se guarda en el disco, por lo que cualquier cambio que hagas, o cualquier macro nueva que crees, siempre estará disponible la próxima vez que inicies FreeCAD.

Personalización

Por supuesto que no es práctico cargar una macro en el editor con el fin de usarla. FreeCAD proporciona formas mucho mejores de iniciar la macro, como la asignación de un atajo de teclado, o poner una entrada en el menú. Una vez que la macro se crea, todo esto se puede hacer a través de menú Herramientas → Personalizar.

De esta manera puedes hacer que tu macro se convierta en una herramienta real, como cualquier herramienta estándar de FreeCAD. Esto, sumado a la potencia de los scripts de Python dentro de FreeCAD, hace posible añadir fácilmente tus propias herramientas a la interfaz. Sigue leyendo la página Guión si quieres saber más sobre Python scripting.

Ver Personalizar barras de herramientas para una descripción más detallada.

Creación de macros sin grabar

También puedes copiar/pegar directamente código python en una macro, sin grabar acciones de la interfaz gráfica de usuario. Basta con crear una nueva macro, editarla, y pegar el código. A continuación, puedes guardar la macro del mismo modo que se guarda un documento de FreeCAD. La próxima vez que se inicie FreeCAD, la macro aparecerá bajo el apartado "Macros instaladas" del menú Macro.

Ver Cómo instalar las macros para obtener una descripción más detallada.

Repositorio de Macros

Visita la página Recetas de macros para recoger algunas macros útiles para añadir a tu instalación de FreeCAD.

Información adicional

Tutoriales

Puede instalar manualmente las extensiones, sin embargo, es mucho más sencillo utilizar el Gestor Complementos.


Standard Menu/es
Introduction to Python/es

Introducción a Python


Introducción

Este es un breve tutorial para los nuevos en Python. Python es un lenguaje de programación de código abierto y multiplataforma lenguaje de programación. Tiene varias características que lo hacen diferente de otros lenguajes de programación, y muy accesible para los nuevos usuarios:

  • Ha sido diseñado para que sea legible por los seres humanos, lo que hace que sea relativamente fácil de aprender y entender.
  • Es interpretado, lo que significa que los programas no necesitan ser compilados antes de ser ejecutados. El código de Python puede ser ejecutado inmediatamente, incluso línea por línea si lo desea.
  • Puede ser incrustado en otros programas como un lenguaje de scripting. FreeCAD tiene un intérprete de Python incrustado. Puedes escribir código Python para manipular partes de FreeCAD. Esto es muy potente, significa que puedes construir tus propias herramientas.
  • Es extensible, puedes conectar fácilmente nuevos módulos en tu instalación de Python y extender su funcionalidad. Por ejemplo, hay módulos que permiten a Python leer y escribir imágenes, comunicarse con Twitter, programar tareas para que las realice tu sistema operativo, etc.

o siguiente es una introducción muy básica, y de ninguna manera un tutorial completo. Pero esperamos que proporcione un buen punto de partida para una mayor exploración de FreeCAD y sus mecanismos. Te recomendamos encarecidamente que introduzcas los fragmentos de código de abajo en un intérprete de Python.

El intérprete

Por lo general, cuando se escriben programas de ordenador, se abre un editor de texto o su entorno de programación especial (que es básicamente un editor de texto con algunas herramientas adicionales), se escribe el programa, luego se compila y se ejecuta. A menudo se cometieron uno o más errores durante la entrada, por lo que su programa no funcionará. Puede que incluso aparezca un mensaje de error indicando lo que ha fallado. Entonces vuelves a tu editor de texto, corriges los errores, ejecutas de nuevo, repitiendo hasta que tu programa funcione como es debido.

En Python todo ese proceso se puede hacer de forma transparente dentro del intérprete de Python. El intérprete es una ventana de Python con un prompt de comandos, donde puedes simplemente escribir código Python. Si has instalado Python en tu ordenador (descárgalo desde el Python página web si estás en Windows o Mac, instálalo desde tu repositorio de paquetes si estás en GNU/Linux), tendrás un intérprete de Python en tu menú de inicio. Pero, como ya se ha mencionado, FreeCAD también tiene un intérprete de Python incorporado: la Consola de Python.

La consola de FreeCAD Python

Si no la ve, haga clic en Ver → Paneles → Consola de Python. La consola de Python puede cambiar de tamaño y también desacoplarse.

El intérprete muestra la versión de Python, y luego un símbolo >> que es el prompt del comando. Escribir código en el intérprete es sencillo: una línea es una instrucción. Cuando pulses Intro, tu línea de código se ejecutará (después de haber sido compilada instantánea e invisiblemente). Por ejemplo, trata de escribir esto:

print("hello")

print() es un comando de Python que, obviamente, imprime algo en la pantalla. Al pulsar Enter, se ejecuta la operación y se imprime el mensaje "hola". Si se produce un error, por ejemplo, escribamos:

print(hello)

Python te lo dirá inmediatamente. En este caso Python no sabe qué es hello. Los caracteres " " especifican que el contenido es una cadena, jerga de programación para un trozo de texto. Sin ellos, el comando print() no reconoce hello. Pulsando la flecha hacia arriba puedes volver a la última línea de código y corregirla.

El intérprete de Python también tiene un sistema de ayuda incorporado. Supongamos que no entendemos qué ha ido mal con print(hello) y queremos información específica sobre el comando:

help("print")

Obtendrá una larga y completa descripción de todo lo que puede hacer el comando print().

Ahora que entiendes el intérprete de Python, podemos continuar con las cosas más serias.

Inicio

Variables

Muy a menudo en la programación se necesita almacenar un valor bajo un nombre. Ahí es donde entran las variables. Por ejemplo, escribe esto:

a = "hello"
print(a)

Probablemente entiendas lo que ha pasado aquí, hemos guardado la cadena "hello" bajo el nombre a. Ahora que a es conocido podemos usarlo en cualquier lugar, por ejemplo en el comando print(). Podemos usar cualquier nombre que queramos, sólo tenemos que seguir algunas reglas simples, como no usar espacios o puntuación y no usar palabras clave de Python. Por ejemplo, podemos escribir:

hello = "my own version of hello"
print(hello)

Ahora hello ya no es un indefinido. Las variables pueden ser modificadas en cualquier momento, por eso se llaman variables, su contenido puede variar. Por ejemplo:

myVariable = "hello"
print(myVariable)
myVariable = "good bye"
print(myVariable)

Cambiamos el valor de myVariable. También podemos copiar variables:

var1 = "hello"
var2 = var1
print(var2)

Es aconsejable dar nombres significativos a sus variables. Después de un tiempo no recordarás qué representa tu variable llamada a. Pero si la nombras, por ejemplo, myWelcomeMessage recordarás fácilmente su propósito. Además, tu código está un paso más cerca de ser auto-documentado.

El caso es muy importante, myVariable no es lo mismo que myvariable. Si se introdujera print(myvariable) se obtendría un error como no definido.

Inicio

Números

Por supuesto, los programas de Python pueden tratar con todo tipo de datos, no sólo con cadenas de texto. Una cosa es importante, Python debe saber con qué tipo de datos está tratando. Vimos en nuestro ejemplo de imprimir hola, que el comando print() reconoció nuestra cadena "hello". Al usar " " , especificamos que lo que sigue es una cadena de texto.

Siempre podemos comprobar el tipo de datos de una variable con el comando type():

myVar = "hello"
type(myVar)

Nos dirá que el contenido de myVar es un 'str', que es la abreviatura de cadena. También tenemos otros tipos de datos básicos como números enteros y flotantes:

firstNumber = 10
secondNumber = 20
print(firstNumber + secondNumber)
type(firstNumber)

Python sabe que 10 y 20 son números enteros, por lo que se almacenan como 'int', y Python puede hacer con ellos todo lo que puede hacer con los enteros. Mira los resultados de esto:

firstNumber = "10"
secondNumber = "20"
print(firstNumber + secondNumber)

Aquí forzamos a Python a considerar que nuestras dos variables no son números sino trozos de texto. Python puede sumar dos trozos de texto, aunque en ese caso, por supuesto, no realizará ninguna aritmética. Pero estábamos hablando de números enteros. También hay números de coma flotantes. La diferencia es que los números de coma flotantes pueden tener una parte decimal y los números enteros no:

var1 = 13
var2 = 15.65
print("var1 is of type ", type(var1))
print("var2 is of type ", type(var2))

Número entero y Número de coma flotante pueden mezclarse sin problemas:

total = var1 + var2
print(total)
print(type(total))

Como var2 es un Número de coma flotante, Python decide automáticamente que el resultado debe ser también un Número de coma flotante. Pero hay casos en los que Python no sabe qué tipo usar. Por ejemplo:

varA = "hello 123"
varB = 456
print(varA + varB)

Esto resulta en un error, varA es una cadena y varB es un Número entero, y Python no sabe qué hacer. Sin embargo, podemos forzar a Python a convertir entre tipos:

varA = "hello"
varB = 123
print(varA + str(varB))

Ahora que ambas variables son cadenas la operación funciona. Observe que hemos "encadenado" varB en el momento de la impresión, pero no hemos cambiado varB en sí. Si quisiéramos convertir varB permanentemente en una cadena, tendríamos que hacer lo siguiente

varB = str(varB)

También podemos usar int() y float() para convertir a entero y a flotante si queremos:

varA = "123"
print(int(varA))
print(float(varA))

Habrás notado que hemos utilizado el comando print() de varias maneras. Hemos impreso variables, sumas, varias cosas separadas por comas, e incluso el resultado de otro comando de Python. Quizás también hayas visto que estos dos comandos:

type(varA)
print(type(varA))

tienen el mismo resultado. Esto es porque estamos en el intérprete, y todo se imprime automáticamente. Cuando escribamos programas más complejos que se ejecuten fuera del intérprete, no se imprimirán automáticamente, por lo que tendremos que utilizar el comando print(). Teniendo esto en cuenta, dejemos de usarlo aquí. A partir de ahora simplemente escribiremos:

myVar = "hello friends"
myVar

Inicio

Listas

Otro tipo de datos útil es una lista. Una lista es una colección de otros datos. Para definir una lista utilizamos [ ]:

myList = [1, 2, 3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

Como puede ver, una lista puede contener cualquier tipo de datos. Puedes hacer muchas cosas con una lista. Por ejemplo, contar sus elementos:

len(myOtherList)

O recuperar un elemento:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

Mientras que el comando len() devuelve el número total de elementos de una lista, el primer elemento de una lista siempre está en la posición 0, por lo que en nuestra myOtherList "Bob" estará en la posición 2. Podemos hacer mucho más con las listas, como ordenar los elementos y eliminar o añadir elementos.

Curiosamente, una cadena de texto es muy similar a una lista de caracteres en Python. Intenta hacer esto:

myvar = "hello"
len(myvar)
myvar[2]

Normalmente, lo que se puede hacer con las listas también se puede hacer con las cadenas. De hecho, tanto las listas como las cadenas son secuencias.

Además de las cadenas, los enteros, los flotadores y las listas, hay más tipos de datos incorporados, como los diccionarios, e incluso puedes crear tus propios tipos de datos con clases.

Inicio

Indentación

Un uso importante de las listas es la posibilidad de "navegar" por ellas y hacer algo con cada elemento. Por ejemplo, mira esto:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
    print(dalton + " Dalton")

Hemos iterado (jerga de programación) a través de nuestra lista con el comando for in y hemos hecho algo con cada uno de los elementos. Observe la sintaxis especial: el comando for termina con : indicando que lo siguiente será un bloque de uno o más comandos. En el intérprete, inmediatamente después de introducir la línea de comando que termina con :, el prompt de comando cambiará a ... lo que significa que Python sabe que hay más por venir.

¿Cómo sabrá Python cuántas de las siguientes líneas deberán ejecutarse dentro de la operación for in? Para ello, Python se basa en la indentación. Las siguientes líneas deben comenzar con un espacio en blanco, o varios espacios en blanco, o un tabulador, o varios tabuladores. Y mientras la indentación sea la misma, las líneas se considerarán parte del bloque for in. Si empiezas una línea con 2 espacios y la siguiente con 4, habrá un error. Cuando haya terminado, simplemente escriba otra línea sin sangría, o pulse Enter para volver del bloque for in.

La indentación también ayuda a la legibilidad del programa. Si usas sangrías grandes (por ejemplo, usa tabuladores en lugar de espacios) cuando escribas un programa grande, tendrás una visión clara de qué se ejecuta dentro de qué. Veremos que otros comandos también utilizan bloques de código con indentación.

El comando for in puede utilizarse para muchas cosas que deben hacerse más de una vez. Por ejemplo, puede combinarse con el comando range():

serie = range(1, 11)
total = 0
print("sum")
for number in serie:
    print(number)
    total = total + number
print("----")
print(total)

Si ha ejecutado los ejemplos de código en un intérprete copiando y pegando, encontrará que el bloque de texto anterior arrojará un error. En su lugar, copie hasta el final del bloque sangrado, es decir, el final de la línea total = total + number y luego pegue en el intérprete. En el intérprete pulsa Intro hasta que desaparezca el aviso de los tres puntos y se ejecute el código. A continuación, copia las dos últimas líneas seguidas de otro Intro. Debería aparecer la respuesta final.

Si escribe en el intérprete help(range) verá:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Aquí los corchetes denotan un parámetro opcional. Sin embargo, se espera que todos sean enteros. A continuación forzaremos que el parámetro del paso sea un entero usando int():

number = 1000
for i in range(0, 180 * number, int(0.5 * number)):
    print(float(i) / number)

Otro ejemplo range():

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
    print(alldaltons[n], " is Dalton number ", n)

El comando range() también tiene esa extraña particularidad de que comienza con 0 (si no especificas el número inicial) y que su último número será uno menos que el número final que especifiques. Eso sí, para que funcione bien con otros comandos de Python. Por ejemplo:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
    print(alldaltons[n])

Otro uso interesante de los bloques indentados es con el comando if. Este comando ejecuta un bloque de código sólo si se cumple una determinada condición, por ejemplo:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
    print("We found that Dalton!!!")

Por supuesto, esto siempre imprimirá la frase, pero pruebe a sustituir la segunda línea por

if "Lucky" in alldaltons:

Entonces no se imprime nada. También podemos especificar una sentencia else:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
    print("We found that Dalton!!!")
else:
    print("Such Dalton doesn't exist!")

Inicio

Funciones

Hay muy pocos standard Python commands y ya conocemos varios de ellos. Pero puedes crear tus propios comandos. De hecho, la mayoría de los módulos adicionales que puedes conectar a tu instalación de Python hacen precisamente eso, añadir comandos que puedes utilizar. Un comando personalizado en Python se llama función y se hace así:

def printsqm(myValue):
    print(str(myValue) + " square meters")

printsqm(45)

El comando def() define una nueva función, le das un nombre, y dentro del paréntesis defines los argumentos que la función utilizará. Los argumentos son los datos que se pasarán a la función. Por ejemplo, mira el comando len(). Si sólo escribes len(), Python te dirá que necesita un argumento. Lo cual es obvio: quieres saber la longitud de algo. Si escribes len(myList) entonces myList es el argumento que pasas a la función len(). Y la función len() está definida de tal manera que sabe qué hacer con este argumento. Hemos hecho lo mismo con nuestra función printsqm.

El nombre myValue puede ser cualquier cosa, y sólo se utilizará dentro de la función. Es sólo un nombre que le das al argumento para poder hacer algo con él. Al definir los argumentos también le dices a la función cuántos debe esperar. Por ejemplo, si haces esto:

printsqm(45, 34)

habrá un error. Nuestra función estaba programada para recibir un solo argumento, pero recibió dos, 45 y 34. Intentemos otro ejemplo:

def sum(val1, val2):
    total = val1 + val2
    return total

myTotal = sum(45, 34)

Aquí hicimos una función que recibe dos argumentos, los suma y devuelve ese valor. Devolver algo es muy útil, porque podemos hacer algo con el resultado, como almacenarlo en la variable myTotal.

Inicio

Módulos

Ahora que tienes una buena idea de cómo funciona Python, necesitarás saber una cosa más: cómo trabajar con archivos y módulos

Hasta ahora, hemos escrito las instrucciones de Python línea por línea en el intérprete. Obviamente, este método no es adecuado para programas más grandes. Normalmente el código de los programas Python se almacena en archivos con la extensión .py. Los cuales son simplemente archivos de texto plano y cualquier editor de texto (Linux gedit, emacs, vi o incluso el Bloc de notas de Windows) puede ser utilizado para crear y editarlos.

Hay varias formas de ejecutar un programa Python. En Windows, basta con hacer clic con el botón derecho en el archivo, abrirlo con Python y ejecutarlo. Pero también puedes ejecutarlo desde el propio intérprete de Python. Para ello, el intérprete debe saber dónde está tu programa. En FreeCAD la forma más fácil es colocar tu programa en una carpeta que el intérprete de Python de FreeCAD conozca por defecto, como la carpeta del usuario de FreeCAD Mod:

  • En Linux suele ser /home/<username>/.FreeCAD/Mod/.
  • En Windows es %APPDATA%\FreeCAD\Mod, que suele ser C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod.
  • En Mac OSX suele ser /Users/<username>/Library/Preferences/FreeCAD/Mod/.

Vamos a añadir una subcarpeta allí llamada scripts y luego escribir un archivo como este:

def sum(a,b):
    return a + b

print("myTest.py succesfully loaded")

Guarda el archivo como myTest.py en la carpeta scripts, y en la ventana del intérprete escribe:

import myTest

sin la extensión .py. Esto ejecutará el contenido del archivo, línea por línea, tal como si lo hubiéramos escrito en el intérprete. Se creará la función suma y se imprimirá el mensaje. Los archivos que contienen funciones, como el nuestro, se llaman módulos.

Cuando escribimos una función sum() en el intérprete, la ejecutamos así:

sum(14, 45)

Pero cuando importamos un módulo que contiene una función sum() la sintaxis es un poco diferente:

myTest.sum(14, 45)

Es decir, el módulo se importa como un "contenedor", y todas sus funciones están dentro de ese contenedor. Esto es muy útil, porque podemos importar muchos módulos, y mantener todo bien organizado. Básicamente, cuando veas something.somethingElse, con un punto en medio, significa que somethingElse está dentro de something.

También podemos importar nuestra función sum() directamente al espacio principal del intérprete:

from myTest import *
sum(12, 54)

Casi todos los módulos hacen eso: definen funciones, nuevos tipos de datos y clases que puedes utilizar en el intérprete o en tus propios módulos de Python, ¡porque nada te impide importar otros módulos dentro de tu módulo!

¿Cómo sabemos qué módulos tenemos, qué funciones hay dentro y cómo usarlas (es decir, qué tipo de argumentos necesitan)? Ya hemos visto que Python tiene una función help(). Haciendo:

help("modules")

nos dará una lista de todos los módulos disponibles. Podemos importar cualquiera de ellos y navegar por su contenido con el comando dir():

import math
dir(math)

Veremos todas las funciones contenidas en el módulo math, así como cosas extrañas llamadas __doc__, __file__, __name__. Cada función en un módulo bien hecho tiene un __doc__ que explica cómo usarlo. Por ejemplo, vemos que hay una función sin() dentro del módulo de matemáticas. ¿Quieres saber cómo usarla?

print(math.sin.__doc__)

Puede que no sea evidente, pero a cada lado de doc hay dos caracteres de subrayado.

Y finalmente un último consejo: Cuando trabajes en código nuevo o existente, es mejor no usar la extensión de archivo de macro de FreeCAD, .FCMacro, sino usar la extensión estándar .py. Esto es porque Python no reconoce la extensión .FCMacro. Si usas .py tu código puede cargarse fácilmente con import, como ya hemos visto, y también recargarse con importlib.reload():

import importlib
importlib.reload(myTest)

Sin embargo, hay una alternativa:

exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Inicio

Empezando con FreeCAD

Esperemos que ahora tengas una buena idea de cómo funciona Python, y puedas empezar a explorar lo que FreeCAD tiene que ofrecer. Las funciones de Python de FreeCAD están todas bien organizadas en diferentes módulos. Algunas de ellas ya están cargadas (importadas) cuando inicias FreeCAD. Sólo tienes que probar:

dir()

Inicio

Notas

  • FreeCAD fue diseñado originalmente para trabajar con Python 2. Desde que Python 2 llegó al final de su vida en 2020, el desarrollo futuro de FreeCAD se hará exclusivamente con Python 3, y no se soportará la compatibilidad hacia atrás.
  • Se puede encontrar mucha más información sobre Python en el tutorial oficial de Python y en la referencia oficial de Python.

Inicio

Macros/es
Python scripting tutorial/es


Guionización Python en FreeCAD

FreeCAD está construido desde cero para ser totalmente controlado por guiónes de Python. Casi todas las partes de FreeCAD, como la interfaz, el contenido de la escena, e incluso la representación de este contenido en las vistas 3D, son accesibles desde el intérprete de Python incorporado o desde tus propios guiónes. Como resultado, FreeCAD es probablemente una de las aplicaciones de ingeniería más profundamente personalizables disponibles hoy en día.

Si no estás familiarizado con Python, te recomendamos que busques tutoriales en Internet y eches un vistazo rápido a su estructura. Python es un lenguaje muy fácil de aprender, especialmente porque puede ser ejecutado dentro de un intérprete, donde comandos simples, hasta programas completos, pueden ser ejecutados sobre la marcha sin necesidad de compilar nada. FreeCAD tiene un intérprete de Python incorporado. Si no ves la ventana etiquetada como Consola de Python como se muestra a continuación, puedes activarla en el Ver → Paneles → Consola Python.

El intérprete

Desde el intérprete, puedes acceder a todos los módulos de Python instalados en el sistema, así como a los módulos incorporados de FreeCAD, y a todos los módulos adicionales de FreeCAD que hayas instalado posteriormente. La captura de pantalla de abajo muestra el intérprete de Python:

The FreeCAD Python interpreter

Desde el intérprete, puedes ejecutar código Python y navegar a través de las clases y funciones disponibles. FreeCAD proporciona un navegador de clases muy práctico para explorar el mundo de FreeCAD: Cuando escribes el nombre de una clase conocida seguido de un punto (lo que significa que quieres añadir algo de esa clase), se abre una ventana del navegador de clases, donde puedes navegar entre las subclases y métodos disponibles. Cuando seleccionas algo, se muestra un texto de ayuda asociado (si existe):

The FreeCAD class browser

Por lo tanto, comience aquí escribiendo App. o Gui. y vea lo que sucede. Otra forma más genérica de Python para explorar el contenido de los módulos y clases es utilizar el comando print(dir()). Por ejemplo, escribiendo print(dir()) listará todos los módulos cargados actualmente en FreeCAD. print(dir(App)) te mostrará todo lo que hay dentro del módulo App, etc.

Otra característica útil del intérprete es la posibilidad de retroceder en el historial de comandos y recuperar una línea de código que ya hayas escrito anteriormente. Para navegar por el historial de comandos, basta con utilizar Flecha arriba o Flecha abajo.

Al hacer clic derecho en la ventana del intérprete también tienes otras opciones, tales como copiar todo el historial (útil para experimentar con algo, y luego hacer un archivo de guión con todo ello), o insertar el nombre de un archivo con su ruta completa.

Inicio

Ayuda de Python

En el menú de FreeCAD Ayuda, encontrarás una entrada etiquetada como Documentación automática de los módulos de Python, que abrirá una ventana del navegador que contiene una documentación completa, generada en tiempo real, de todos los módulos de Python disponibles para el intérprete de FreeCAD, incluyendo los módulos incorporados de Python y FreeCAD, los módulos instalados en el sistema y los módulos adicionales de FreeCAD. La documentación disponible allí depende del esfuerzo que cada desarrollador de módulos ponga en documentar su código, pero los módulos de Python tienen la reputación de estar bastante bien documentados. Tu ventana de FreeCAD debe permanecer abierta para que este sistema de documentación funcione. La entrada Documentación Guionización en Python te dará un enlace rápido a la sección wiki Centro usuarios avanzados.

Inicio

Módulos incorporados

Dado que FreeCAD está diseñado para que también pueda ejecutarse sin una interfaz gráfica de usuario (GUI), casi toda su funcionalidad está separada en dos grupos: La funcionalidad del núcleo, llamada App, y la funcionalidad de la GUI, llamada Gui. A estos dos módulos también se puede acceder desde scripts fuera del intérprete, con los nombres FreeCAD y FreeCADGui respectivamente.

  • En el módulo App encontrarás todo lo relacionado con la propia aplicación, como los métodos para abrir o cerrar archivos, y con los documentos, como establecer el documento activo o listar su contenido.
  • En el módulo Gui, encontrarás herramientas para acceder y gestionar los elementos de la Gui, como los ambientes de trabajo y sus barras de herramientas, y, lo que es más interesante, la representación gráfica de todo el contenido de FreeCAD.

Listar el contenido de estos módulos no es muy útil porque crecen bastante rápido a medida que FreeCAD se desarrolla. Pero las dos herramientas de navegación proporcionadas (el navegador de clases y la ayuda de Python) deberían darte una documentación completa y actualizada en cualquier momento.

Inicio

Los objetos App y Gui

Como ya se ha mencionado, en FreeCAD todo está separado en núcleo y representación. Esto incluye los objetos 3D. Puedes acceder a las propiedades que definen los objetos (llamados características en FreeCAD) a través del módulo App, y cambiar la forma en que se representan en la pantalla a través del módulo Gui. Por ejemplo, un cubo tiene propiedades que lo definen (como anchura, longitud, altura) que se almacenan en un objeto App, y propiedades de representación (como color de las caras, modo de dibujo) que se almacenan en un objeto Gui correspondiente.

Esta forma de hacer las cosas permite una amplia gama de usos, como los algoritmos que sólo funcionan en la parte definitoria de características, sin la necesidad de ocuparse de ningun aspecto visual, o incluso redirigir el contenido del documento con la aplicación no-gráfica, como listas, hojas de cálculo o análisis de elementos.

Para cada objeto App en su documento, existe un objeto Gui correspondiente. De hecho, el propio documento tiene tanto un objeto App como un objeto Gui. Esto, por supuesto, sólo se aplica cuando se ejecuta FreeCAD con su interfaz completa. En la versión de línea de comandos no existe la interfaz gráfica, por lo que sólo están disponibles los objetos App. Ten en cuenta que la parte Gui de los objetos se vuelve a generar cada vez que un objeto App se marca como 'a recalcular' (por ejemplo cuando uno de sus parámetros cambia), por lo que cualquier cambio realizado directamente en el objeto Gui puede perderse.

Para acceder a la parte App de algo, se teclea:

myObject = App.ActiveDocument.getObject("ObjectName")

donde "ObjectName" es el nombre de su objeto. También puede teclea:

myObject = App.ActiveDocument.ObjectName

Para acceder a la parte Gui del mismo objeto, se teclea:

myViewObject = Gui.ActiveDocument.getObject("ObjectName")

donde "ObjectName" es el nombre de su objeto. También puede teclea:

myViewObject = App.ActiveDocument.ObjectName.ViewObject

Si está en modo de línea de comandos y no tiene GUI, la última línea devolverá None.

Inicio

Los objetos Documento

En FreeCAD todo tu trabajo reside dentro de los documentos. Un documento contiene tu geometría y puede ser guardado en un archivo. Se pueden abrir varios documentos al mismo tiempo. El documento, al igual que la geometría que contiene, tiene objetos App y Gui. El objeto App contiene las definiciones reales de la geometría, mientras que el objeto Gui contiene las diferentes vistas del documento. Puedes abrir varias ventanas, cada una de ellas viendo tu trabajo con un factor de zoom diferente o desde una dirección diferente. Todas estas vistas forman parte del objeto Gui de tu documento.

Para acceder a la parte App del documento actualmente abierto (activo), se escribe:

myDocument = App.ActiveDocument

Para crear un nuevo documento, teclea:

myDocument = App.newDocument("Document Name")

Para acceder a la parte Gui del documento abierto actualmente (active), teclea:

myGuiDocument = Gui.ActiveDocument

Para acceder a la vista actual, teclea:

myView = Gui.ActiveDocument.ActiveView

Inicio

Utilizando módulos adicionales

Los módulos FreeCAD y FreeCADGui sólo se encargan de crear y gestionar objetos en el documento de FreeCAD. En realidad no hacen nada más como crear o modificar la geometría. Esto se debe a que la geometría puede ser de varios tipos, y por lo tanto requiere módulos adicionales, cada uno responsable de la gestión de un determinado tipo de geometría. Por ejemplo, el Part Workbench, usando el kernel de OpenCascade, es capaz de crear y manipular geometría del tipo BRep. Mientras que el Mesh Workbench es capaz de construir y modificar objetos de malla. De esta manera FreeCAD es capaz de manejar una amplia variedad de tipos de objetos, que pueden coexistir en el mismo documento, y nuevos tipos pueden ser fácilmente añadidos en el futuro.

Inicio

Creación objetos

Cada módulo tiene su propia manera de tratar la geometría, pero una cosa que normalmente todos pueden hacer es crear objetos en el documento. Pero el documento de FreeCAD también es consciente de los tipos de objetos disponibles proporcionados por los módulos:

FreeCAD.ActiveDocument.supportedTypes()

listará todos los objetos posibles que puedes crear. Por ejemplo, vamos a crear una malla (manejada por el módulo Mesh) y una pieza (manejada por el módulo Part):

myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "myMeshName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature", "myPartName")

El primer argumento es el tipo de objeto, el segundo el nombre del objeto. Nuestros dos objetos parecen casi iguales: no contienen ninguna geometría todavía, y la mayoría de sus propiedades son las mismas cuando los inspeccionas con dir(myMesh) y dir(myPart). Excepto por una cosa, myMesh tiene una propiedad Mesh y myPart tiene una propiedad Shape. Ahí es donde se almacenan los datos de la Malla y de la Pieza. Por ejemplo, vamos a crear un cubo Part y almacenarlo en nuestro objeto myPart:

import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube

Podrías intentar almacenar el cubo dentro de la propiedad Mesh del objeto myMesh, pero devolverá un error. Esto se debe a que cada propiedad está hecha para almacenar sólo un tipo determinado. En una propiedad Mesh, sólo puedes guardar cosas creadas con el módulo Mesh. Tenga en cuenta que la mayoría de los módulos también tienen un acceso directo para añadir su geometría al documento:

import Part
cube = Part.makeBox(2, 2, 2)
Part.show(cube)

Inicio

Modificando objetos

Modificación de un objeto se hace de la misma manera:

import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube

Ahora vamos a cambiar la forma por una mayor:

biggercube = Part.makeBox(5, 5, 5)
myPart.Shape = biggercube

Inicio

Consultar objetos

Siempre se puede mirar el tipo de un objeto así:

myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
print(myObj.TypeId)

o comprobar si un objeto deriva de uno de los básicos (Característica Pieza, Característica Malla, etc):

print(myObj.isDerivedFrom("Part::Feature"))

¡Ahora puedes empezar a jugar de verdad con FreeCAD! Para una lista completa de los módulos disponibles y sus herramientas, visite la sección Categoría:API.

Inicio

Python scripting tutorial/es
Mesh Scripting/es


Introducción

Para obtener acceso al módulo Malla hay que importarlo primero:

import Mesh

Creación

Para crear un objeto de malla vacío basta con utilizar el constructor estándar:

mesh = Mesh.Mesh()

También puede crear un objeto a partir de un archivo:

mesh = Mesh.Mesh("D:/temp/Something.stl")

O crearla a partir de un conjunto de triángulos descritos por sus puntos de esquina:

triangles = [
# triangle 1
[-0.5000, -0.5000, 0.0000], [0.5000, 0.5000, 0.0000], [-0.5000, 0.5000, 0.0000],
#triangle 2
[-0.5000, -0.5000, 0.0000], [0.5000, -0.5000, 0.0000], [0.5000, 0.5000, 0.0000],
]
meshObject = Mesh.Mesh(triangles)
Mesh.show(meshObject)

El Núcleo-Malla se encarga de crear una estructura de datos topológicamente correcta ordenando los puntos y aristas coincidentes.

Inicio

Modelización

Para crear geometrías regulares se puede utilizar uno de los métodos create*(). Un toroide, por ejemplo, se puede crear de la siguiente manera:

m = Mesh.createTorus(8.0, 2.0, 50)
Mesh.show(m)

Los dos primeros parámetros definen los radios del toroide y el tercer parámetro es un factor de submuestreo para saber cuántos triángulos se crean. Cuanto mayor sea este valor, más suave será la malla.

El módulo Malla también proporciona tres métodos booleanos: union(), intersection() y difference():

m1, m2              # are the input mesh objects
m3 = Mesh.Mesh(m1)  # create a copy of m1
m3.unite(m2)        # union of m1 and m2, the result is stored in m3
m4 = Mesh.Mesh(m1)
m4.intersect(m2)    # intersection of m1 and m2
m5 = Mesh.Mesh(m1)
m5.difference(m2)   # the difference of m1 and m2
m6 = Mesh.Mesh(m2)
m6.difference(m1)   # the difference of m2 and m1, usually the result is different to m5

Este es un ejemplo que crea una tubería utilizando el método difference():

import FreeCAD, Mesh
cylA = Mesh.createCylinder(2.0, 10.0, True, 1.0, 36)
cylB = Mesh.createCylinder(1.0, 12.0, True, 1.0, 36)
cylB.Placement.Base = (FreeCAD.Vector(-1, 0, 0)) # move cylB to avoid co-planar faces
pipe = cylA
pipe = pipe.difference(cylB)
pipe.flipNormals() # somehow required
doc = FreeCAD.ActiveDocument
obj = d.addObject("Mesh::Feature", "Pipe")
obj.Mesh = pipe
doc.recompute()

Inicio

Notas

Una fuente extensa, aunque difícil de usar, de scripts relacionados con la malla son los scripts de pruebas unitarias del módulo Mesh. En estas pruebas unitarias se llaman literalmente todos los métodos y se ajustan todas las propiedades/atributos. Así que si eres lo suficientemente audaz, echa un vistazo al módulo Unit Test.

Ver también: Interfaz de programación de aplicaciones Malla.

Inicio


Introducción

Aquí te explicaremos cómo controlar el módulo Pieza directamente desde el intérprete de Python de FreeCAD, o desde cualquier guión externo. Asegúrate de navegar por la sección Guionización y las páginas Básicos de Guionización FreeCAD si necesitas más información sobre cómo funciona el guionización de Python en FreeCAD. Si eres nuevo en Python, es una buena idea leer primero la Introducción a Python.

Ver también

Diagrama de clase

Este es un resumen Lenguaje Unificado de Modelado (UML) de las clases más importantes del módulo Pieza:

Clases de Python del módulo Pieza
Clases de Python del módulo Pieza

Inicio

Geometría

Los objetos geométricos son los bloques de construcción de todos los objetos topológicos:

  • Geom Clase base de los objetos geométricos.
  • Línea Una línea recta en 3D, definida por un punto inicial y un punto final.
  • Círculo Círculo o segmento de círculo definido por un punto central y un punto inicial y final.
  • Etc.

Inicio

Topología

Los siguientes tipos de datos topológicos están disponibles:

  • Compuesto Un grupo de cualquier tipo de objetos topológicos.
  • Sólido compuesto Un sólido compuesto es un conjunto de sólidos conectados por sus caras. Amplía las nociones de ALAMBRE y CASCO a los sólidos.
  • Sólido Una parte del espacio limitada por cáscaras. Es tridimensional.
  • Cáscara Conjunto de caras conectadas por sus aristas. Una cáscara puede ser abierta o cerrada.
  • En 2D es parte de un plano; en 3D es parte de una superficie. Su geometría está limitada (recortada) por los contornos. Es bidimensional.
  • Alambre Conjunto de aristas conectadas por sus vértices. Puede ser un contorno abierto o cerrado dependiendo de si las aristas están unidas o no.
  • Arista Elemento topológico que corresponde a una curva restringida. Una arista está generalmente limitada por los vértices. Tiene una dimensión.
  • Vértice Elemento topológico que corresponde a un punto. Tiene una dimensión cero.
  • Forma Término genérico que abarca todo lo anterior.

Inicio

Ejemplo: Crear una topología simple

Hilo

Ahora crearemos una topología construyéndola a partir de una geometría más sencilla. Como caso de estudio utilizaremos una pieza como la que se ve en la imagen que consta de cuatro vértices, dos arcos y dos líneas.

Inicio

Crear geometría

Primero creamos las distintas partes geométricas de este cable. Asegurándonos de que las partes que tienen que ser conectadas más tarde comparten los mismos vértices.

Así que primero creamos los puntos:

import FreeCAD as App
import Part
V1 = App.Vector(0, 10, 0)
V2 = App.Vector(30, 10, 0)
V3 = App.Vector(30, -10, 0)
V4 = App.Vector(0, -10, 0)

Inicio

Arco

Círculo


Para cada arco necesitamos un punto de ayuda:

VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
VC2 = App.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)

Inicio

Línea

Línea


Los segmentos de línea se pueden crear a partir de dos puntos:

L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)

Inicio

Poniendo todo junto

El último paso es poner los elementos base de la geometría juntos y formar una forma topológica:

S1 = Part.Shape([C1, L1, C2, L2])

Inicio

Crear un prisma

Ahora extruir el hilo en una dirección y crear una forma 3D real:

W = Part.Wire(S1.Edges)
P = W.extrude(App.Vector(0, 0, 10))

Inicio

Mostrar todo

Part.show(P)

Inicio

Crear formas básicas

Puedes crear fácilmente objetos topológicos básicos con los métodos make...() del módulo Pieza:

b = Part.makeBox(100, 100, 100)
Part.show(b)

Algunos métodos disponibles make...():

  • makeBox(l, w, h, [p, d]) Hace una caja situada en p y apuntando a la dirección d con las dimensiones (l,w,h).
  • makeCircle(radius) Hace un círculo con un radio determinado.
  • makeCone(radius1, radius2, height) Hace un cono con los radios y la altura dados.
  • makeCylinder(radius, height) Hace un cilindro con un radio y altura dados.
  • makeLine((x1, y1, z1), (x2, y2, z2)) Hace una línea desde dos puntos.
  • makePlane(length, width) Hace un plano con longitud y anchura.
  • makePolygon(list) Hace un polígono a partir de una lista de puntos.
  • makeSphere(radius) Hace una esfera con un radio determinado.
  • makeTorus(radius1, radius2) Hace un toro con los radios dados.

Ver la página Pieza API para una lista completa de los métodos disponibles del módulo Pieza.

Inicio

Módulos de importación

Primero necesitamos importar el módulo Pieza para poder usar su contenido en Python. También importaremos el módulo Base desde dentro del módulo FreeCAD:

import FreeCAD as App
import Part

Inicio

Crear un vector

Vectores son una de las piezas de información más importantes cuando se construir formas. Suelen contener tres números (pero no necesariamente siempre): las coordenadas cartesianas X, Y y Z. Se crea un vector así:

myVector = App.Vector(3, 2, 0)

Hemos creado un vector en las coordenadas X = 3, Y = 2, Z = 0. En el módulo de la pieza, los vectores se utilizan en todas partes. Las formas de la pieza también utilizan otro tipo de representación de puntos llamada Vértice que es simplemente un contenedor para un vector. Se accede al vector de un vértice así:

myVertex = myShape.Vertexes[0]
print(myVertex.Point)
> Vector (3, 2, 0)

Inicio

Crear un borde

Un borde no es más que una línea con dos vértices:

edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]

Nota: También se puede crear un borde pasando dos vectores:

vec1 = App.Vector(0, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()

Puedes encontrar la longitud y el centro de un borde así:

edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)

Inicio

Poniendo la forma en la pantalla

Hasta ahora hemos creado un objeto de borde, pero no aparece en ninguna parte de la pantalla. Esto se debe a que la escena 3D de FreeCAD sólo muestra lo que tú le dices que muestre. Para ello, utilizamos este sencillo método:

Part.show(edge)

La función mostrar crea un objeto en nuestro documento de FreeCAD y le asigna nuestra forma "borde". Utilízala siempre que sea el momento de mostrar tu creación en pantalla.

Inicio

Crear un hilo

Un hilo es una línea de varias aristas y puede crearse a partir de una lista de aristas o incluso de una lista de hilos:

edge1 = Part.makeLine((0, 0, 0), (10, 0, 0))
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0))
wire1 = Part.Wire([edge1, edge2]) 
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0))
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0))
wire2 = Part.Wire([edge3, edge4])
wire3 = Part.Wire([wire1, wire2])
wire3.Edges
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)

Part.show(wire3) mostrará las 4 aristas que componen nuestro contorno. Otra información útil se puede recuperar fácilmente:

wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False

Inicio

Creación de una cara

Sólo serán válidas las caras creadas a partir de contornos cerrados. En este ejemplo, wire3 es un contorno cerrado pero wire2 no es un contorno cerrado (mira más arriba)

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above):

face = Part.Face(wire3)
face.Area
> 99.99999999999999
face.CenterOfMass
> Vector (5, 5, 0)
face.Length
> 40.0
face.isValid()
> True
sface = Part.Face(wire2)
sface.isValid()
> False

Sólo las caras tendrán un área, ni los contornos ni las aristas.

Inicio

Crear un círculo

Se puede crear un círculo así:

circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))

Si quieres crearlo en una cierta posición y con una cierta dirección:

ccircle = Part.makeCircle(10, App.Vector(10, 0, 0), App.Vector(1, 0, 0))
ccircle.Curve
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))

ccircle se creará a una distancia de 10 en el eje x desde el origen, y estará orientado hacia el eje x. Nota: makeCircle sólo acepta Base.Vector() para posición y normal, pero no admite tuplas. Tambien puedes crear una parte de una circunferencia dando su ángulo de inicio y fin, así:

from math import pi
arc1 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)

Juntando arc1 y arc2 obtendremos una circunferencia. Los ángulos deberán indicarse en grados, si los tienes en radianes simplemente conviertelos según la fórmula: degrees = radians * 180/PI o usando el módulo Python de matemáticas (después de importarlo, obviamente):

import math
degrees = math.degrees(radians)

Inicio

Creación de un arco por varios puntos

Desafortunadamente no hay ninguna función makeArc pero tenemos la función Part.Arc para crear un arco a lo largo de tres puntos. Básicamente se puede suponer como un arco de unión entre el punto de partida y el punto final, pasando por el punto medio. Part.Arc crea un objeto arco en el que .toShape() tiene que ser llamado para obtener el objeto arista, del mismo modo como utilizamos Part.Line en lugar de Part.makeLine.

Unfortunately there is no makeArc() function, but we have the Part.Arc() function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's toShape() function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine.

arc = Part.Arc(App.Vector(0, 0, 0), App.Vector(0, 5, 0), App.Vector(5, 5, 0))
arc
> <Arc object>
arc_edge = arc.toShape()
Part.show(arc_edge)

Arc solo acepta puntos como Base.Vector() no acepta tuplas. arc_edge es lo que queremos que podemos mostrar utilizando Part.show(arc_edge). También puedes obtener un arco utilizando una porción de una circunferencia:

arc_edge es lo que queríamos conseguir, y podemos visualizar utilizando Part.show (arc_edge). Si desea una pequeña parte de un círculo como un arco, también es posible:

from math import pi
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)

Los arcos son aristas válidas, como las líneas. Así que también pueden utilizarse en los contornos.

Inicio

Creación de un polígono

Un polígono es simplemente un contorno con múltiples aristas rectas. La función makePolygon toma una lista de puntos y crea un contorno a través de dichos puntos:

A polygon is simply a wire with multiple straight edges. The makePolygon() function takes a list of points and creates a wire through those points:

lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])

Inicio

Create a Bézier curve

Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve() from a series of FreeCAD.Vector() points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0.

def makeBCurveEdge(Points):
   geomCurve = Part.BezierCurve()
   geomCurve.setPoles(Points)
   edge = Part.Edge(geomCurve)
   return(edge)

Inicio

Creación de un plano

Un plano es simplemente una superficie rectangular plana. El método utilizado para crear uno es este: makePlane(length,width,[start_pnt,dir_normal]). Por defecto start_pnt = Vector(0,0,0) y dir_normal = Vector(0,0,1). Utilizando dir_normal = Vector(0,0,1) crearemos el plano orientado hacia el eje Z, mientras que con dir_normal = Vector(1,0,0) crearemos el plano orientado hacia el eje X:

A Plane is a flat rectangular surface. The method used to create one is makePlane(length, width, [start_pnt, dir_normal]). By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction:

plane = Part.makePlane(2, 2)
plane
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.Vector(0, 1, 0))
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)

BoundBox es un prisma encerrando el plano con una diagonal empezando en (3,0,0) y terminando en (5,0,2). Aquí el espesor de BoundBox en el eje Y es cero, ya que nuestra forma es totalmente plana.

Nota: makePlane sólo acepta Base.Vector() para start_pnt y dir_normal pero no tuplas

Inicio

Creación de una elipse

Para crear una elipse existen varios métodos:

There are several ways to create an ellipse:

Part.Ellipse()

Crea una elipse cuyo radio mayor es 2 y el radio menor 1 con centro en el (0,0,0)

Part.Ellipse(Ellipse)

Crea una copia de la elipse dada

Part.Ellipse(S1, S2, Center)

Crea una elipse centrada en el punto Center, donde el plano de la elipse está definido por Center, S1 y S2, su eje mayor está definido por Center y S1, su radio mayor es la distancia entre Center y S1, y su radio menor es la distancia entre S2 y el eje mayor.

Part.Ellipse(Center, MajorRadius, MinorRadius)

Crea una elipse con radios mayor y menor MajorRadius y MinorRadius respectivamente, y ubicada en el plano definido por Center y la normal (0,0,1)

eli = Part.Ellipse(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.Vector(0, 0, 0))
Part.show(eli.toShape())

En el código de arriba hemos pasado S1, S2 y center. De forma similar a Arc, Ellipse también crea un objeto elipse pero no una arista, así que tenemos que convertirlo en una arista utilizando toShape() para mostrarlo.

Nota: Arc sólo acepta Base.Vector() para puntos pero no tuplas

eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())

para el constructor de la elipse de arriba hemos pasado el centro, MajorRadius y MinorRadius

Inicio

Creación de un toro

Utilizando el método makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]). Por defecto pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 y angle=360. Considera un toro como un pequeño circulo barrido a lo largo de una circunferencia grande. Radius1 es el radio de la circunferencia grande, radius2 es el radio del círculo pequeño, pnt es el centro del toro y dir es la dirección normal. angle1 y angle2 son ángulos en radianes para el círculo pequeño, el último parámetro angle es para hacer una sección del toro:

Using makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus:

torus = Part.makeTorus(10, 2)

El código de arriba creará un toro con diámetro 20 (radio 10) y espesor 4 (radio del círculo pequeño 2)

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)

El código de arriba creará una sección del toro

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 360, 180)

El código de arriba creará un semi toro, sólo el último parámetro se ha cambiado, dando el valor 180 creará el toro desde 0 hasta 180, eso es, medio toro.

Inicio

Creación de un cubo o prisma

Utilizando makeBox(length,width,height,[pnt,dir]). Por defecto pnt=Vector(0,0,0) y dir=Vector(0,0,1)

Using makeBox(length, width, height, [pnt, dir]). By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1).

box = Part.makeBox(10, 10, 10)
len(box.Vertexes)
> 8

Inicio

Creación de una esfera

Utilizando makeSphere(radius,[pnt, dir, angle1,angle2,angle3]). Por defecto pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 y angle3=360. angle1 y angle2 son el punto vertical mínimo y máximo de la esfera, angle3 es el diámetro de la esfera.

Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter.

sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)

Inicio

Creación de un cilindro

Utilizando makeCylinder(radius,height,[pnt,dir,angle]). Por defecto pnt=Vector(0,0,0),dir=Vector(0,0,1) y angle=360

Using makeCylinder(radius, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

cylinder = Part.makeCylinder(5, 20)
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Inicio

Creación de un cono

Utilizando makeCone(radius1,radius2,height,[pnt,dir,angle]). Por defecto pnt=Vector(0,0,0), dir=Vector(0,0,1) y angle=360

Using makeCone(radius1, radius2, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Inicio

Modificando formas

Existen diversos métodos para modificar formas. Algunas son simples operaciones de transformación como mover o rotar formas, otras son más complejas, como la unión y diferencia de una forma y otra. are simple transformation operations such as moving or rotating shapes, other are more complex, such as unioning and subtracting one shape from another. Tenlo en cuenta

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.

Inicio

Operaciones de transformación

Traslación de una forma

Traslación es el acto de mover una forma de una situación a otra. Cualquier forma (aristas, caras, cubos, etc...) se puede trasladar del mismo modo:

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way:

myShape = Part.makeBox(2, 2, 2)
myShape.translate(App.Vector(2, 0, 0))

Esto moverá nuestra forma "myShape" 2 unidades en la dirección del eje X.

Inicio

Rotación de una forma

Para rotar una forma, necesitas especificar el centro de rotación, el eje, y el ángulo de rotación:

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:

myShape.rotate(App.Vector(0, 0, 0),App.Vector(0, 0, 1), 180)

El código de arriba rotará la forma 180 grados alrededor del eje Z.

Inicio

Transformaciones genéricas con matrices

Una matriz es un modo muy conveniente de almacenar transformaciones en el mundo 3D. En una simple matriz, puedes establecer traslaciones, rotaciones y valores de escala a ser aplicados a un objeto. Por ejemplo:

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example:

myMat = App.Matrix()
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)

Nota: Las matrices de FreeCAD funcionan en radianes. También, casi todas las operaciones de matrices que toman un vector pueden tomar 3 números, así estas dos líneas hacen lo mismo:

myMat.move(2, 0, 0)
myMat.move(App.Vector(2, 0, 0))

Cuando nuestra matriz es establecida, podemos aplicarla a nuestra forma. FreeCAD proporciona 2 métodos para hacerlo: transformShape() y transformGeometry(). La diferencia es que con el primero, estas seguro de que no ocurrirá ninguna deformación (mira "escalando una forma" más abajo). Podemos aplicar nuestra transformación así:

myShape.transformShape(myMat)

o

myShape.transformGeometry(myMat)

Inicio

Escalando una forma

Escalando una forma es una operación más peligrosa porque, a diferencia de la traslación o rotación, un escalado no uniforme (con diferentes valores para los ejes X,Y y Z) puede modificar la estructura de la forma. Por ejemplo, escalando una circunferencia con un valor horizontal superior al vertical la transformará en una elipse, que se comporta matemáticamente de forma muy diferente. Para el escalado, no podemos utilizar transformShape, tenemos que usar transformGeometry():

Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the transformShape(), we must use transformGeometry():

myMat = App.Matrix()
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)

Inicio

Operaciones Booleanas

Diferencia

La diferencia de una forma con otra se llama "corte" en el argot de OCC/FreeCAD y se hace así:

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:

cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)

Inicio

Intersección

del mismo modo, la intersección entre dos formas es denominada "común" y se hace de este modo:

The same way, the intersection between two shapes is called "common" and is done this way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)

Inicio

Unión

La unión se llama "fusión" y funciona del mismo modo:

Union is called "fuse" and works the same way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)

Inicio

Sección

Una sección es la intersección entre una forma de un sólido y una forma de un plano. Devolverá una curva de intersección, un componente con aristas

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges.

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section.Wires
> []
section.Edges
> [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, 
 <Edge  object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, 
 <Edge object at 0D8F4BB0>]

Inicio

Extrusión

Extrusión es el acto de "empujar" una forma plana en determinada dirección resultando en un cuerpo sólido. Piensa en una círculo convirtiéndose en un tubo:

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out":

circle = Part.makeCircle(10)
tube = circle.extrude(App.Vector(0, 0, 2))

Si tu círculo está hueco, obtendrás un tubo hueco. Si no es hueco, obtendrás un cilindro sólido:

wire = Part.Wire(circle)
disc = Part.Face(wire)
cylinder = disc.extrude(App.Vector(0, 0, 2))

Inicio

Exploración de formas

Puedes explorar fácilmente la estructura de datos topológicos:

You can easily explore the topological data structure:

import Part
b = Part.makeBox(100, 100, 100)
b.Wires
w = b.Wires[0]
w
w.Wires
w.Vertexes
Part.show(w)
w.Edges
e = w.Edges[0]
e.Vertexes
v = e.Vertexes[0]
v.Point

Escribiendo las líneas de arriba en el interprete de Python, conseguirás una buena comprensión de la estructura de los objetos de piezas. Aquí, nuestro comando makeBox() crea una forma sólida. Este sólido, como todos los sólidos de piezas, contiene caras. Las caras siempre contienen contornos, que son listas de aristas que bordean la cara. Cada cara tiene al menos un contorno cerrado (puede tener más si la cara tiene huecos). En el contorno, podemos mirar en cada arista de forma separada, y dentro de cada arista, podemos ver los vértices. Las aristas rectas tienen sólo dos vértices, obviamente.

Inicio

Análisis de aristas

En el caso de una arista con una curva arbitraria, es más probable que quieras hacer una discretización. En FreeCAD las aristas son parametrizadas por sus longitudes. Eso significa que puedes recorrer una arista/curva por su longitud:

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length:

import Part
box = Part.makeBox(100, 100, 100)
anEdge = box.Edges[0]
print(anEdge.Length)

Ahora puedes acceder a un montón de propiedades de la arista utilizando la longitud como una posición. Eso significa que si la arista es de 100mm de longitud el punto inicial es y la posición final es 100.

anEdge.tangentAt(0.0)          # tangent direction at the beginning
anEdge.valueAt(0.0)            # Point at the beginning
anEdge.valueAt(100.0)          # Point at the end of the edge
anEdge.derivative1At(50.0)     # first derivative of the curve in the middle
anEdge.derivative2At(50.0)     # second derivative of the curve in the middle
anEdge.derivative3At(50.0)     # third derivative of the curve in the middle
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.curvatureAt(50.0)       # the curvature
anEdge.normalAt(50)            # normal vector at that position (if defined)

Inicio

Utilizando la selección

Aquí vemos ahora cómo podemos utilizar la selección que el usuario hizo en la vista. Antes de nada creamos un cubo y lo mostramos en la vista

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer.

import Part
Part.show(Part.makeBox(100, 100, 100))
Gui.SendMsgToActiveView("ViewFit")

Selecciona ahora algunas caras o aristas. Con este archivo de guión puedes iterar todos los objetos seleccionados y sus subelementos:

for o in Gui.Selection.getSelectionEx():
    print(o.ObjectName)
    for s in o.SubElementNames:
        print("name: ", s)
        for s in o.SubObjects:
            print("object: ", s)

Selecciona algunas aristas y este archivo de guión calculará la longitud:

length = 0.0
for o in Gui.Selection.getSelectionEx():
    for s in o.SubObjects:
        length += s.Length

print("Length of the selected edges: ", length)

Inicio

Examen completo: La botella OCC

Un ejemplo típico encontrado en la página de primeros pasos de OpenCasCade es cómo construir una botella. Este es un buen ejercicio también para FreeCAD. En realidad, puedes seguir nuestro ejemplo de abajo y la página de OCC simultáneamente, comprenderás bien cómo están implementadas las estructuras de OCC en FreeCAD. El archivo de guión completo de abajo está también incluido en la instalación de FreeCAD (dentro del directorio Mod/Part) y puede llamarse desde el interprete de Python escribiendo:

A typical example found on the OpenCasCade Technology website is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the Python interpreter by typing:

import Part
import MakeBottle
bottle = MakeBottle.makeBottle()
Part.show(bottle)

Inicio

El archivo de guión completo

Aquí está el archivo de guión completo MakeBottle:

For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.

import FreeCAD as App
import Part, math

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)
    myBody = myBody.fuse(myNeck)

    return myBody

el = makeBottleTut()
Part.show(el)

Inicio

Explicación detallada

import FreeCAD as App
import Part, math

Necesitaremos, desde luego, el módulo de piezas, pero también el módulo FreeCAD.Base, que contiene estructuras básicas de FreeCAD como vectores y matrices.

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

Aquí definimos nuestra función makeBottle. Esta función se puede llamar sin argumentos, como hicimos arriba, en cuyo caso se utilizaran los valores por defecto para ancho, alto, y espesor. Luego, definimos un conjunto de puntos que serán utilizados para construir nuestro perfil base.

...
    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

Aquí en realidad definimos la geometría: un arco, creado por 3 puntos, y dos segmentos de línea, creados por 2 puntos.

...
    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

Recuerdas la diferencia entre geometría y formas? Aquí construimos formas a partir de nuestra geometría de construcción. 3 aristas (las aristas pueden ser rectas o curvas), luego un contorno creado a partir de dichas tres aristas.

...
    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

Hasta ahora construimos sólo medio perfil. Más sencillo que construir el perfil completo del mismo modo, simplemente podemos crear una simetría de lo que hicimos, y pegar ambas partes. Así primero creamos una matriz. Una matriz es un modo muy común para aplicar transformaciones a objetos en el mundo 3D, ya que puede contener en una estructura todas las transformaciones básicas que los objetos pueden sufrir (mover, rotar y escalar). Aquí, después de crear la matriz, creamos una simétrica, y creamos una copia de nuestro contorno con esa matriz de transformación aplicada. Ahora tenemos 2 contornos, y podemos crear un tercer contorno a partir de ellos, ya que los contornos son en realidad listas de aristas.

...
    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

Ahora que tenemos un contorno cerrado, se puede convertir en una cara. Una vez que tengamos una cara, podemos extruirla. Haciendo esto, creamos un sólido. Entonces aplicamos un pequeño redondeo a nuestro objeto porque queremos crear un buen diseño, no es así?

...
    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)

El cuerpo de nuestra botella está creado, aún tenemos que crear el cuello. Así que creamos un nuevo sólido, con un cilindro.

...
    myBody = myBody.fuse(myNeck)

La operación de fusión, que en otras aplicaciones es llamada unión, es muy potente. Tendrá cuidado de pegar lo que necesita ser pegado y eliminar las partes que necesiten ser eliminadas.

...
    return myBody

Obtenemos nuestro sólido de pieza como resultado de nuestra función. Ese sólido de pieza, como cualquier otra forma de piezas, se puede atribuir a un objeto en el documento de FreeCAD, con:

el = makeBottleTut()
Part.show(el)

o, de forma más simple:

Inicio

Example: Pierced box

Here is a complete example of building a pierced box.

The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder through it.

import FreeCAD as App
import Part, math

size = 10
poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)])

face1 = Part.Face(poly)
face2 = Part.Face(poly)
face3 = Part.Face(poly)
face4 = Part.Face(poly)
face5 = Part.Face(poly)
face6 = Part.Face(poly)
     
myMat = App.Matrix()

myMat.rotateZ(math.pi / 2)
face2.transformShape(myMat)
face2.translate(App.Vector(size, 0, 0))

myMat.rotateZ(math.pi / 2)
face3.transformShape(myMat)
face3.translate(App.Vector(size, size, 0))

myMat.rotateZ(math.pi / 2)
face4.transformShape(myMat)
face4.translate(App.Vector(0, size, 0))

myMat = App.Matrix()

myMat.rotateX(-math.pi / 2)
face5.transformShape(myMat)

face6.transformShape(myMat)               
face6.translate(App.Vector(0, 0, size))

myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])   
mySolid = Part.makeSolid(myShell)

myCyl = Part.makeCylinder(2, 20)
myCyl.translate(App.Vector(size / 2, size / 2, 0))

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)

Inicio

Cargando y guardando

Existen diversas formas de guardar tu trabajo en el módulo de piezas. Puedes desde luego guardar el documento de FreeCAD, pero también puedes guardar objetos de pieza directamente en formatos de CAD comunes, como BREP, IGS, STEP y STL.

There are several ways to save your work. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL.

El guardado de una forma en un archivo es sencillo. Existen los métodos exportBrep(), exportIges(), exportStl() y exportStep() disponibles para todos los objetos de forma. Así, haciendo:

import Part
s = Part.makeBox(10, 10, 10)
s.exportStep("test.stp")

se guardará nuestro cubo en un archivo STEP. Para cargar un archivo BREP, IGES o STEP, simplemente haz lo contrario:

import Part
s = Part.Shape()
s.read("test.stp")

To convert a STEP file to an IGS file:

import Part
 s = Part.Shape()
 s.read("file.stp")       # incoming file igs, stp, stl, brep
 s.exportIges("file.igs") # outbound file igs

Inicio

Mesh Scripting/es
Mesh to Part/es


Convertir Objetos parte en mallas

La conversión de objetos de alto nivel, tales como formas de Piezas en objetos más simples como mallas es una operación bastante sencilla, en la que todas las caras de un objeto Pieza son triangularizadas. El resultado de esa triangulación (o teselado) se utiliza para construir una malla:

import Mesh

obj = FreeCADGui.Selection.getSelection()[0] # a Part object must be preselected
shp = obj.Shape
faces = []

triangles = shp.tessellate(1) # the number represents the precision of the tessellation
for tri in triangles[1]:
    face = []
    for i in tri:
        face.append(triangles[0][i])
    faces.append(face)

m = Mesh.Mesh(faces)
Mesh.show(m)

Alternative example:

import Mesh
import MeshPart

obj = FreeCADGui.Selection.getSelection()[0] # a Part object must be preselected
shp = obj.Shape

mesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "Mesh")
mesh.Mesh = MeshPart.meshFromShape(
        Shape=shp,
        LinearDeflection=0.01,
        AngularDeflection=0.025,
        Relative=False)

Convertir Mallas en objetos Pieza

La conversión de mallas en objetos Pieza es una operación muy importante en el trabajo de CAD, ya que a menudo se reciben datos 3D en formato de malla de otras personas o son generados con otras aplicaciones. Las mallas son muy prácticas para representar la geometría de forma libre y para grandes escenas visuales, ya que son muy ligeras. Pero, por lo general, el CAD prefiere objetos de nivel superior que llevan mucha más información, como la idea de sólidos, o caras hechas de curvas, en lugar de triángulos.

La conversión de las mallas a esos objetos de nivel superior (manejados por el Módulo de Piezas en FreeCAD) no es una operación fácil. Las mallas pueden tener miles de triángulos (por ejemplo, los generados por un escáner 3D), y si los sólidos se hacen con el mismo número de caras, serían extremadamente pesados de manipular. Así que por lo general, se desea optimizar el objeto durante la conversión.

FreeCAD actualmente ofrece dos métodos para convertir mallas en piezas. El primer método es una conversión sencilla, directa, sin ningún tipo de optimización:

import Mesh
import Part

mesh = Mesh.createTorus()
shape = Part.Shape()
shape.makeShapeFromMesh(mesh.Topology, 0.05) # the second arg is the tolerance for sewing
solid = Part.makeSolid(shape)
Part.show(solid)

El segundo método ofrece la posibilidad de considerar coplanares las facetas de malla que forman entre si un pequeño ángulo. Esto permite la construcción de formas mucho más simples:

import Mesh
import Part
import MeshPart

obj = FreeCADGui.Selection.getSelection()[0] # a Mesh object must be preselected
mesh = obj.Mesh
segments = mesh.getPlanarSegments(0.00001) # use rather strict tolerance here
faces = []

for i in segments:
    if len(i) > 0:
        # a segment can have inner holes
        wires = MeshPart.wireFromSegment(mesh, i)
        # we assume that the exterior boundary is that one with the biggest bounding box
        if len(wires) > 0:
            ext = None
            max_length=0
            for i in wires:
                if i.BoundBox.DiagonalLength > max_length:
                    max_length = i.BoundBox.DiagonalLength
                    ext = i

            wires.remove(ext)
            # all interior wires mark a hole and must reverse their orientation, otherwise Part.Face fails
            for i in wires:
                i.reverse()

            # make sure that the exterior wires comes as first in the list
            wires.insert(0, ext)
            faces.append(Part.Face(wires))

solid = Part.Solid(Part.Shell(faces))
Part.show(solid)



Introduction

La geometría que aparece en las vistas 3D de FreeCAD son renderizadas por la biblioteca Coin3D. Coin3D es una implementación del estandard OpenInventor. El software OpenCascade también proporciona la misma funcionalidad, pero se decidió, al comenzar el desarrollo de FreeCAD, no utilizar el visor de OpenCascade, sino cambiar al software Coin3D, por tener mejor rendimiento. Un buen modo de aprender sobre esa librería es el libro Open Inventor Mentor.

Description

OpenInventor es en realidad un lenguaje de descripción de escena 3D. La escena descrita en openInventor es seguidamente renderizada en la pantalla con OpenGL. Coin3d se encarga de hacer esto, por lo que el programador no tiene que lidiar con complejas llamadas a OpenGL, bastará con que le proporcione código OpenInventor válido. La gran ventaja es que openInventor es un estándard muy bien conocido y bien documentado.

Uno de los trabajos mas inportantes que FreeCAD hace por ti es, básicamente, traducir la información de geometría OpenCascade al idioma de openInventor.

OpenInventor describe una escena 3D en forma de una escena gráfica (scenegraph), como la siguiente:

image from Inventor mentor

Una escena gráfica de openInventor describe todo lo que es parte de una escena 3D, como la geometría, colores, materiales, luces, etc, y organiza todos los datos en una estructura cómoda y clara. Todo puede agruparse en sub-estructuras, lo que te permite organizar los contenidos de tu escena más o menos de la forma que quiera. He aquí un ejemplo de un archivo de openInventor:

#Inventor V2.0 ascii
 
Separator { 
    RotationXYZ {	
       axis Z
       angle 0
    }
    Transform {
       translation 0 0 0.5
    }
    Separator {	
       Material {
          diffuseColor 0.05 0.05 0.05
       }
       Transform {
          rotation 1 0 0 1.5708
          scaleFactor 0.2 0.5 0.2
       }
       Cylinder {
       }
    }
}

Como puedes ver, la estructura es muy simple. Utiliza separadores para organizar los datos en bloques, parecido a como harías al organizar tus archivos en carpetas. Cada declaración afecta a lo que viene después, por ejemplo los dos primeros puntos de nuestro separador raíz son una rotación y una traslación, todo ello afectará al siguiente elemento, que es un separador. En ese separador, se define un material y otra transformación. Nuestro cilindro por lo tanto se verá afectado por las dos transformaciones, la que le fue aplicada directamente, y la que se aplicó al separador que le contiene.

También tenemos muchos otros tipos de elementos para organizar nuestra escena, como los grupos, conmutadores o anotaciones. Podemos definir materiales muy complejos para nuestros objetos, con el color, las texturas, los modos de sombreado y transparencia. También podemos definir las luces, cámaras, e incluso movimiento. También es posible integrar pedazos de secuencias de comandos en los archivos de openInventor, para definir comportamientos más complejos.

Si estás interesado en aprender más sobre openInventor, vete directamente a su referencia más famosa, Inventor mentor.

En FreeCAD, normalmente, no es necesario interactuar directamente con la escena gráfica (scenegraph) de openInventor. Cada objeto en un documento de FreeCAD, ya sea una malla, una forma de pieza o cualquier otra cosa, se convierte automáticamente en código de openInventor y se inserta en la escena gráfica (scenegraph) principal que aparecen en una vista 3D. Esa escena gráfica se actualiza continuamente cuando se hacen modificaciones, se añaden o eliminan objetos en el documento. De hecho, cada objeto (en el espacio App) tiene un proveedor de vista (un objeto correspondiente en el espacio de la interfaz gráfica del usuario GUI), responsable de la expedición de código de openInventor.

Pero poder acceder a la escena gráfica directamente tiene muchas ventajas. Por ejemplo, puedes cambiar temporalmente la apariencia de un objeto, o podemos agregar objetos a la escena que no tienen existencia real en el documento de FreeCAD, como la geometría constructiva, ayudantes, sugerencias o herramientas gráficas como manipuladores o información en pantalla.

FreeCAD cuenta con varias herramientas para ver o modificar código de openInventor. Por ejemplo, el código de Python siguiente muestra la representación en openInventor de un objeto seleccionado:

obj = FreeCAD.ActiveDocument.ActiveObject
viewprovider = obj.ViewObject
print viewprovider.toString()

Pero también tenemos un módulo de Python que permite un acceso completo a todo lo controlado por Coin3d, como la escena gráfica (scenegraph) de FreeCAD. Sigue leyendo en Pivy.

Coding examples

See Coin3d snippets courtesy of MariwanJ's research for the Design456 Workbench. The code repository can be found at https://github.com/MariwanJ/COIN3D_Snippet.

Inicio

Mesh to Part/es
Pivy/es


Introduction

Pivy es una biblioteca para enlazar Python con Coin3d, la biblioteca de renderizado-3D utilizada en FreeCAD. Cuando se importa en un intérprete de Python en ejecución, permite dialogar directamente con cualquier escenas gráficas (scenegraphs) de Coin3d en ejecución, como las vistas 3D de FreeCAD, o incluso para crear otras nuevas. Pivy se incluye en la instalación estándar de FreeCAD.

When imported in a running Python interpreter, Pivy allows us to communicate directly with any running Coin scenegraph, such as the 3D view, or even to create new ones. Pivy is not required to compile FreeCAD, but it is required at runtime when running Python-based workbenches that create shapes on screen, like Draft and Arch. Because of this, Pivy is normally installed when installing a distribution of FreeCAD.

La biblioteca de Coin se divide en varias partes, la propia Coin, para manipular escenas gráficas, y pasarelas a varios sistemas de interfaz gráfica de usuario (GUI), tales como Windows o, en nuestro caso, Qt. Esos módulos están también disponibles para Pivy, si están presentes en el sistema. El módulo Coin está siempre presente, y es lo que vamos a utilizar en todos los casos, y no tendrás que preocuparte de anclar nuestra pantalla 3D en ninguna interfaz, ya que FreeCAD ya lo ha hecho por si mismo. Todo lo que necesitamos hacer es esto:

from pivy import coin

Acceso y modificación de la escena gráfica

Vimos en la Página de escenas gráficas cómo se organiza una típica escena de Coin. Todo lo que aparece en una vista 3D de FreeCAD es una escena gráfica de Coin, organizada de la misma manera. Tenemos un nodo raíz, y todos los objetos en la pantalla son sus hijos.

FreeCAD tiene una sencilla forma de acceder al nodo raíz de una escenas gráficas en vista 3D:

sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
print(sg)

Esto devolverá el nodo raíz:

<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >

Podemos inspeccionar los elementos secundarios inmediatos de nuestra escena:

for node in sg.getChildren():
    print(node)

Algunos de esos nodos, tales como SoSeparators o SoGroups, pueden tener sus propios hijos. La lista completa de los objetos de Coin disponibles se puede encontrar en la documentación oficial de Coin.

Ahora vamos a tratar de añadir algo a nuestra escena gráfica. Vamos a añadir un bonito cubo rojo:

col = coin.SoBaseColor()
col.rgb = (1, 0, 0)
cub = coin.SoCube()
myCustomNode = coin.SoSeparator()
myCustomNode.addChild(col)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)

y aquí está nuestro (magnífico) cubo rojo. Ahora, vamos a probar esto:

col.rgb = (1, 1, 0)

¿Ves? todo se mantiene accesible y modificable sobre la marcha. No hay necesidad de volver a calcular o dibujar cualquier cosa, Coin se encarga de todo. Puedes agregar cosas a la escena gráfica, cambiar las propiedades, ocultar cosas, mostrar objetos temporales, cualquier cosa. Por supuesto, esto sólo afecta a la pantalla en la vista 3D. Esa pantalla se vuelve a calcular por FreeCAD al abrir el archivo, y cuando un objeto necesita recalcularse. Por lo tanto, si cambias el aspecto de un objeto FreeCAD existente, esos cambios se perderán si el objeto se vuelve a recalcular o cuando se vuelve a abrir el archivo.

Una de las claves para trabajar con escenas gráficas en los archivos de guión es poder tener acceso cuando sea necesario a ciertas propiedades de los nodos que has añadido. Por ejemplo, si quisieramos mover nuestro cubo, habríamos añadido un nodo SoTranslation a nuestro nodo de referencia, y se vería así:

col = coin.SoBaseColor()
col.rgb = (1, 0, 0)
trans = coin.SoTranslation()
trans.translation.setValue([0, 0, 0])
cub = coin.SoCube()
myCustomNode = coin.SoSeparator()
myCustomNode.addChild(col)
myCustomNode.addChild(trans)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)

Recuerda que en una escena gráfica de openInventor, el orden es importante. Un nodo afecta a lo que viene a continuación, por lo que puedes decir algo como: color rojo, cubo, color amarillo, esfera, y obtendrás un cubo rojo y una esfera amarilla. Si ahora añadimos la traslación a nuestro nodo de referencia existente, eso llegaría después del cubo, y no lo afectaría. Si lo hubieramos insertado cuando lo creamos, como aquí arriba, ahora podríamos hacer:

trans.translation.setValue([2, 0, 0])

Y nuestro cubo saltaría 2 unidades a la derecha. Por último, para eliminar algo se hace con:

sg.removeChild(myCustomNode)

Inicio

La utilización de mecanismos de devolución de llamada

Un callback mechanism (mecanismo de devolución de llamada) es un sistema que permite a una biblioteca que se está utilizando, como la biblioteca Coin, que le devuelva la llamada, es decir, que llame a una función específica de tu objeto de Python ejecutado actualmente. Esto es muy útil, porque de esa manera Coin puede avisarte si algún evento específico se produce en la escena. Coin pueden ver cosas muy diferentes, como la posición del ratón, clics en un botón del ratón, las teclas del teclado que son pulsadas y muchas otras cosas.

FreeCAD cuenta con una sencilla manera de utilizar devoluciones de llamada de este tipo:

from pivy import coin

class ButtonTest:
    def __init__(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.callback = self.view.addEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), self.getMouseClick) 

    def getMouseClick(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == coin.SoMouseButtonEvent.DOWN:
            print("Alert!!! A mouse button has been improperly clicked!!!")
            self.view.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), self.callback)

ButtonTest()

La devolución de llamada tiene que ser iniciada por un objeto, y ese objeto debe estar todavía en ejecución cuando la devolución de llamada se produzca. Mira también una lista completa de los eventos posibles y sus parámetros, o la documentación oficial de Coin.

Inicio

Documentación

Lamentablemente Pivy aún no tiene una documentación formal, pero como es una traducción exacta de Coin, puedes utilizar con seguridad la documentación de Coin como referencia, y utilizar el estilo de Python en lugar del estilo de C++ (por ejemplo, SoFile::getClassTypeId() se escribiría en Pivy como: SoFile.getClassId() )

In C++:

SoFile::getClassTypeId()

In Pivy:

SoFile.getClassId()

Older

These links provide reference documentation for Coin v3.x. The differences with v4.x are minimal, so they may still be useful.

Inicio

Scenegraph/es
PySide/es

PyQt/es


Introduction

Además de los tipos de objetos estándar, tales como anotaciones, mallas y objetos de pieza, FreeCAD también ofrece la estupenda posibilidad de construir objetos de archivos de guión hechos al 100% en Python, llamados Funcionalidades Python (Feature Python). Esos objetos se comportan exactamente como cualquier otro objeto de FreeCAD, y se guardar y restauran automáticamente al guardar o cargar archivos.

Debe comprenderse una particularidad, dichos objetos son guardados en archivos FcStd de FreeCAD con el módulo de Python cPickle. Este módulo devuelve un objeto de Python como una cadena de texto, permitiendo que se añada al guardado del archivo. En la carga, el módulo cPickle utiliza esa cadena de texto para recrear los objetos originales, proporcionándole acceso al código fuente que creó el objeto. Es decir que si guardas un objeto personalizado y lo abres en un ordenador en el que el código de Python que generó dicho objeto no está presente, el objeto no será recreado. Si distribuyes dichos objetos a otros usuarios, tendrás que distribuirlos junta al archivo de guión de Python que los crea.

Note: It is possible to pack python code inside a FreeCAD file using json serializing with an App::PropertyPythonObject, but that code can never directly be run, and therefore has little use for our purpose here.

Las Funcionalidades Python siguen las mismas reglas que todas las Funcionalidades de FreeCAD: se separan en las partes de App y GUI. La parte de App, el objeto documento, define la geometría de nuestro objeto, mientras que su parte GUI, el objeto proveedor de vistas, define el modo en que el objeto se dibujará en la pantalla. El objeto proveedor de vistas, como cualquier otra Funcionalidad de FreeCAD, sólo está disponible cuando se ejecuta FreeCAD en su propio GUI. Hay varias propiedades y métodos disponibles para construir tu objeto. Las propiedades tienen que ser de cualquiera de los tipos predefinidos de propiedades que ofrece FreeCAD, y aparecerá en la ventana de vista de propiedades, por lo que puede ser editado por el usuario. De esta manera, los objetos Funcionalidad Python son total y absolutamente paramétricos. Puedes definir las propiedades del objeto y de su ViewObject por separado.

Basic example

Ejemplo básico

El ejemplo siguiente se puede encontrar en el archivo src/Mod/TemplatePyMod/FeaturePython.py , junto con varios otros ejemplos:

'''Examples for a feature class and its view provider.'''

import FreeCAD, FreeCADGui
from pivy import coin

class Box:
    def __init__(self, obj):
        '''Add some custom properties to our box feature'''
        obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box").Length = 1.0
        obj.addProperty("App::PropertyLength", "Width", "Box", "Width of the box").Width = 1.0
        obj.addProperty("App::PropertyLength", "Height", "Box", "Height of the box").Height = 1.0
        obj.Proxy = self

    def onChanged(self, fp, prop):
        '''Do something when a property has changed'''
        FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")

    def execute(self, fp):
        '''Do something when doing a recomputation, this method is mandatory'''
        FreeCAD.Console.PrintMessage("Recompute Python Box feature\n")

class ViewProviderBox:
    def __init__(self, obj):
        '''Set this object to the proxy object of the actual view provider'''
        obj.addProperty("App::PropertyColor","Color", "Box", "Color of the box").Color = (1.0, 0.0, 0.0)
        obj.Proxy = self

    def attach(self, obj):
        '''Setup the scene sub-graph of the view provider, this method is mandatory'''
        self.shaded = coin.SoGroup()
        self.wireframe = coin.SoGroup()
        self.scale = coin.SoScale()
        self.color = coin.SoBaseColor()

        data=coin.SoCube()
        self.shaded.addChild(self.scale)
        self.shaded.addChild(self.color)
        self.shaded.addChild(data)
        obj.addDisplayMode(self.shaded, "Shaded");
        style=coin.SoDrawStyle()
        style.style = coin.SoDrawStyle.LINES
        self.wireframe.addChild(style)
        self.wireframe.addChild(self.scale)
        self.wireframe.addChild(self.color)
        self.wireframe.addChild(data)
        obj.addDisplayMode(self.wireframe, "Wireframe");
        self.onChanged(obj,"Color")

    def updateData(self, fp, prop):
        '''If a property of the handled feature has changed we have the chance to handle this here'''
        # fp is the handled feature, prop is the name of the property that has changed
        l = fp.getPropertyByName("Length")
        w = fp.getPropertyByName("Width")
        h = fp.getPropertyByName("Height")
        self.scale.scaleFactor.setValue(float(l), float(w), float(h))
        pass

    def getDisplayModes(self,obj):
        '''Return a list of display modes.'''
        modes=[]
        modes.append("Shaded")
        modes.append("Wireframe")
        return modes

    def getDefaultDisplayMode(self):
        '''Return the name of the default display mode. It must be defined in getDisplayModes.'''
        return "Shaded"

    def setDisplayMode(self,mode):
        '''Map the display mode defined in attach with those defined in getDisplayModes.\
                Since they have the same names nothing needs to be done. This method is optional'''
        return mode

    def onChanged(self, vp, prop):
        '''Here we can do something when a single property got changed'''
        FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
        if prop == "Color":
            c = vp.getPropertyByName("Color")
            self.color.rgb.setValue(c[0], c[1], c[2])

    def getIcon(self):
        '''Return the icon in XPM format which will appear in the tree view. This method is\
                optional and if not defined a default icon is shown.'''
        return """
            /* XPM */
            static const char * ViewProviderBox_xpm[] = {
            "16 16 6 1",
            "   c None",
            ".  c #141010",
            "+  c #615BD2",
            "@  c #C39D55",
            "#  c #000000",
            "$  c #57C355",
            "        ........",
            "   ......++..+..",
            "   .@@@@.++..++.",
            "   .@@@@.++..++.",
            "   .@@  .++++++.",
            "  ..@@  .++..++.",
            "###@@@@ .++..++.",
            "##$.@@$#.++++++.",
            "#$#$.$$$........",
            "#$$#######      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            " #$#$$$$$#      ",
            "  ##$$$$$#      ",
            "   #######      "};
            """

    def dumps(self):
        '''When saving the document this object gets stored using Python's json module.\
                Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
                to return a tuple of all serializable objects or None.'''
        return None

    def loads(self,state):
        '''When restoring the serialized object from document we have the chance to set some internals here.\
                Since no data were serialized nothing needs to be done here.'''
        return None

def makeBox():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Box")
    Box(a)
    ViewProviderBox(a.ViewObject)

makeBox()

Things to note

If your object relies on being recomputed as soon as it is created, you must do this manually in the __init__ function as it is not called automatically. This example does not require it because the onChanged method of the Box class has the same effect as the execute function, but the examples below rely on being recomputed before anything is displayed in the 3D view. In the examples, this is done manually with ActiveDocument.recompute() but in more complex scenarios you need to decide where to recompute either the whole document or the FeaturePython object.

This example produces a number of exception stack traces in the report view window. This is because the onChanged method of the Box class is called each time a property is added in __init__. When the first one is added, the Width and Height properties don't exist yet and so the attempt to access them fails.

An explanation of __getstate__ and __setstate__ which have been replaced by dumps and loads is in the forum thread obj.Proxy.Type is a dict, not a string.

obj.addProperty(...) returns obj, so that the value of the property can be set on the same line:

obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box").Length = 1.0

Which is equivalent to:

obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box")
obj.Length = 1.0

Other more complex example

Otro ejemplo más complejo

En este ejemplo se hace uso del Módulo de Pieza para crear un octaedro, a continuación, se crea su representación Coin con Pivy.

Lo primero es el propio objeto del documento:

import FreeCAD, FreeCADGui, Part
import pivy
from pivy import coin

class Octahedron:
  def __init__(self, obj):
     "Add some custom properties to our box feature"
     obj.addProperty("App::PropertyLength","Length","Octahedron","Length of the octahedron").Length=1.0
     obj.addProperty("App::PropertyLength","Width","Octahedron","Width of the octahedron").Width=1.0
     obj.addProperty("App::PropertyLength","Height","Octahedron", "Height of the octahedron").Height=1.0
     obj.addProperty("Part::PropertyPartShape","Shape","Octahedron", "Shape of the octahedron")
     obj.Proxy = self

  def execute(self, fp):
     # Define six vetices for the shape
     v1 = FreeCAD.Vector(0,0,0)
     v2 = FreeCAD.Vector(fp.Length,0,0)
     v3 = FreeCAD.Vector(0,fp.Width,0)
     v4 = FreeCAD.Vector(fp.Length,fp.Width,0)
     v5 = FreeCAD.Vector(fp.Length/2,fp.Width/2,fp.Height/2)
     v6 = FreeCAD.Vector(fp.Length/2,fp.Width/2,-fp.Height/2)

     # Make the wires/faces
     f1 = self.make_face(v1,v2,v5)
     f2 = self.make_face(v2,v4,v5)
     f3 = self.make_face(v4,v3,v5)
     f4 = self.make_face(v3,v1,v5)
     f5 = self.make_face(v2,v1,v6)
     f6 = self.make_face(v4,v2,v6)
     f7 = self.make_face(v3,v4,v6)
     f8 = self.make_face(v1,v3,v6)
     shell=Part.makeShell([f1,f2,f3,f4,f5,f6,f7,f8])
     solid=Part.makeSolid(shell)
     fp.Shape = solid

  # helper mehod to create the faces
  def make_face(self,v1,v2,v3):
     wire = Part.makePolygon([v1,v2,v3,v1])
     face = Part.Face(wire)
     return face

después, conseguimos el objeto proveedor de vista, responsable de mostrar el objeto en la escena 3D:

class ViewProviderOctahedron:
  def __init__(self, obj):
     "Set this object to the proxy object of the actual view provider"
     obj.addProperty("App::PropertyColor","Color","Octahedron","Color of the octahedron").Color=(1.0,0.0,0.0)
     obj.Proxy = self

  def attach(self, obj):
     "Setup the scene sub-graph of the view provider, this method is mandatory"
     self.shaded = coin.SoGroup()
     self.wireframe = coin.SoGroup()
     self.scale = coin.SoScale()
     self.color = coin.SoBaseColor()

     self.data=coin.SoCoordinate3()
     self.face=coin.SoIndexedFaceSet()

     self.shaded.addChild(self.scale)
     self.shaded.addChild(self.color)
     self.shaded.addChild(self.data)
     self.shaded.addChild(self.face)
     obj.addDisplayMode(self.shaded,"Shaded");
     style=coin.SoDrawStyle()
     style.style = coin.SoDrawStyle.LINES
     self.wireframe.addChild(style)
     self.wireframe.addChild(self.scale)
     self.wireframe.addChild(self.color)
     self.wireframe.addChild(self.data)
     self.wireframe.addChild(self.face)
     obj.addDisplayMode(self.wireframe,"Wireframe");
     self.onChanged(obj,"Color")

  def updateData(self, fp, prop):
     "If a property of the handled feature has changed we have the chance to handle this here"
     # fp is the handled feature, prop is the name of the property that has changed
     if prop == "Shape":
        s = fp.getPropertyByName("Shape")
        self.data.point.setNum(6)
        cnt=0
        for i in s.Vertexes:
           self.data.point.set1Value(cnt,i.X,i.Y,i.Z)
           cnt=cnt+1

        self.face.coordIndex.set1Value(0,0)
        self.face.coordIndex.set1Value(1,1)
        self.face.coordIndex.set1Value(2,2)
        self.face.coordIndex.set1Value(3,-1)

        self.face.coordIndex.set1Value(4,1)
        self.face.coordIndex.set1Value(5,3)
        self.face.coordIndex.set1Value(6,2)
        self.face.coordIndex.set1Value(7,-1)

        self.face.coordIndex.set1Value(8,3)
        self.face.coordIndex.set1Value(9,4)
        self.face.coordIndex.set1Value(10,2)
        self.face.coordIndex.set1Value(11,-1)

        self.face.coordIndex.set1Value(12,4)
        self.face.coordIndex.set1Value(13,0)
        self.face.coordIndex.set1Value(14,2)
        self.face.coordIndex.set1Value(15,-1)

        self.face.coordIndex.set1Value(16,1)
        self.face.coordIndex.set1Value(17,0)
        self.face.coordIndex.set1Value(18,5)
        self.face.coordIndex.set1Value(19,-1)

        self.face.coordIndex.set1Value(20,3)
        self.face.coordIndex.set1Value(21,1)
        self.face.coordIndex.set1Value(22,5)
        self.face.coordIndex.set1Value(23,-1)

        self.face.coordIndex.set1Value(24,4)
        self.face.coordIndex.set1Value(25,3)
        self.face.coordIndex.set1Value(26,5)
        self.face.coordIndex.set1Value(27,-1)

        self.face.coordIndex.set1Value(28,0)
        self.face.coordIndex.set1Value(29,4)
        self.face.coordIndex.set1Value(30,5)
        self.face.coordIndex.set1Value(31,-1)

  def getDisplayModes(self,obj):
     "Return a list of display modes."
     modes=[]
     modes.append("Shaded")
     modes.append("Wireframe")
     return modes

  def getDefaultDisplayMode(self):
     "Return the name of the default display mode. It must be defined in getDisplayModes."
     return "Shaded"

  def setDisplayMode(self,mode):
     return mode

  def onChanged(self, vp, prop):
     "Here we can do something when a single property got changed"
     FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
     if prop == "Color":
        c = vp.getPropertyByName("Color")
        self.color.rgb.setValue(c[0],c[1],c[2])

  def getIcon(self):
     return """
        /* XPM */
        static const char * ViewProviderBox_xpm[] = {
        "16 16 6 1",
        "    c None",
        ".   c #141010",
        "+   c #615BD2",
        "@   c #C39D55",
        "#   c #000000",
        "$   c #57C355",
        "        ........",
        "   ......++..+..",
        "   .@@@@.++..++.",
        "   .@@@@.++..++.",
        "   .@@  .++++++.",
        "  ..@@  .++..++.",
        "###@@@@ .++..++.",
        "##$.@@$#.++++++.",
        "#$#$.$$$........",
        "#$$#######      ",
        "#$$#$$$$$#      ",
        "#$$#$$$$$#      ",
        "#$$#$$$$$#      ",
        " #$#$$$$$#      ",
        "  ##$$$$$#      ",
        "   #######      "};
        """

  def dumps(self):
     return None

  def loads(self,state):
     return None

Por último, una vez que nuestro objeto y su viewobject están definidos, sólo nos falta invocarlos:

FreeCAD.newDocument()
a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron")
Octahedron(a)
ViewProviderOctahedron(a.ViewObject)

Making objects selectable

Haciendo objetos seleccionables

Si deseas hacer tu objeto seleccionable, o al menos parte de el, haciendo clic sobre el en el visor, debes incluir su geometría Coin dentro de un nodo SoFCSelection. Si el objeto tiene una representación compleja, con widgets, anotaciones, etc, puede que desees incluir sólo una parte de el en un SoFCSelection. Todo lo que es un SoFCSelection es constantemente explorado por FreeCAD para detectar selección/preselección, por lo que tiene sentido evitar sobrecargalo con innecesarias exploraciones. Esto es lo que se haría para incluir un self.face en el ejemplo anterior:

Once the parts of the scenegraph that are to be selectable are inside SoFCSelection nodes, you then need to provide two methods to handle the selection path. The selection path can take the form of a string giving the names of each element in the path, or of an array of scenegraph objects. The two methods you provide are getDetailPath, which converts from a string path to an array of scenegraph objects, and getElementPicked, which takes an element which has been clicked on in the scenegraph and returns its string name (note, not its string path).

Here is the molecule example above, adapted to make the elements of the molecule selectable:

class Molecule:
    def __init__(self, obj):
        ''' Add two point properties '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0)

        obj.Proxy = self

    def onChanged(self, fp, prop):
        if prop == "p1" or prop == "p2":
            ''' Print the name of the property that has changed '''
            fp.Shape = Part.makeLine(fp.p1,fp.p2)

    def execute(self, fp):
        ''' Print a short message when doing a recomputation, this method is mandatory '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

class ViewProviderMolecule:
    def __init__(self, obj):
        ''' Set this object to the proxy object of the actual view provider '''
        obj.Proxy = self
        self.ViewObject = obj
        sep1=coin.SoSeparator()
        sel1 = coin.SoType.fromName('SoFCSelection').createInstance()
        # sel1.policy.setValue(coin.SoSelection.SHIFT)
        sel1.ref()
        sep1.addChild(sel1)
        self.trl1=coin.SoTranslation()
        sel1.addChild(self.trl1)
        sel1.addChild(coin.SoSphere())
        sep2=coin.SoSeparator()
        sel2 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel2.ref()
        sep2.addChild(sel2)
        self.trl2=coin.SoTranslation()
        sel2.addChild(self.trl2)
        sel2.addChild(coin.SoSphere())
        obj.RootNode.addChild(sep1)
        obj.RootNode.addChild(sep2)
        self.updateData(obj.Object, 'p2')
        self.sel1 = sel1
        self.sel2 = sel2

    def getDetailPath(self, subname, path, append):
        vobj = self.ViewObject
        if append:
            path.append(vobj.RootNode)
            path.append(vobj.SwitchNode)

            mode = vobj.SwitchNode.whichChild.getValue()
            if mode >= 0:
                mode = vobj.SwitchNode.getChild(mode)
                path.append(mode)
                sub = Part.splitSubname(subname)[-1]
                if sub == 'Atom1':
                    path.append(self.sel1)
                elif sub == 'Atom2':
                    path.append(self.sel2)
                else:
                    path.append(mode.getChild(0))
        return True

    def getElementPicked(self, pp):
        path = pp.getPath()
        if path.findNode(self.sel1) >= 0:
            return 'Atom1'
        if path.findNode(self.sel2) >= 0:
            return 'Atom2'
        raise NotImplementedError

    def updateData(self, fp, prop):
        "If a property of the handled feature has changed we have the chance to handle this here"
        # fp is the handled feature, prop is the name of the property that has changed
        if prop == "p1":
            p = fp.getPropertyByName("p1")
            self.trl1.translation=(p.x,p.y,p.z)
        elif prop == "p2":
            p = fp.getPropertyByName("p2")
            self.trl2.translation=(p.x,p.y,p.z)

    def dumps(self):
        return None

    def loads(self,state):
        return None

def makeMolecule():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Molecule")
    Molecule(a)
    ViewProviderMolecule(a.ViewObject)
    FreeCAD.ActiveDocument.recompute()

Working with simple shapes

Trabajar con formas simples

Si tu objeto paramétrico saca simplemente una forma, no es necesario utilizar un objeto proveedor de vista. La forma se mostrará en la representación de formas de FreeCAD:

import FreeCAD as App
import FreeCADGui
import FreeCAD
import Part
class Line:
    def __init__(self, obj):
        '''"App two point properties" '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(1,0,0)
        obj.Proxy = self

    def execute(self, fp):
        '''"Print a short message when doing a recomputation, this method is mandatory" '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
Line(a)
a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification)
FreeCAD.ActiveDocument.recompute()

Same code with use ViewProviderLine

import FreeCAD as App
import FreeCADGui
import FreeCAD
import Part

class Line:
    def __init__(self, obj):
         '''"App two point properties" '''
         obj.addProperty("App::PropertyVector","p1","Line","Start point")
         obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(100,0,0)
         obj.Proxy = self

    def execute(self, fp):
        '''"Print a short message when doing a recomputation, this method is mandatory" '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

class ViewProviderLine:
   def __init__(self, obj):
      ''' Set this object to the proxy object of the actual view provider '''
      obj.Proxy = self

   def getDefaultDisplayMode(self):
      ''' Return the name of the default display mode. It must be defined in getDisplayModes. '''
      return "Flat Lines"

a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
Line(a)
ViewProviderLine(a.ViewObject)
App.ActiveDocument.recompute()

Scenegraph Structure

You may have noticed that the examples above construct their scenegraphs in slightly different ways. Some use obj.addDisplayMode(node, "modename") while others use obj.SwitchNode.getChild(x).addChild(y).

Each feature in a FreeCAD document is based the following scenegraph structure:

RootNode
 \- SwitchNode
     \- Shaded
      - Wireframe
      - etc

The SwitchNode displays only one of its children, depending on which display mode is selection in FreeCAD.

The examples which use addDisplayMode are constructing their scenegraphs solely out of coin3d scenegraph elements. Under the covers, addDisplayMode adds a new child to the SwitchNode; the name of that node will match the display mode it was passed.

The examples which use SwitchNode.getChild(x).addChild also construct part of their geometry using functions from the Part workbench, such as fp.Shape = Part.makeLine(fp.p1,fp.p2). This constructs the different display mode scenegraphs under the SwitchNode; when we later come to add coin3d elements to the scenegraph, we need to add them to the existing display mode scenegraphs using addChild rather than creating a new child of the SwitchNode.

When using addDisplayMode() to add geometry to the scenegraph, each display mode should have its own node which is passed to addDisplayMode(); don't reuse the same node for this. Doing so will confuse the selection mechanism. It's okay if each display mode's node has the same geometry nodes added below it, just the root of each display mode needs to be distinct.

Here is the above molecule example, adapted to be drawn only with Coin3D scenegraph objects instead of using objects from the Part workbench:

import Part
from pivy import coin

class Molecule:
    def __init__(self, obj):
        ''' Add two point properties '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0)

        obj.Proxy = self

    def onChanged(self, fp, prop):
        pass

    def execute(self, fp):
        ''' Print a short message when doing a recomputation, this method is mandatory '''
        pass

class ViewProviderMolecule:
    def __init__(self, obj):
        ''' Set this object to the proxy object of the actual view provider '''
        self.constructed = False
        obj.Proxy = self
        self.ViewObject = obj

    def attach(self, obj):
        material = coin.SoMaterial()
        material.diffuseColor = (1.0, 0.0, 0.0)
        material.emissiveColor = (1.0, 0.0, 0.0)
        drawStyle = coin.SoDrawStyle()
        drawStyle.pointSize.setValue(10)
        drawStyle.style = coin.SoDrawStyle.LINES
        wireframe = coin.SoGroup()
        shaded = coin.SoGroup()
        self.wireframe = wireframe
        self.shaded = shaded

        self.coords = coin.SoCoordinate3()
        self.coords.point.setValues(0, 2, [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0)])
        wireframe += self.coords
        wireframe += drawStyle
        wireframe += material
        shaded += self.coords
        shaded += drawStyle
        shaded += material

        g = coin.SoGroup()
        sel1 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel1.style = 'EMISSIVE_DIFFUSE'
        p1 = coin.SoType.fromName('SoIndexedPointSet').createInstance()
        p1.coordIndex.set1Value(0, 0)
        sel1 += p1
        g += sel1
        wireframe += g
        shaded += g

        g = coin.SoGroup()
        sel2 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel2.style = 'EMISSIVE_DIFFUSE'
        p2 = coin.SoType.fromName('SoIndexedPointSet').createInstance()
        p2.coordIndex.set1Value(0, 1)
        sel2 += p2
        g += sel2
        wireframe += g
        shaded += g

        g = coin.SoGroup()
        sel3 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel3.style = 'EMISSIVE_DIFFUSE'
        p3 = coin.SoType.fromName('SoIndexedLineSet').createInstance()
        p3.coordIndex.setValues(0, 2, [0, 1])
        sel3 += p3
        g += sel3
        wireframe += g
        shaded += g

        obj.addDisplayMode(wireframe, 'Wireframe')
        obj.addDisplayMode(shaded, 'Shaded')

        self.sel1 = sel1
        self.sel2 = sel2
        self.sel3 = sel3
        self.constructed = True
        self.updateData(obj.Object, 'p2')

    def getDetailPath(self, subname, path, append):
        vobj = self.ViewObject
        if append:
            path.append(vobj.RootNode)
            path.append(vobj.SwitchNode)

            mode = vobj.SwitchNode.whichChild.getValue()
            FreeCAD.Console.PrintWarning("getDetailPath: mode {} is active\n".format(mode))
            if mode >= 0:
                mode = vobj.SwitchNode.getChild(mode)
                path.append(mode)
                sub = Part.splitSubname(subname)[-1]
                print(sub)
                if sub == 'Atom1':
                    path.append(self.sel1)
                elif sub == 'Atom2':
                    path.append(self.sel2)
                elif sub == 'Line':
                    path.append(self.sel3)
                else:
                    path.append(mode.getChild(0))
        return True

    def getElementPicked(self, pp):
        path = pp.getPath()
        if path.findNode(self.sel1) >= 0:
            return 'Atom1'
        if path.findNode(self.sel2) >= 0:
            return 'Atom2'
        if path.findNode(self.sel3) >= 0:
            return 'Line'
        raise NotImplementedError

    def updateData(self, fp, prop):
        "If a property of the handled feature has changed we have the chance to handle this here"
        # fp is the handled feature, prop is the name of the property that has changed
        if not self.constructed:
            return
        if prop == "p1":
            p = fp.getPropertyByName("p1")
            self.coords.point.set1Value(0, p)
        elif prop == "p2":
            p = fp.getPropertyByName("p2")
            self.coords.point.set1Value(1, p)

    def getDisplayModes(self, obj):
        return ['Wireframe', 'Shaded']

    def getDefaultDisplayMode(self):
        return 'Shaded'

    def setDisplayMode(self, mode):
        return mode

    def dumps(self):
        return None

    def loads(self,state):
        return None

def makeMolecule():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Molecule")
    Molecule(a)
    b=ViewProviderMolecule(a.ViewObject)
    a.touch()
    FreeCAD.ActiveDocument.recompute()
    return a,b

a,b = makeMolecule()

Part Design scripted objects

When making scripted objects in Part Design the process is similar to the scripted objects discussed above, but with a few additional considerations. We must handle 2 shape properties, one for the shape we see in the 3D view and another for the shape used by the pattern tools, such as polar pattern features. The object shapes also needs to be fused to any existing material already in the Body (or cut from it in the case of Subtractive features). And we must account for the placement and attachment of our objects a little bit differently.

Part Design scripted solid object features should be based on either PartDesign::FeaturePython, PartDesign::FeatureAdditivePython, or PartDesign::FeatureSubtractivePython rather than Part::FeaturePython. Only the Additive and Subtractive variants can be used in pattern features, and if based on Part::FeaturePython when the user drops the object into a Part Design Body it becomes a BaseFeature rather than being treated by the Body as a native Part Design object. Note: all of these are expected to be solids, so if you are making a non-solid feature it should be based on Part::FeaturePython or else the next feature in the tree will attempt to fuse to as a solid and it will fail.

Here is a simple example of making a Tube primitive, similar to the Tube primitive in Part Workbench except this one will be a Part Design solid feature object. For this we will 2 separate files: pdtube.FCMacro and pdtube.py. The .FCMacro file will be executed by the user to create the object. The .py file will hold the class definitions, imported by the .FCMacro. The reason for doing it this way is to maintain the parametric nature of the object after restarting FreeCAD and opening a document containing one of our Tubes.

First, the class definition file:

# -*- coding: utf-8 -*-
#classes should go in pdtube.py
import FreeCAD, FreeCADGui, Part
class PDTube:
    def __init__(self,obj):
        obj.addProperty("App::PropertyLength","Radius1","Tube","Radius1").Radius1 = 5
        obj.addProperty("App::PropertyLength","Radius2","Tube","Radius2").Radius2 = 10
        obj.addProperty("App::PropertyLength","Height","Tube","Height of tube").Height = 10
        self.makeAttachable(obj)
        obj.Proxy = self

    def makeAttachable(self, obj):

        if int(FreeCAD.Version()[1]) >= 19:
            obj.addExtension('Part::AttachExtensionPython')
        else:
            obj.addExtension('Part::AttachExtensionPython', obj)

        obj.setEditorMode('Placement', 0) #non-readonly non-hidden

    def execute(self,fp):
        outer_cylinder = Part.makeCylinder(fp.Radius2, fp.Height)
        inner_cylinder = Part.makeCylinder(fp.Radius1, fp.Height)
        if fp.Radius1 == fp.Radius2: #just make cylinder
            tube_shape = outer_cylinder
        elif fp.Radius1 < fp.Radius2:
            tube_shape = outer_cylinder.cut(inner_cylinder)
        else: #invert rather than error out
            tube_shape = inner_cylinder.cut(outer_cylinder)

        if not hasattr(fp, "positionBySupport"):
            self.makeAttachable(fp)
        fp.positionBySupport()
        tube_shape.Placement = fp.Placement

        #BaseFeature (shape property of type Part::PropertyPartShape) is provided for us
        #with the PartDesign::FeaturePython and related classes, but it might be empty
        #if our object is the first object in the tree.  it's a good idea to check
        #for its existence in case we want to make type Part::FeaturePython, which won't have it

        if hasattr(fp, "BaseFeature") and fp.BaseFeature != None:
            if "Subtractive" in fp.TypeId:
                full_shape = fp.BaseFeature.Shape.cut(tube_shape)
            else:
                full_shape = fp.BaseFeature.Shape.fuse(tube_shape)
            full_shape.transformShape(fp.Placement.inverse().toMatrix(), True) #borrowed from gears workbench
            fp.Shape = full_shape
        else:
            fp.Shape = tube_shape
        if hasattr(fp,"AddSubShape"): #PartDesign::FeatureAdditivePython and
                                      #PartDesign::FeatureSubtractivePython have this
                                      #property but PartDesign::FeaturePython does not
                                      #It is the shape used for copying in pattern features
                                      #for example in making a polar pattern
            tube_shape.transformShape(fp.Placement.inverse().toMatrix(), True)
            fp.AddSubShape = tube_shape

class PDTubeVP:
    def __init__(self, obj):
        '''Set this object to the proxy object of the actual view provider'''
        obj.Proxy = self

    def attach(self,vobj):
        self.vobj = vobj

    def updateData(self, fp, prop):
        '''If a property of the handled feature has changed we have the chance to handle this here'''
        pass

    def getDisplayModes(self,obj):
        '''Return a list of display modes.'''
        modes=[]
        modes.append("Flat Lines")
        modes.append("Shaded")
        modes.append("Wireframe")
        return modes

    def getDefaultDisplayMode(self):
        '''Return the name of the default display mode. It must be defined in getDisplayModes.'''
        return "Flat Lines"

    def setDisplayMode(self,mode):
        '''Map the display mode defined in attach with those defined in getDisplayModes.\
                Since they have the same names nothing needs to be done. This method is optional'''
        return mode

    def onChanged(self, vp, prop):
        '''Here we can do something when a single property got changed'''
        #FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
        pass

    def getIcon(self):
        '''Return the icon in XPM format which will appear in the tree view. This method is\
                optional and if not defined a default icon is shown.'''
        return """
            /* XPM */
            static const char * ViewProviderBox_xpm[] = {
            "16 16 6 1",
            "   c None",
            ".  c #141010",
            "+  c #615BD2",
            "@  c #C39D55",
            "#  c #000000",
            "$  c #57C355",
            "        ........",
            "   ......++..+..",
            "   .@@@@.++..++.",
            "   .@@@@.++..++.",
            "   .@@  .++++++.",
            "  ..@@  .++..++.",
            "###@@@@ .++..++.",
            "##$.@@$#.++++++.",
            "#$#$.$$$........",
            "#$$#######      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            " #$#$$$$$#      ",
            "  ##$$$$$#      ",
            "   #######      "};
            """

    def dumps(self):
        '''When saving the document this object gets stored using Python's json module.\
                Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
                to return a tuple of all serializable objects or None.'''
        return None

    def loads(self,state):
        '''When restoring the serialized object from document we have the chance to set some internals here.\
                Since no data were serialized nothing needs to be done here.'''
        return None

And now the macro file to create the object:

# -*- coding: utf-8 -*-

#pdtube.FCMacro
import pdtube
#above line needed if the class definitions above are place in another file: PDTube.py
#this is needed if the tube object is to remain parametric after restarting FreeCAD and loading
#a document containing the object

body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody")
if not body:
    FreeCAD.Console.PrintError("No active body.\n")
else:
    from PySide import QtGui
    window = FreeCADGui.getMainWindow()
    items = ["Additive","Subtractive","Neither additive nor subtractive"]
    item,ok =QtGui.QInputDialog.getItem(window,"Select tube type","Select whether you want additive, subtractive, or neither:",items,0,False)
    if ok:
        if item == items[0]:
            className = "PartDesign::FeatureAdditivePython"
        elif item == items[1]:
            className = "PartDesign::FeatureSubtractivePython"
        else:
            className = "PartDesign::FeaturePython" #not usable in pattern features, such as polar pattern

        tube = FreeCAD.ActiveDocument.addObject(className,"Tube")
        pdtube.PDTube(tube)
        pdtube.PDTubeVP(tube.ViewObject)
        body.addObject(tube) #optionally we can also use body.insertObject() for placing at particular place in tree

Available object types

The list of all object types you can create with FreeCAD.ActiveDocument.addObject() can be obtained with FreeCAD.ActiveDocument.supportedTypes(). Only object types with a name ending in Python can be used for scripted objects. These are listed here (for FreeCAD v0.21):

  • App::DocumentObjectGroupPython
  • App::FeaturePython
  • App::GeometryPython
  • App::LinkElementPython
  • App::LinkGroupPython
  • App::LinkPython
  • App::MaterialObjectPython
  • App::PlacementPython
  • Part::CustomFeaturePython
  • Part::FeaturePython
  • Part::Part2DObjectPython
  • Path::FeatureAreaPython
  • Path::FeatureAreaViewPython
  • Path::FeatureCompoundPython
  • Path::FeaturePython
  • Path::FeatureShapePython
  • Sketcher::SketchObjectPython
  • TechDraw::DrawComplexSectionPython
  • TechDraw::DrawLeaderLinePython
  • TechDraw::DrawPagePython
  • TechDraw::DrawRichAnnoPython
  • TechDraw::DrawTemplatePython
  • TechDraw::DrawTilePython
  • TechDraw::DrawTileWeldPython
  • TechDraw::DrawViewPartPython
  • TechDraw::DrawViewPython
  • TechDraw::DrawViewSectionPython
  • TechDraw::DrawViewSymbolPython
  • TechDraw::DrawWeldSymbolPython

Available methods

See FeaturePython methods for the complete reference.

Available properties

Propiedades disponibles

Las propiedades son las auténticas piedras de construcción de los objetos FeaturePython. A través de ellas, el usuario será capaz de interactuar y modificar su objeto. Después de crear un nuevo objeto FeaturePython en tu documento ( a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), puedes obtener una lista de las propiedades disponibles escribiendo:

obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Box")
obj.supportedProperties()

Obtendrás una lista de propiedades disponibles:

Cuando se añaden propiedades a tus objetos personalizados, ten en cuenta esto:

  • No utilices caracteres "<" o ">" en las descripciones de las propiedades (eso rompería las partes de xml en el archivo .fcstd)
  • Las propiedades se almacenan alfabéticamente en un archivo .fcstd. Si tienes una forma en tus propiedades, cualquier propiedad cuyo nombre va después de "Shape" en orden alfabético, se cargará DESPUÉS de la forma, lo que puede causar un comportamiento extraño.

The properties are defined in the PropertyStandard C++ header file.

Property types

By default properties can be updated, but it is possible to make properties read-only, for instance if one wants to show the result of a method. It is also possible to hide a property. The property type can be set using:

obj.setEditorMode("MyPropertyName", mode)

where mode is a short int that can be set to:

 0 -- default mode, read and write
 1 -- read-only
 2 -- hidden

The mode can also be set using a list of strings, e.g. obj.setEditorMode("Placement", ["ReadOnly", "Hidden"]).

The EditorModes are not set at FreeCAD file reload. This could to be done by the loads function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=10#p108072. By using the setEditorMode the properties are only read-only in the Property editor. They can still be changed from Python. To really make them read-only the setting has to be passed directly inside the addProperty function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=20#p109709 for an example.

Using the direct setting in the addProperty function, you also have more possibilities. In particular, an interesting one is mark a property as an output property. This way FreeCAD won't mark the feature as touched when changing it (so no need to recompute).

Example of output property (see also https://forum.freecadweb.org/viewtopic.php?t=24928):

obj.addProperty("App::PropertyString", "MyCustomProperty", "", "", 8)

The property types that can be set at last parameter of the addProperty function are:

  0 -- Prop_None, No special property type
  1 -- Prop_ReadOnly, Property is read-only in the editor
  2 -- Prop_Transient, Property won't be saved to file
  4 -- Prop_Hidden, Property won't appear in the editor
  8 -- Prop_Output, Modified property doesn't touch its parent container
 16 -- Prop_NoRecompute, Modified property doesn't touch its container for recompute
 32 -- Prop_NoPersist, Property won't be saved to file at all

The property types are defined in the PropertyContainer C++ header file.

Available extensions

The list of available extensions can be obtained with grep -RI EXTENSION_PROPERTY_SOURCE_TEMPLATE in the repository of the source code and is given here (for FreeCAD v0.21).

For objects:

  • App::GeoFeatureGroupExtensionPython
  • App::GroupExtensionPython
  • App::LinkBaseExtensionPython
  • App::LinkExtensionPython
  • App::OriginGroupExtensionPython
  • Part::AttachExtensionPython
  • TechDraw::CosmeticExtensionPython

For view objects:

  • Gui::ViewProviderExtensionPython
  • Gui::ViewProviderGeoFeatureGroupExtensionPython
  • Gui::ViewProviderGroupExtensionPython
  • Gui::ViewProviderOriginGroupExtensionPython
  • PartGui::ViewProviderAttachExtensionPython
  • PartGui::ViewProviderSplineExtensionPython

There exist other extensions but they do not work as-is:

  • App::ExtensionPython
  • TechDrawGui::ViewProviderCosmeticExtensionPython
  • TechDrawGui::ViewProviderDrawingViewExtensionPython
  • TechDrawGui::ViewProviderPageExtensionPython
  • TechDrawGui::ViewProviderTemplateExtensionPython

PySide/es
Embedding FreeCAD/es

Additional pages:

Interesting forum threads about scripted objects:

In addition to the examples presented here have a look at FreeCAD source code src/Mod/TemplatePyMod/FeaturePython.py for more examples.



Introduction

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

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 Blender. Aquí está el archivo de guión completo. Espero que te impresione por su sencillez:

FREECADPATH = '/usr/lib/freecad-python3/lib/' # path to your FreeCAD.so or FreeCAD.pyd file,
# for Windows you must either use \\ or / in the path, using a single \ is problematic
# FREECADPATH = 'C:\\FreeCAD\\bin'
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()

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.

FREECADPATH = 'C:\\FreeCAD\\bin' # path to your FreeCAD.so or FreeCAD.pyd file
import sys
sys.path.append(FREECADPATH)

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.

import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':

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!

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()

Por supuesto, como este archivo de guión es muy simple (de hecho hice uno más avanzados 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.

Note: checkout Headless FreeCAD for running FreeCAD without the GUI.

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.

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

import FreeCADGui 
FreeCADGui.showMainWindow()

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.

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.

Caveats

Although it is possible to import FreeCAD to an external Python interpreter, this is not a common usage scenario and requires some care. Generally, it is better to use the Python included with FreeCAD, run FreeCAD via command line, or as a subprocess. See Start up and Configuration for more on the last two options.

Since the FreeCAD Python module is compiled from C++ (rather than being a pure Python module), it can only be imported from a compatible Python interpreter. Generally this means that the Python interpreter must be compiled with the same C compiler as was used to build FreeCAD. Information about the compiler used to build a Python interpreter (including the one built with FreeCAD) can be found as follows:

>>> import sys
>>> sys.version
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'

Related



Introducción

Esta página contiene ejemplos, pedazos, trozos de código de Python en FreeCAD recogidos de experiencias de los usuarios y las discusiones en los forums foros. Lee y utilízala como punto de partida para tus propios archivos de guión ...

Fragmentos

Un típico archivo InitGui.py

Cada módulo debe contener, además de tu archivo del módulo principal, un archivo InitGui.py, responsable de insertar el módulo en la interfaz GUI principal. Este es un ejemplo de uno sencillo:

class ScriptWorkbench (Workbench): 
    MenuText = "Scripts"
    def Initialize(self):
        import Scripts # assuming Scripts.py is your module
        list = ["Script_Cmd"] # That list must contain command names, that can be defined in Scripts.py
        self.appendToolbar("My Scripts",list) 
        
Gui.addWorkbench(ScriptWorkbench())

Inicio

Un típico archivo de módulo

Este es un ejemplo de un archivo de módulo principal, que contiene todo lo que tu módulo hace. Es el archivo Scripts.py invocado por el ejemplo anterior. Puedes tener en él todos tus comandos personalizados.

import FreeCAD, FreeCADGui 
 
class ScriptCmd: 
   def Activated(self): 
       # Here your write what your ScriptCmd does...
       FreeCAD.Console.PrintMessage('Hello, World!')
   def GetResources(self): 
       return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} 
       
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())

Inicio

Importar un nuevo tipo de archivo

Hacer un importador para un nuevo tipo de archivo en FreeCAD es fácil. FreeCAD no considera que importes datos de un documento abierto, sino que simplemente puede abrir directamente el nuevo tipo de archivo. Así que, lo qué tienes que hacer es añadir la nueva extensión de archivo a la lista de las extensiones conocidas de FreeCAD, y escribir el código que leerá el archivo, y crear los objetos de FreeCAD que desees.

Esta línea debe añadirse al archivo InitGui.py para agregar la nueva extensión de archivo a la lista:

# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")

Y despues en el archivo Import_Ext.py :

def open(filename): 
   doc=App.newDocument()
   # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
   doc.recompute()

Para exportar tu documentno a algún nuevo tipo de archivo, se haría del mismo modo, salvo que usarías:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

Inicio

Añadir una linea

Una línea simplemente tiene 2 puntos.

import Part,PartGui 
doc=App.activeDocument() 
# add a line element to the document and set its points 
l=Part.LineSegment()
l.StartPoint=(0.0,0.0,0.0)
l.EndPoint=(1.0,1.0,1.0)
doc.addObject("Part::Feature","Line").Shape=l.toShape() 
doc.recompute()

Inicio

Añadir un polígono

Un polígono es simplemente un conjunto de segmentos de línea concetados (una polilínea en AutoCAD). No tiene que ser necesariamente cerrado.

import Part, PartGui 
doc = App.activeDocument()
n = list() 

# create a 3D vector, set its coordinates and add it to the list 
v = App.Vector(0,0,0) 
n.append(v) 
v = App.Vector(10,0,0) 
n.append(v) 
#... repeat for all nodes 

# Create a polygon object and set its nodes 
p = doc.addObject("Part::Polygon","Polygon") 
p.Nodes = n 
doc.recompute()

Inicio

Añadir y eliminar un objeto a/de un grupo

doc=App.activeDocument() 
grp=doc.addObject("App::DocumentObjectGroup", "Group") 
lin=doc.addObject("Part::Feature", "Line")
grp.addObject(lin) # adds the lin object to the group grp
grp.removeObject(lin) # removes the lin object from the group grp

Nota: También puedes añadir grupos a otros grupos...

Inicio

Añadir una Malla

import Mesh
doc=App.activeDocument()
# create a new empty mesh
m = Mesh.Mesh()
# build up box out of 12 facets
m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0)
m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0)
m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0)
m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0)
m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)
# scale to a edge langth of 100
m.scale(100.0)
# add the mesh to the active document
me=doc.addObject("Mesh::Feature","Cube")
me.Mesh=m

Inicio

Añadir un arco o un círculo

import Part
doc = App.activeDocument()
c = Part.Circle() 
c.Radius=10.0  
f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature 
f.Shape = c.toShape() # Assign the circle shape to the shape property 
doc.recompute()

Inicio

Acceder y cambiar la representación de un objeto

Cada objeto en un documento de FreeCAD tiene un objeto de representación de vista asociado que almacena todos los parámetros que definen cómo aparece ese objeto: por ejemplo, color, ancho de línea, etc... Ver también Listar los componentes de un objeto snippet abajo

gad = Gui.activeDocument() # access the active document containing all 
                           # view representations of the features in the
                           # corresponding App document 

v = gad.getObject("Cube")  # access the view representation to the Mesh feature 'Cube' 
v.ShapeColor               # prints the color to the console 
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white

Inicio

Sustituir la forma de ratón con una imagen

import PySide2
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QColor, QPixmap, QImage, QPainter, QCursor
from PySide2.QtCore import Qt

myImage = QtGui.QPixmap("Complete_Path_to_image.bmp")
cursor = QtGui.QCursor(myImage)
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(cursor))

Inicio

Sustituir la forma de ratón con una imagen (cruz) incluye

The image is created by Gimp exported in a .XPM file. Copy and use the code between the bracket "{" code to copy "}"

import PySide2
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QColor, QPixmap, QImage, QPainter, QCursor
from PySide2.QtCore import Qt

cross32x32Icon = [
"32 32 2 1",
" 	c None",
".	c #FF0000",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                                ",
"............... . ..............",
"                                ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               "
]

myImage = QtGui.QPixmap(cross32x32Icon)
cursor = QtGui.QCursor(myImage)
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(cursor))

Inicio

Observe camera change in the 3D viewer via Python

This can be done adding a Node sensor to the camera:

from pivy import coin
def callback(*args):
    cam, sensor = args
    print()
    print("Cam position : {}".format(cam.position.getValue().getValue()))
    print("Cam rotation : {}".format(cam.orientation.getValue().getValue()))

camera_node = Gui.ActiveDocument.ActiveView.getCameraNode()
node_sensor = coin.SoNodeSensor(callback, camera_node)
node_sensor.attach(camera_node)

Inicio

Observar los eventos del ratón en el visor 3D a través de Python

La estructura de Inventor permite añadir uno o más nodos de devolución de llamada al escenario gráfico del visor. De forma predeterminada en FreeCAD se instala un nodo de devolución de llamada por cada visor lo que permite añadir funciones C++ globales o estáticas. En el caso de la pasarela Python se han incluido algunos métodos para hacer uso de esta técnica dentro del código Python.

App.newDocument()
v=Gui.activeDocument().activeView()
 
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
   def logPosition(self, info):
       down = (info["State"] == "DOWN")
       pos = info["Position"]
       if (down):
           FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
       
o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)


Ahora, pulsa en algún lugar en la zona del visor 3D y observa los mensajes en la ventana de resultados. Para finalizar la observación sólo llama

v.removeEventCallback("SoMouseButtonEvent",c)

Se soportan los siguientes tipos de eventos:

  • SoEvent -- Todo tipo de eventos
  • SoButtonEvent -- Todos los eventos de los botones del ratón y del teclado
  • SoLocation2Event -- Eventos de movimiento 2D (normalmente movimientos del ratón)
  • SoMotion3Event -- Eventos de movimiento 3D (normalmente del spaceball)
  • SoKeyboardEvent -- Eventos de pulsar y soltar teclas
  • SoMouseButtonEvent -- Eventos de presionar y soltar los botones del ratón
  • SoSpaceballButtonEvent -- Eventos de presionar y soltar los botones del spaceball

La función de Python que se puede registrar con addEventCallback () espera un diccionario. Dependiendo del evento observado, el diccionario puede contener diferentes claves.

En todos los eventos existen las siguientes claves:

  • Type -- El nombre del tipo de evento i.e. SoMouseEvent, SoLocation2Event, ...
  • Time -- La hora actual como una cadena de texto
  • Position -- Una dupla de dos enteros, con la posición del ratón
  • ShiftDown -- Un booleano, true si la tecla Shift estaba presionada y false en caso contrario
  • CtrlDown -- Un booleano, true si la tecla Ctrl estaba presionada y false en caso contrario
  • AltDown -- Un booleano, true si la tecla Alt estaba presionada y false en caso contrario


Para los eventos de botones, (tanto del teclado, como del ratón o de un spaceball):

  • State -- Una cadena de texto 'UP' si el botón no estaba presionado, 'DOWN' si estaba presionado o 'UNKNOWN' para cualquier otro caso

Para eventos de teclado:

  • Key -- Un carácter de la tecla presionada

Para eventos de botón de ratón

  • Button -- El botón presionado, podría ser BUTTON1, ..., BUTTON5 o ANY

Para eventos de spaceball:

  • Button -- El botón presionado, podría ser BUTTON1, ..., BUTTON7 o ANY

Y por último, eventos de movimiento:

  • Translation -- Una tripla de tres números de coma flotante
  • Rotation -- Una cuádrupla para la rotación, i.e. a tupla de cuatro números de coma flotante

Inicio

Mostrar teclas pulsadas y comando eventos

Esta macro muestra en la vista de informes las teclas pulsadas y todos los eventos comando

App.newDocument()
v=Gui.activeDocument().activeView()
class ViewObserver:
   def logPosition(self, info):
       try:
           down = (info["Key"])
           FreeCAD.Console.PrintMessage(str(down)+"\n") # here the character pressed
           FreeCAD.Console.PrintMessage(str(info)+"\n") # list all events command
           FreeCAD.Console.PrintMessage("_______________________________________"+"\n")
       except Exception:
           None
 
o = ViewObserver()
c = v.addEventCallback("SoEvent",o.logPosition)

#v.removeEventCallback("SoEvent",c) # remove ViewObserver

Inicio

Manipular escenario gráfico en Python

También es posible obtener y cambiar el escenario gráfico en Python, con el módulo 'Pivy' - una pasarela de Python para Coin.

from pivy.coin import *                # load the pivy module
view = Gui.ActiveDocument.ActiveView   # get the active viewer
root = view.getSceneGraph()            # the root is an SoSeparator node
root.addChild(SoCube())
view.fitAll()

La API en Python de Pivy está creada utilizando la herramienta de SWIG. En FreeCAD se usan algunos nodos auto-escritos, que no pueden crearse directamente en Python. Sin embargo, es posible crear un nodo por su nombre interno. Se puede crear una instancia del tipo "SoFCSelection" con

type = SoType.fromName("SoFCSelection")
node = type.createInstance()

Inicio

Añadir y eliminar objetos al/del escenario gráfico

La adición de nuevos nodos al escenario gráfico se puede hacer de esta manera. Ten cuidado de añadir siempre un SoSeparator para contener la geometría, las coordenadas y la información de materiales de un mismo objeto. En el ejemplo siguiente se agrega una línea roja desde (0,0,0) a (10,0,0):

from pivy import coin
sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
co = coin.SoCoordinate3()
pts = [[0,0,0],[10,0,0]]
co.point.setValues(0,len(pts),pts)
ma = coin.SoBaseColor()
ma.rgb = (1,0,0)
li = coin.SoLineSet()
li.numVertices.setValue(2)
no = coin.SoSeparator()
no.addChild(co)
no.addChild(ma)
no.addChild(li)
sg.addChild(no)

Para quitarlo, simplemente escribe:

sg.removeChild(no)

Inicio

Guardar el sceneGraph en 3 series de 36 archivos

View the code snippet by expanding this section

import math
import time
from FreeCAD import Base
from pivy import coin

size=(1000,1000)
dirname = "C:/Temp/animation/"
steps=36
angle=2*math.pi/steps

matX=Base.Matrix()
matX.rotateX(angle)
stepsX=Base.Placement(matX).Rotation

matY=Base.Matrix()
matY.rotateY(angle)
stepsY=Base.Placement(matY).Rotation

matZ=Base.Matrix()
matZ.rotateZ(angle)
stepsZ=Base.Placement(matZ).Rotation

view=Gui.ActiveDocument.ActiveView
cam=view.getCameraNode()
rotCamera=Base.Rotation(*cam.orientation.getValue().getValue())

# this sets the lookat point to the center of circumsphere of the global bounding box
view.fitAll()

# the camera's position, i.e. the user's eye point
position=Base.Vector(*cam.position.getValue().getValue())
distance=cam.focalDistance.getValue()

# view direction
vec=rotCamera.multVec(Base.Vector(0,0,-1))

# this is the point on the screen the camera looks at
# when rotating the camera we should make this point fix
lookat=position+vec*distance

# around x axis
for i in range(steps):
    rotCamera=stepsX.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"x-%d.png" % i,*size)

# around y axis
for i in range(steps):
    rotCamera=stepsY.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"y-%d.png" % i,*size)

# around z axis
for i in range(steps):
    rotCamera=stepsZ.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"z-%d.png" % i,*size)

Inicio

Añadir asistentes personalizados a la interfaz

Puedes crear asisstentes personalizados con Qt designer, transformarlos es archivos de guión en Python, y luego cargarlos en la interfaz de FreeCAD con PyQt4.

El código de Python producido por el compilador-UI de python (la herramienta que convierte archivos .UI de Qt-designer en código de Python) tiene, en general, este aspecto (es simple, también puedes escribir el código directamente en Python):

class myWidget_Ui(object):
    def setupUi(self, myWidget):
        myWidget.setObjectName("my Nice New Widget")
        myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget
 
        self.label = QtGui.QLabel(myWidget) # creates a label
        self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
        self.label.setObjectName("label") # sets its name, so it can be found by name

    def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets
        myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))

Despues, todo lo que necesitas hacer es crear una referencia a la ventana Qt de FreeCAD, insertar un widget personalizado en ella, y "transformar" ese widget en el tuyo con el código UI que acabas de hacer:

app = QtGui.qApp
FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
# FCmw = FreeCADGui.getMainWindow() # use this line if the 'addDockWidget' error is declared
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget
myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Inicio

Añadir una pestaña a la vista combinada

El siguiente código te permite añadir una pestaña al Vista Combinada de FreeCAD, además de las pestañas "Proyecto" y "Tareas". Utiliza también el módulo UIC para cargar un archivo UI directamente en esa pestaña.

# create new Tab in ComboView
from PySide import QtGui,QtCore
#from PySide import uic

def getMainWindow():
   "returns the main window"
   # using QtGui.qApp.activeWindow() isn't very reliable because if another
   # widget than the mainwindow is active (e.g. a dialog) the wrong widget is
   # returned
   toplevel = QtGui.qApp.topLevelWidgets()
   for i in toplevel:
       if i.metaObject().className() == "Gui::MainWindow":
           return i
   raise Exception("No main window found")

def getComboView(mw):
   dw=mw.findChildren(QtGui.QDockWidget)
   for i in dw:
       if str(i.objectName()) == "Combo View":
           return i.findChild(QtGui.QTabWidget)
       elif str(i.objectName()) == "Python Console":
           return i.findChild(QtGui.QTabWidget)
   raise Exception ("No tab widget found")

mw = getMainWindow()
tab = getComboView(getMainWindow())
tab2=QtGui.QDialog()
tab.addTab(tab2,"A Special Tab")

#uic.loadUi("/myTaskPanelforTabs.ui",tab2)
tab2.show()
#tab.removeTab(2)

Inicio

Habilitar o deshabilitar una ventana

This script give the ability to manipulate the UI from the Python console to show/hide different components in the FreeCAD interface such as:

from PySide import QtGui
mw = FreeCADGui.getMainWindow()
dws = mw.findChildren(QtGui.QDockWidget)

# objectName may be :
# "Report view"
# "Tree view"
# "Property view"
# "Selection view"
# "Combo View"
# "Python console"
# "draftToolbar"

for i in dws:
  if i.objectName() == "Report view":
    dw = i
    break

va = dw.toggleViewAction()
va.setChecked(True)        # True or False
dw.setVisible(True)        # True or False

Inicio

Abrir una página web personalizada

import WebGui
WebGui.openBrowser("http://www.example.com")

Inicio

Obtener el contenido HTML de una página web abierta

from PySide import QtGui,QtWebKit
a = QtGui.qApp
mw = a.activeWindow()
v = mw.findChild(QtWebKit.QWebFrame)
html = unicode(v.toHtml())
print( html)

Inicio

Recuperar las coordenadas de 3 puntos u objetos seleccionados

# -*- coding: utf-8 -*-
# the line above to put the accentuated in the remarks
# If this line is missing, an error will be returned
# extract and use the coordinates of 3 objects selected
import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base, Console
sel = FreeCADGui.Selection.getSelection() # " sel " contains the items selected
if len(sel)!=3 :
  # If there are no 3 objects selected, an error is displayed in the report view
  # The \r and \n at the end of line mean return and the newline CR + LF.
  Console.PrintError("Select 3 points exactly\r\n")
else :
  points=[]
  for obj in sel:
    points.append(obj.Shape.BoundBox.Center)

  for pt in points:
    # display of the coordinates in the report view
    Console.PrintMessage(str(pt.x)+"\r\n")
    Console.PrintMessage(str(pt.y)+"\r\n")
    Console.PrintMessage(str(pt.z)+"\r\n")

  Console.PrintMessage(str(pt[1]) + "\r\n")

Inicio

Listar todos los objetos

# -*- coding: utf-8 -*-
import FreeCAD,Draft
# List all objects of the document
doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects
#App.Console.PrintMessage(str(objs) + "\n")
#App.Console.PrintMessage(str(len(FreeCAD.ActiveDocument.Objects)) + " Objects"  + "\n")

for obj in objs:
    a = obj.Name                                             # list the Name  of the object  (not modifiable)
    b = obj.Label                                            # list the Label of the object  (modifiable)
    try:
        c = obj.LabelText                                    # list the LabeText of the text (modifiable)
        App.Console.PrintMessage(str(a) +" "+ str(b) +" "+ str(c) + "\n") # Displays the Name the Label and the text
    except:
        App.Console.PrintMessage(str(a) +" "+ str(b) + "\n") # Displays the Name and the Label of the object

#doc.removeObject("Box") # Clears the designated object

Inicio

Listar las dimensiones de un objeto, dado su nombre

for edge in FreeCAD.ActiveDocument.MyObjectName.Shape.Edges: # replace "MyObjectName" for list
    print( edge.Length)

Inicio

Función residente con la acción del clic del ratón

Here with SelObserver on a object select

# -*- coding: utf-8 -*-
# causes an action to the mouse click on an object
# This function remains resident (in memory) with the function "addObserver(s)"
# "removeObserver(s) # Uninstalls the resident function
class SelObserver:
    def setPreselection(self,doc,obj,sub):                # Preselection object
        App.Console.PrintMessage(str(sub)+ "\n")          # The part of the object name

    def addSelection(self,doc,obj,sub,pnt):               # Selection object
        App.Console.PrintMessage("addSelection"+ "\n")
        App.Console.PrintMessage(str(doc)+ "\n")          # Name of the document
        App.Console.PrintMessage(str(obj)+ "\n")          # Name of the object
        App.Console.PrintMessage(str(sub)+ "\n")          # The part of the object name
        App.Console.PrintMessage(str(pnt)+ "\n")          # Coordinates of the object
        App.Console.PrintMessage("______"+ "\n")

    def removeSelection(self,doc,obj,sub):                # Remove the selection
        App.Console.PrintMessage("removeSelection"+ "\n")

    def setSelection(self,doc):                           # Set selection
        App.Console.PrintMessage("setSelection"+ "\n")

    def clearSelection(self,doc):                         # If click on the screen, clear the selection
        App.Console.PrintMessage("clearSelection"+ "\n")  # If click on another object, clear the previous object
s =SelObserver()
FreeCADGui.Selection.addObserver(s)                       # install the function mode resident
#FreeCADGui.Selection.removeObserver(s)                   # Uninstall the resident function

Other example with ViewObserver on a object select or view

App.newDocument()
v=Gui.activeDocument().activeView()
 
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
   def __init__(self, view):
       self.view = view
   
   def logPosition(self, info):
       down = (info["State"] == "DOWN")
       pos = info["Position"]
       if (down):
           FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
           pnt = self.view.getPoint(pos)
           FreeCAD.Console.PrintMessage("World coordinates: " + str(pnt) + "\n")
           info = self.view.getObjectInfo(pos)
           FreeCAD.Console.PrintMessage("Object info: " + str(info) + "\n")

o = ViewObserver(v)
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)

Inicio

Display the active document

class DocObserver:                      # document Observer
    def slotActivateDocument(self,doc):
        print(doc.Name)

obs=DocObserver()
App.addDocumentObserver(obs)
#App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

To remove the observer call:

App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

Inicio

Buscar/seleccionar todos los elementos por debajo del cursor

from pivy import coin
import FreeCADGui

def mouse_over_cb( event_callback):
    event = event_callback.getEvent()
    pos = event.getPosition().getValue()
    listObjects = FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo((int(pos[0]),int(pos[1])))
    obj = []
    if listObjects:
        FreeCAD.Console.PrintMessage("\n *** Objects under mouse pointer ***")
        for o in listObjects:
            label = str(o["Object"])
            if not label in obj:
                obj.append(label)
        FreeCAD.Console.PrintMessage("\n"+str(obj))


view = FreeCADGui.ActiveDocument.ActiveView

mouse_over = view.addEventCallbackPivy( coin.SoLocation2Event.getClassTypeId(), mouse_over_cb )

# to remove Callback :
#view.removeEventCallbackPivy( coin.SoLocation2Event.getClassTypeId(), mouse_over)

####
#The easy way is probably to use FreeCAD's selection.
#FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo(mouse_coords)

####
#you get that kind of result :
#'Document': 'Unnamed', 'Object': 'Box', 'Component': 'Face2', 'y': 8.604081153869629, 'x': 21.0, 'z': 8.553047180175781

####
#You can use this data to add your element to FreeCAD's selection :
#FreeCADGui.Selection.addSelection(FreeCAD.ActiveDocument.Box,'Face2',21.0,8.604081153869629,8.553047180175781)

Inicio

Listar los componentes de un objeto

This function list the components of an object and extracts:

  • this object its XYZ coordinates,
  • its edges and their lengths center of mass and coordinates
  • its faces and their center of mass
  • its faces and their surfaces and coordinates
# -*- coding: utf-8 -*-
# This function list the components of an object
# and extract this object its XYZ coordinates,
# its edges and their lengths center of mass and coordinates
# its faces and their center of mass
# its faces and their surfaces and coordinates
# 8/05/2014

import Draft,Part
def detail():
    sel = FreeCADGui.Selection.getSelection()   # Select an object
    if len(sel) != 0:                           # If there is a selection then
        Vertx=[]
        Edges=[]
        Faces=[]
        compt_V=0
        compt_E=0
        compt_F=0
        pas    =0
        perimetre = 0.0   
        EdgesLong = []

        # Displays the "Name" and the "Label" of the selection
        App.Console.PrintMessage("Selection > " + str(sel[0].Name) + "  " + str(sel[0].Label) +"\n"+"\n")

        for j in enumerate(sel[0].Shape.Edges):                                     # Search the "Edges" and their lengths
            compt_E+=1
            Edges.append("Edge%d" % (j[0]+1))
            EdgesLong.append(str(sel[0].Shape.Edges[compt_E-1].Length))
            perimetre += (sel[0].Shape.Edges[compt_E-1].Length)                     # calculates the perimeter

            # Displays the "Edge" and its length
            App.Console.PrintMessage("Edge"+str(compt_E)+" Length > "+str(sel[0].Shape.Edges[compt_E-1].Length)+"\n")

            # Displays the "Edge" and its center mass
            App.Console.PrintMessage("Edge"+str(compt_E)+" Center > "+str(sel[0].Shape.Edges[compt_E-1].CenterOfMass)+"\n")

            num = sel[0].Shape.Edges[compt_E-1].Vertexes[0]
            Vertx.append("X1: "+str(num.Point.x))
            Vertx.append("Y1: "+str(num.Point.y))
            Vertx.append("Z1: "+str(num.Point.z))
            # Displays the coordinates 1
            App.Console.PrintMessage("X1: "+str(num.Point[0])+" Y1: "+str(num.Point[1])+" Z1: "+str(num.Point[2])+"\n")

            try:
                num = sel[0].Shape.Edges[compt_E-1].Vertexes[1]
                Vertx.append("X2: "+str(num.Point.x))
                Vertx.append("Y2: "+str(num.Point.y))
                Vertx.append("Z2: "+str(num.Point.z))
            except:
                Vertx.append("-")
                Vertx.append("-")
                Vertx.append("-")
            # Displays the coordinates 2
            App.Console.PrintMessage("X2: "+str(num.Point[0])+" Y2: "+str(num.Point[1])+" Z2: "+str(num.Point[2])+"\n")

            App.Console.PrintMessage("\n")
        App.Console.PrintMessage("Perimeter of the form  : "+str(perimetre)+"\n") 

        App.Console.PrintMessage("\n")
        FacesSurf = []
        for j in enumerate(sel[0].Shape.Faces):                                      # Search the "Faces" and their surface
            compt_F+=1
            Faces.append("Face%d" % (j[0]+1))
            FacesSurf.append(str(sel[0].Shape.Faces[compt_F-1].Area))

            # Displays 'Face' and its surface
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Surface "+str(sel[0].Shape.Faces[compt_F-1].Area)+"\n")

            # Displays 'Face' and its CenterOfMass
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Center  "+str(sel[0].Shape.Faces[compt_F-1].CenterOfMass)+"\n")

            # Displays 'Face' and its Coordinates
            FacesCoor = []
            fco = 0
            for f0 in sel[0].Shape.Faces[compt_F-1].Vertexes:                        # Search the Vertexes of the face
                fco += 1
                FacesCoor.append("X"+str(fco)+": "+str(f0.Point.x))
                FacesCoor.append("Y"+str(fco)+": "+str(f0.Point.y))
                FacesCoor.append("Z"+str(fco)+": "+str(f0.Point.z))

            # Displays 'Face' and its Coordinates
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Coordinate"+str(FacesCoor)+"\n")

            # Displays 'Face' and its Volume
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Volume  "+str(sel[0].Shape.Faces[compt_F-1].Volume)+"\n")
            App.Console.PrintMessage("\n")

        # Displays the total surface of the form
        App.Console.PrintMessage("Surface of the form    : "+str(sel[0].Shape.Area)+"\n")

        # Displays the total Volume of the form
        App.Console.PrintMessage("Volume  of the form    : "+str(sel[0].Shape.Volume)+"\n")

detail()

Inicio

Listar de PropiedadesLista

import FreeCADGui
from FreeCAD import Console
o = App.ActiveDocument.ActiveObject
op = o.PropertiesList
for p in op:
    Console.PrintMessage("Property: "+ str(p)+ " Value: " + str(o.getPropertyByName(p))+"\r\n")

Inicio

Añadir un único comentario sobre la propiedad

import Draft
obj = FreeCADGui.Selection.getSelection()[0]
obj.addProperty("App::PropertyString","GComment","Draft","Font name").GComment = "Comment here"
App.activeDocument().recompute()

Inicio

Búsqueda y extracción de datos

Examples of research and decoding information on an object.

Each section is independently and is separated by "############" can be copied directly into the Python console, or in a macro or use this macro. The description of the macro in the commentary.

Displaying it in the "Report View" window (View > Views > Report view)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
 
# Exemples de recherche et de decodage d'informations sur un objet
# Chaque section peut etre copiee directement dans la console Python ou dans une macro ou utilisez la macro tel quel
# Certaines commandes se repetent seul l'approche est differente
# L'affichage se fait dans la Vue rapport : Menu Affichage > Vues > Vue rapport
#
# Examples of research and decoding information on an object
# Each section can be copied directly into the Python console, or in a macro or uses this macro
# Certain commands as repeat alone approach is different
# Displayed in Report view: View > Views > report view
#
# rev:30/08/2014:29/09/2014:17/09/2015 22/11/2019 30/12/2022
 
from FreeCAD import Base
import DraftVecUtils, Draft, Part

##################################################################################
# info in the object

box = App.ActiveDocument.getObject('Box')                                 # object 
####
print(dir(box))                                                           # all options disponible in the object
####
print(box.Name)                                                           # object name
####
print(box.Content)                                                        # content of the object in XML format
##################################################################################
#
# example of using the information listed
#
# search the name of the active document 
mydoc = FreeCAD.activeDocument().Name                                     # Name of active Document
App.Console.PrintMessage("Active docu    : "+(mydoc)+"\n")
##################################################################################

# search the document name and the name of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_FullName = sel[0].FullName                                         # file Name and Name of the object selected
App.Console.PrintMessage("object_FullName: "+(object_FullName)+"\n")
##################################################################################

# search the label of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_Label = sel[0].Label                                               # Label of the object (modifiable)
App.Console.PrintMessage("object_Label   : "+(object_Label)+"\n")
##################################################################################

#TypeID object FreeCAD selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
App.Console.PrintMessage("sel            : "+str(sel[0])+"\n\n")          # sel[0] first object selected
##################################################################################

# search the Name of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_Name  = sel[0].Name                                                # Name of the object (not modifiable)
App.Console.PrintMessage("object_Name    : "+str(object_Name)+"\n\n")
##################################################################################

# search the Sub Element Name of the sub object selected
try:
    SubElement = FreeCADGui.Selection.getSelectionEx()                    # sub element name with getSelectionEx()
    element_ = SubElement[0].SubElementNames[0]                           # name of 1 element selected
    App.Console.PrintMessage("elementSelec   : "+str(element_)+"\n\n")            
except:
    App.Console.PrintMessage("Oups"+"\n\n")            
##################################################################################

# give the length of the subObject selected
SubElementLength = Gui.Selection.getSelectionEx()[0].SubObjects[0].Length # sub element or element name with getSelectionEx()
App.Console.PrintMessage("SubElement length: "+str(SubElementLength)+"\n")# length
##################################################################################

# list the edges and the coordinates of the object[0] selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
i = 0
for j in enumerate(sel[0].Shape.Edges):                                   # list all Edges
    i += 1
    App.Console.PrintMessage("Edges n : "+str(i)+"\n")
    a = sel[0].Shape.Edges[j[0]].Vertexes[0]
    App.Console.PrintMessage("X1             : "+str(a.Point.x)+"\n")     # coordinate XYZ first point
    App.Console.PrintMessage("Y1             : "+str(a.Point.y)+"\n")     #
    App.Console.PrintMessage("Z1             : "+str(a.Point.z)+"\n")     #
    try:
        a = sel[0].Shape.Edges[j[0]].Vertexes[1]
        App.Console.PrintMessage("X2             : "+str(a.Point.x)+"\n") # coordinate XYZ second point
        App.Console.PrintMessage("Y2             : "+str(a.Point.y)+"\n") #
        App.Console.PrintMessage("Z2             : "+str(a.Point.z)+"\n") #
    except:
        App.Console.PrintMessage("Oups"+"\n")    
App.Console.PrintMessage("\n")    
##################################################################################

# give the sub element name, length, coordinates, BoundBox, BoundBox.Center, Area of the SubObjects selected
try:
    SubElement = FreeCADGui.Selection.getSelectionEx()                                        # sub element name with getSelectionEx()
    subElementName = Gui.Selection.getSelectionEx()[0].SubElementNames[0]                     # sub element name with getSelectionEx()
    App.Console.PrintMessage("subElementName : "+str(subElementName)+"\n")
    
    subObjectLength = Gui.Selection.getSelectionEx()[0].SubObjects[0].Length                  # sub element Length
    App.Console.PrintMessage("subObjectLength: "+str(subObjectLength)+"\n\n")
    
    subObjectX1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.x         # sub element coordinate X1
    App.Console.PrintMessage("subObject_X1   : "+str(subObjectX1)+"\n")
    subObjectY1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.y         # sub element coordinate Y1
    App.Console.PrintMessage("subObject_Y1   : "+str(subObjectY1)+"\n")
    subObjectZ1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.z         # sub element coordinate Z1
    App.Console.PrintMessage("subObject_Z1   : "+str(subObjectZ1)+"\n\n")

    try:
        subObjectX2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.x     # sub element coordinate X2
        App.Console.PrintMessage("subObject_X2   : "+str(subObjectX2)+"\n")
        subObjectY2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.y     # sub element coordinate Y2
        App.Console.PrintMessage("subObject_Y2   : "+str(subObjectY2)+"\n")
        subObjectZ2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.z     # sub element coordinate Z2
        App.Console.PrintMessage("subObject_Z2   : "+str(subObjectZ2)+"\n\n")
    except:
        App.Console.PrintMessage("Oups"+"\n\n")            

    subObjectBoundBox = Gui.Selection.getSelectionEx()[0].SubObjects[0].BoundBox              # sub element BoundBox coordinates
    App.Console.PrintMessage("subObjectBBox  : "+str(subObjectBoundBox)+"\n")
    
    subObjectBoundBoxCenter = Gui.Selection.getSelectionEx()[0].SubObjects[0].BoundBox.Center # sub element BoundBoxCenter
    App.Console.PrintMessage("subObjectBBoxCe: "+str(subObjectBoundBoxCenter)+"\n")
    
    surfaceFace = Gui.Selection.getSelectionEx()[0].SubObjects[0].Area                        # Area of the face selected
    App.Console.PrintMessage("surfaceFace    : "+str(surfaceFace)+"\n\n")
except:
    App.Console.PrintMessage("Oups"+"\n\n")            
##################################################################################

# give the area of the object
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
surface = sel[0].Shape.Area                                               # Area object complete
App.Console.PrintMessage("surfaceObjet   : "+str(surface)+"\n\n")
##################################################################################

# give the Center Of Mass and coordinates of the object
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
CenterOfMass = sel[0].Shape.CenterOfMass                                  # Center of Mass of the object
App.Console.PrintMessage("CenterOfMass   : "+str(CenterOfMass)+"\n")
App.Console.PrintMessage("CenterOfMassX  : "+str(CenterOfMass[0])+"\n")   # coordinates [0]=X [1]=Y [2]=Z
App.Console.PrintMessage("CenterOfMassY  : "+str(CenterOfMass[1])+"\n")   # or CenterOfMass.x, CenterOfMass.y, CenterOfMass.z
App.Console.PrintMessage("CenterOfMassZ  : "+str(CenterOfMass[2])+"\n\n")
##################################################################################

# list the all faces of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
for j in enumerate(sel[0].Shape.Faces):                                   # List alles faces of the object
    App.Console.PrintMessage("Face           : "+str("Face%d" % (j[0]+1))+"\n")
App.Console.PrintMessage("\n\n")
##################################################################################

# give the volume of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
volume_ = sel[0].Shape.Volume                                             # Volume of the object
App.Console.PrintMessage("volume_        : "+str(volume_)+"\n\n")
##################################################################################
 
# give the BoundBox of the oject selected all type
objs = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
if len(objs) >= 1:                                                         # serch the object type
    if hasattr(objs[0], "Shape"):
        s = objs[0].Shape
    elif hasattr(objs[0], "Mesh"):      # upgrade with wmayer thanks #http://forum.freecadweb.org/viewtopic.php?f=13&t=22331
        s = objs[0].Mesh
    elif hasattr(objs[0], "Points"):
        s = objs[0].Points

boundBox_= s.BoundBox                                                     # BoundBox of the object
App.Console.PrintMessage("boundBox_      : "+str(boundBox_)+"\n")         # 
 
boundBoxLX   = boundBox_.XLength                                          # Length x boundBox rectangle
boundBoxLY   = boundBox_.YLength                                          # Length y boundBox rectangle
boundBoxLZ   = boundBox_.ZLength                                          # Length z boundBox rectangle

boundBoxXMin = boundBox_.XMin                                             # coordonate XMin
boundBoxYMin = boundBox_.YMin                                             # coordonate YMin
boundBoxZMin = boundBox_.ZMin                                             # coordonate ZMin
boundBoxXMax = boundBox_.XMax                                             # coordonate XMax
boundBoxYMax = boundBox_.YMax                                             # coordonate YMax
boundBoxZMax = boundBox_.ZMax                                             # coordonate ZMax

boundBoxDiag= boundBox_.DiagonalLength                                    # Diagonal Length boundBox rectangle
boundBoxCenter = boundBox_.Center                                         # BoundBox Center
boundBoxCenterOfGravity = boundBox_.CenterOfGravity                       # BoundBox CenterOfGravity

App.Console.PrintMessage("boundBoxLX     : "+str(boundBoxLX)+"\n")
App.Console.PrintMessage("boundBoxLY     : "+str(boundBoxLY)+"\n")
App.Console.PrintMessage("boundBoxLZ     : "+str(boundBoxLZ)+"\n\n")

App.Console.PrintMessage("boundBoxXMin   : "+str(boundBoxXMin)+"\n")
App.Console.PrintMessage("boundBoxYMin   : "+str(boundBoxYMin)+"\n")
App.Console.PrintMessage("boundBoxZMin   : "+str(boundBoxZMin)+"\n")
App.Console.PrintMessage("boundBoxXMax   : "+str(boundBoxXMax)+"\n")
App.Console.PrintMessage("boundBoxYMax   : "+str(boundBoxYMax)+"\n")
App.Console.PrintMessage("boundBoxZMax   : "+str(boundBoxZMax)+"\n\n")

App.Console.PrintMessage("boundBoxDiag   : "+str(boundBoxDiag)+"\n")
App.Console.PrintMessage("boundBoxCenter : "+str(boundBoxCenter)+"\n")

App.Console.PrintMessage("boundBox Center of Gravity : "+str(boundBoxCenterOfGravity )+"\n\n")

##################################################################################

# give the complete placement of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement                                               # Placement Vector XYZ and Yaw-Pitch-Roll
App.Console.PrintMessage("Placement      : "+str(pl)+"\n")
##################################################################################

# give the placement Base (xyz) of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Base                                          # Placement Vector XYZ
App.Console.PrintMessage("PlacementBase  : "+str(pl)+"\n\n")
##################################################################################
 
# give the placement Base (xyz) of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
oripl_X = sel[0].Placement.Base[0]                                        # decode Placement X
oripl_Y = sel[0].Placement.Base[1]                                        # decode Placement Y
oripl_Z = sel[0].Placement.Base[2]                                        # decode Placement Z

# same 
#oripl_X = sel[0].Placement.Base.x                                        # decode Placement X
#oripl_Y = sel[0].Placement.Base.y                                        # decode Placement Y
#oripl_Z = sel[0].Placement.Base.z                                        # decode Placement Z
 
App.Console.PrintMessage("oripl_X        : "+str(oripl_X)+"\n")
App.Console.PrintMessage("oripl_Y        : "+str(oripl_Y)+"\n")
App.Console.PrintMessage("oripl_Z        : "+str(oripl_Z)+"\n\n")
##################################################################################

# give the placement rotation of the object selected (x, y, z, angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
rotation = sel[0].Placement.Rotation                                      # decode Placement Rotation
App.Console.PrintMessage("rotation              : "+str(rotation)+"\n\n")
##################################################################################

# give the placement rotation of the object selected (x, y, z, angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Rotation                                      # decode Placement Rotation other method
App.Console.PrintMessage("Placement Rot         : "+str(pl)+"\n\n")
##################################################################################

# give the rotation of the object selected (angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Rotation.Angle                                # decode Placement Rotation Angle
App.Console.PrintMessage("Placement Rot Angle   : "+str(pl)+"\n\n")
##################################################################################

# give the rotation.Q of the object selected (angle rotation in Radian) for convert: math.degrees(angleInRadian)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
Rot   = sel[0].Placement.Rotation.Q                                       # Placement Rotation Q
App.Console.PrintMessage("Rot           : "+str(Rot)+ "\n")
 
Rot_0 = sel[0].Placement.Rotation.Q[0]                                    # decode Placement Rotation Q
App.Console.PrintMessage("Rot_0         : "+str(Rot_0)+ " rad ,  "+str(180 * Rot_0 / 3.1416)+" deg "+"\n") # or math.degrees(angle)
 
Rot_1 = sel[0].Placement.Rotation.Q[1]                                    # decode Placement Rotation 1
App.Console.PrintMessage("Rot_1         : "+str(Rot_1)+ " rad ,  "+str(180 * Rot_1 / 3.1416)+" deg "+"\n") # or math.degrees(angle)
 
Rot_2 = sel[0].Placement.Rotation.Q[2]                                    # decode Placement Rotation 2
App.Console.PrintMessage("Rot_2         : "+str(Rot_2)+ " rad ,  "+str(180 * Rot_2 / 3.1416)+" deg "+"\n") # or math.degrees(angle)

Rot_3 = sel[0].Placement.Rotation.Q[3]                                    # decode Placement Rotation 3
App.Console.PrintMessage("Rot_3         : "+str(Rot_3)+"\n\n")

Rot_Axis = sel[0].Placement.Rotation.Axis                                 # Placement Rotation .Axis
App.Console.PrintMessage("Rot_Axis      : "+str(Rot_Axis)+ "\n")
 
Rot_Angle = sel[0].Placement.Rotation.Angle                               # Placement Rotation .Angle
App.Console.PrintMessage("Rot_Angle     : "+str(Rot_Angle)+ "\n\n")
##################################################################################

# give the rotation of the object selected toEuler (angle rotation in degrees)
sel = FreeCADGui.Selection.getSelection()                             # select object with getSelection()
angle   = sel[0].Shape.Placement.Rotation.toEuler()                   # angle Euler
App.Console.PrintMessage("Angle          : "+str(angle)+"\n")
Yaw   = sel[0].Shape.Placement.Rotation.toEuler()[0]                  # decode angle Euler Yaw (Z) lacet (alpha)
App.Console.PrintMessage("Yaw            : "+str(Yaw)+"\n")
Pitch = sel[0].Shape.Placement.Rotation.toEuler()[1]                  # decode angle Euler Pitch (Y) tangage (beta)
App.Console.PrintMessage("Pitch          : "+str(Pitch)+"\n")
Roll  = sel[0].Shape.Placement.Rotation.toEuler()[2]                  # decode angle Euler Roll (X) roulis (gamma)
App.Console.PrintMessage("Roll           : "+str(Roll)+"\n\n")

rot = App.Rotation()
rot.setYawPitchRoll(45,45,0)
print("Angle: ", rot.Angle)
print("Axis: ", rot.Axis)
print("RawAxis: ", rot.RawAxis)
print("YawPitchRoll: ", rot.getYawPitchRoll())
print("Rotation: ", rot)
print("Quaternion: ", rot.Q)

##################################################################################

# find Midpoint of the selected line
import Draft, DraftGeomUtils
sel = FreeCADGui.Selection.getSelection()
vecteur = DraftGeomUtils.findMidpoint(sel[0].Shape.Edges[0])              # find Midpoint
App.Console.PrintMessage(vecteur)
Draft.makePoint(vecteur)
##################################################################################

Inicio

Búsqueda manual de un elemento con etiqueta

# Extract the coordinate X,Y,Z and Angle giving the label (here "Cylindre")
App.Console.PrintMessage("Base.x       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.x)+"\n")
App.Console.PrintMessage("Base.y       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.y)+"\n")
App.Console.PrintMessage("Base.z       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.z)+"\n")
App.Console.PrintMessage("Base.Angle   : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Rotation.Angle)+"\n\n")
##################################################################################

Note: Usually the angles are given in Radian. To convert them:

  1. angle in Degrees to Radians :
    • Angle in radian = pi * (angle in degree) / 180
    • Angle in radian = math.radians(angle in degree)
  2. angle in Radians to Degrees :
    • Angle in degree = 180 * (angle in radian) / pi
    • Angle in degree = math.degrees(angle in radian)

Inicio

Coordenadas cartesianas

This code displays the Cartesian coordinates of the selected item.

Change the value of "numberOfPoints" if you want a different number of points (precision)

numberOfPoints = 100                                                         # Decomposition number (or precision you can change)
selectedEdge = FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy() # select one element
points  = selectedEdge.discretize(numberOfPoints)                            # discretize the element
i=0
for p in points:                                                             # list and display the coordinates
    i+=1
    print( i, " X", p.x, " Y", p.y, " Z", p.z)

Other method display on "Int" and "Float"

import Part
from FreeCAD import Base

c=Part.makeCylinder(2,10)        # create the circle
Part.show(c)                     # display the shape

# slice accepts two arguments:
#+ the normal of the cross section plane
#+ the distance from the origin to the cross section plane. Here you have to find a value so that the plane intersects your object
s=c.slice(Base.Vector(0,1,0),0)  # 

# here the result is a single wire
# depending on the source object this can be several wires
s=s[0]

# if you only need the vertexes of the shape you can use
v=[]
for i in s.Vertexes:
    v.append(i.Point)

# but you can also sub-sample the section to have a certain number of points (int) ...
p1=s.discretize(20)
ii=0
for i in p1:
    ii+=1
    print( i )                                             # Vector()
    print( ii, ": X:", i.x, " Y:", i.y, " Z:", i.z )       # Vector decode
Draft.makeWire(p1,closed=False,face=False,support=None)    # to see the difference accuracy (20)

## uncomment to use
#import Draft
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # first transform the DWire in Wire         "downgrade"
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # second split the Wire in single objects   "downgrade"
#
##Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"


# ... or define a sampling distance (float)
p2=s.discretize(0.5)
ii=0
for i in p2:
    ii+=1
    print( i )                                             # Vector()
    print( ii, ": X:", i.x, " Y:", i.y, " Z:", i.z )       # Vector decode 
Draft.makeWire(p2,closed=False,face=False,support=None)  # to see the difference accuracy (0.5)

## uncomment to use
#import Draft
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # first transform the DWire in Wire         "downgrade"
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # second split the Wire in single objects   "downgrade"
#
##Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"

Inicio

Seleccionar todos los objetos del documento

import FreeCAD
for obj in FreeCAD.ActiveDocument.Objects:
    print( obj.Name )                               # display the object Name
    objName = obj.Name
    obj = App.ActiveDocument.getObject(objName)
    Gui.Selection.addSelection(obj)                 # select the object

Inicio

Seleccionar un área de un objeto por Nombre objeto y Número área

# select one face of the object
import FreeCAD, Draft
App=FreeCAD
nameObject = "Box"                             # objet
faceSelect = "Face3"                           # face to selection
loch=App.ActiveDocument.getObject(nameObject)  # objet
Gui.Selection.clearSelection()                 # clear all selection
Gui.Selection.addSelection(loch,faceSelect)    # select the face specified
s = Gui.Selection.getSelectionEx()
#Draft.makeFacebinder(s)                       #

Inicio

Obtener el vector normal de un área de un objeto por Nombre objeto y número área (r.Q)

## normal of a face by giving the number of the face and the name of the object (rotation Q with yL, uV) = (App.Vector (x, y, z), angle))
## normal d'une face en donnant le numero de la face et le nom de l'objet (rotation Q avec yL, uV) = (App.Vector(x, y, z),angle))
from FreeCAD import Vector

numero_Face = 2      # number of the face searched (begin 0, 1, 2, 3 .....)
nomObjet    = "Box"  # object name
yL = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].CenterOfMass
uv = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].Surface.parameter(yL)

nv = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].normalAt(uv[0], uv[1])
direction = yL.sub(nv + yL)
print("Direction  : ",direction)

r = App.Rotation(App.Vector(0,0,1),direction)
print("Rotation   : ", r)
print("Rotation Q : ", r.Q)

Inicio

Obtener el vector normal de un área de un objeto por Nombre del objeto y número de área

numero_Face = 2       # number of the face searched (begin 0, 1, 2, 3 .....)
nomObjet    = "Box"   # object name
normal      = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].normalAt(0,0)
print("Face"+str(numero_Face), " : ", normal)

Inicio

Obtener el vector normal de un objeto seleccionado y el número de área

## normal of a face by giving the number of the face of the selected object
selectionObjects = FreeCADGui.Selection.getSelection()     
numero_Face = 3    # numero de la face recherchee
normal = selectionObjects[0].Shape.Faces[numero_Face].normalAt(0,0)
print(normal)
# selectionne la face numerotee
Gui.Selection.clearSelection()
Gui.Selection.addSelection(selectionObjects[0],"Face"+str(numero_Face))

Inicio

Obtener el vector normal en la superficie

This example show how to find normal vector on the surface by find the u,v parameters of one point on the surface and use u,v parameters to find normal vector

def normal(self):
   ss=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy()#SubObjects[0] is the edge list
   points  = ss.discretize(3.0)#points on the surface edge, 
             #this example just use points on the edge for example. 
             #However point is not necessary on the edge, it can be anywhere on the surface. 
   face=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[1]
   for pp in points:
      pt=FreeCAD.Base.Vector(pp.x,pp.y,pp.z)#a point on the surface edge
      uv=face.Surface.parameter(pt)# find the surface u,v parameter of a point on the surface edge
      u=uv[0]
      v=uv[1]
      normal=face.normalAt(u,v)#use u,v to find normal vector
      print( normal)
      line=Part.makeLine((pp.x,pp.y,pp.z), (normal.x,normal.y,normal.z))
      Part.show(line)

Inicio

Get the normal vector of the face and create a line at the point mouse clicked

import PySide2
import Draft, Part, FreeCAD, FreeCADGui
import FreeCADGui as Gui
from FreeCAD import Base

FreeCAD.ActiveDocument.openTransaction("Tyty")    # memorise les actions (avec annuler restore)
selectedFace = FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0]
pointClick = FreeCADGui.Selection.getSelectionEx()[0].PickedPoints[0]

########## section direction
plr = FreeCAD.Placement()
yL = pointClick
uv = selectedFace.Surface.parameter(yL)
nv = direction = selectedFace.normalAt(uv[0], uv[1])
r = App.Rotation(App.Vector(0,0,1),nv)
plr.Rotation.Q = r.Q
plr.Base = pointClick
########## section direction

line = Draft.make_wire([App.Vector(0.0,0.0,0.0), App.Vector(0.0,0.0,20.0)] )    # create line
line.Placement=plr
FreeCAD.ActiveDocument.recompute()
print( "Direction (radian) : ",direction )    # direction in radian

Inicio

Obtener el vector normal de una superficie desde un archivo STL

def getNormal(cb):
    if cb.getEvent().getState() == coin.SoButtonEvent.UP:
        pp = cb.getPickedPoint()
        if pp:
            vec = pp.getNormal().getValue()
            index = coin.cast(pp.getDetail(), "SoFaceDetail").getFaceIndex()
            print("Normal: {}, Face index: {}".format(str(vec), index))

from pivy import coin
meth=Gui.ActiveDocument.ActiveView.addEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), getNormal)

you are done then run for quit:

Gui.ActiveDocument.ActiveView.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), meth)

Inicio

Crear un objeto a la posición de la Cámara

# create one object of the position to camera with "getCameraOrientation()"
# the object is still facing the screen
import Draft

plan = FreeCADGui.ActiveDocument.ActiveView.getCameraOrientation()
plan = str(plan)
###### extract data
a    = ""
for i in plan:
    if i in ("0123456789e.- "):
        a+=i
a = a.strip(" ")
a = a.split(" ")
####### extract data

#print( a)
#print( a[0])
#print( a[1])
#print( a[2])
#print( a[3])

xP = float(a[0])
yP = float(a[1])
zP = float(a[2])
qP = float(a[3])

pl = FreeCAD.Placement()
pl.Rotation.Q = (xP,yP,zP,qP)         # rotation of object
pl.Base = FreeCAD.Vector(0.0,0.0,0.0) # here coordinates XYZ of Object
rec = Draft.makeRectangle(length=10.0,height=10.0,placement=pl,face=False,support=None) # create rectangle
#rec = Draft.makeCircle(radius=5,placement=pl,face=False,support=None)                   # create circle
print( rec.Name)

here same code simplified

import Draft
pl = FreeCAD.Placement()
pl.Rotation = FreeCADGui.ActiveDocument.ActiveView.getCameraOrientation()
pl.Base = FreeCAD.Vector(0.0,0.0,0.0)
rec = Draft.makeRectangle(length=10.0,height=10.0,placement=pl,face=False,support=None)

Inicio

Leer y escribir una expresión

import Draft
doc = FreeCAD.ActiveDocument

pl=FreeCAD.Placement()
pl.Rotation.Q=(0.0,-0.0,-0.0,1.0)
pl.Base=FreeCAD.Vector(0.0,0.0,0.0)
obj = Draft.makeCircle(radius=1.0,placement=pl,face=False,support=None)    # create circle

print( obj.PropertiesList )                                                  # properties disponible in the obj

doc.getObject(obj.Name).setExpression('Radius', u'2mm')                    # modify the radius
doc.getObject(obj.Name).setExpression('Placement.Base.x', u'10mm')         # modify the placement 
doc.getObject(obj.Name).setExpression('FirstAngle', u'90')                 # modify the first angle
doc.recompute()

expressions = obj.ExpressionEngine                                         # read the expression list
print( expressions)

for i in expressions:                                                      # list and separate the data expression
    print( i[0]," = ",i[1])

Inicio

Crear un boceto en una superficie en DiseñoPieza

This snippet can be useful, if you want to create a sketch on a surface in PartDesign from inside a macro. Note, that body might be None, if no active body is selected and that the Selection might be empty.

body = Gui.ActiveDocument.ActiveView.getActiveObject('pdbody')
first_selection = Gui.Selection.getSelectionEx()[0]

feature = first_selection.Object
face_name = first_selection.SubElementNames[0]

sketch = App.ActiveDocument.addObject('Sketcher::SketchObject','MySketch')
body.addObject(sketch)
sketch.MapMode = 'FlatFace'
sketch.Support = (feature, face_name)

App.ActiveDocument.recompute()

Inicio

Cómo simular un clic del ratón en una coordenada determinada

The position is relative to the GL widget. See forum thread.

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets

mw = Gui.getMainWindow()
gl = mw.findChild(QtWidgets.QOpenGLWidget)
me = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(800,300), QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier)

app = QtWidgets.QApplication.instance()
app.sendEvent(gl, me)

If you have a 3d point and want to get the 2d point on the opengl widget then use this:

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets
from FreeCAD import Base

x, y, z, = 10,10,10
v = Gui.ActiveDocument.ActiveView
point3d = Base.Vector(x, y, z)
point2d = v.getPointOnScreen(point3d)
size = v.getSize()
coordX = point2d[0]
coordY = size[1] - point2d[1]

me = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(coordX,coordY), QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier)

Inicio

How to create a face with holes using Python API

This snippet demonstrates how to create a face with internal holes through the Python API. See forum thread.

import FreeCAD, Part

# Create poles that will define the Face
pts = [(-2, 2, 0),
       (0, 2, 1),
       (2, 2, 0),
       (2, -2, 0),
       (0, -2, 1),
       (-2, -2, 0)]

bs = Part.BSplineCurve()
bs.buildFromPoles(pts, True)  # True makes this periodic/closed

# Make the Face from the curve
myFace = Part.makeFilledFace([bs.toShape()])

# Create geometry for holes that will be cut in the surface
hole0 = Part.Geom2d.Circle2d(FreeCAD.Base.Vector2d(0,0), 1.0)
hole1 = Part.Geom2d.Circle2d(FreeCAD.Base.Vector2d(0,1.5), 0.1)

edge0 = hole0.toShape(myFace)
edge1 = hole1.toShape(myFace)
wireb = Part.Wire(bs.toShape())
wire0 = Part.Wire(edge0)
wire1 = Part.Wire(edge1)

# Cut holes in the face
myFace.cutHoles([wire0])
myFace.validate()  # This is required
myFace.cutHoles([wire1])
myFace.validate()

Part.show(myFace)

Inicio

Close and restart FreeCAD

import PySide2 
from PySide2 import QtWidgets, QtCore, QtGui

def restart_freecad():
    """Shuts down and restarts FreeCAD"""

    args = QtWidgets.QApplication.arguments()[1:]
    if FreeCADGui.getMainWindow().close():
        QtCore.QProcess.startDetached(
            QtWidgets.QApplication.applicationFilePath(), args
        )

Inicio

Coin3D

See Coin3d snippets

Inicio

Relacionados

Inicio


Introduction

Esta página muestra cómo se puede crear funcionalidades avanzadas con Python. En este ejercicio, construiremos una nueva herramienta que dibuja una línea. Esta herramienta puede ser vinculada a un comando de FreeCAD, y ese comando se puede llamar desde cualquier elemento de la interfaz, tal como un elemento de menú o un botón de una barra de herramientas.

El archivo de guión principal

En primer lugar vamos a escribir un archivo de guión que contenga toda nuestra funcionalidad. Después, vamos a guardar esto en un archivo, e importarlo en FreeCAD, así todas las clases y funciones que escribas estarán disponibles para FreeCAD. De modo que inicia tu editor de texto favorito y escribe las siguientes líneas:

First we will write a script containing all our functionality. Then we will save this in a file and import it in FreeCAD to make all its classes and functions available. Launch your favorite code editor and type the following lines:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def __init__(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Inicio

Explicación detallada

import Part, FreeCADGui
from pivy.coin import *

En Python, cuando desees utilizar las funciones de otro módulo, tienes que importarlo. En nuestro caso, vamos a necesitar las funciones del Módulo de Pieza, para la creación de la línea, y del módulo GUI (FreeCADGui), para acceder a la vista 3D. También necesitamos el contenido completo de la biblioteca de Coin, para que podamos utilizar directamente todos los objetos Coin, como SoMouseButtonEvent, etc ..

class line:

Aquí definimos nuestra clase principal. ¿Por qué utilizar una clase y no una función? La razón es que necesitamos que nuestra herramienta se mantenga "viva" mientras esperamos a que el usuario haga clic en la pantalla. Una función termina cuando su tarea se ha hecho, pero un objeto (una clase se define como un objeto) se mantiene vivo hasta que se destruye.

"""This class will create a line after the user clicked 2 points on the screen"""

En Python, cada clase o función puede tener una cadena de descripción. Esto es particularmente útil en FreeCAD, porque cuando vas a llamar a esa clase en el intérprete, la cadena de descripción se mostrará como una nota.

def __init__(self):

Las clases en Python siempre pueden contener una función __init__, que se ejecuta cuando la clase es llamada para crear un objeto. Por lo tanto, vamos a poner aquí todo lo que queremos que ocurra cuando nuestra herramienta línea comienza.

self.view = FreeCADGui.ActiveDocument.ActiveView

En una clase, por lo general querrás incluir self. antes de un nombre de variable, para que sea fácilmente accesible por todas las funciones dentro y fuera de esa clase. Aquí, vamos a utilizar self.view para acceder y manipular la vista 3D activa.

self.stack = []

Aquí creamos una lista vacía que contendrá los puntos 3D enviados por la función getpoint.

self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

Aquí viene la parte importante: Dado que en realidad se trata de una escena Coin3d, FreeCAD utiliza el mecanismo de devolución de llamada de Coin, que permite que una función sea llamada cada vez que sucede un determinado evento de escena. En nuestro caso, estamos creando una devolución de llamada para eventos SoMouseButtonEvent, y lo conduciremos a la función getpoint. Ahora, cada vez que un botón del ratón sea pulsado o soltado, la función getpoint será ejecutada.

Ten en cuenta que también hay una alternativa a addEventCallbackPivy(), llamada addEventCallback(), que dispensa del uso de pivy. Pero como pivy es una forma muy eficaz y natural para acceder a cualquier parte de la escena de Coin, es mucho mejor usarlo tanto como se pueda!

Inicio

def getpoint(self, event_cb):

Ahora definimos la función getpoint, que se ejecutará cuando el botón del ratón se pulsa en una vista 3D. Esta función recibe un argumento, que llamaremos event_cb. A partir de este evento de devolución de llamada podemos tener acceso al objeto de evento, que contiene varias piezas de información (más información aquí).

if event.getState() == SoMouseButtonEvent.DOWN:

La función getpoint se llamará cuando un botón del ratón sea pulsado o soltado. Pero queremos escoger un punto 3D sólo cuando se presiona (de lo contrario obtendríamos dos puntos 3D muy cerca uno del otro). Por lo tanto, debes comprobar eso aquí.

pos = event.getPosition()

Aquí obtenemos las coordenadas de pantalla del cursor del ratón

point = self.view.getPoint(pos[0], pos[1])

Esta función nos da un vector de FreeCAD (x,y,z) que contiene el punto 3D que se encuentra en el plano focal, justo debajo del cursor de nuestro ratón. Si estás en vista de cámara, imagina un rayo proveniente de la cámara, pasando por el cursor del ratón, y alcanzando el plano focal. Ahí está nuestro punto 3D. Si estamos en una vista ortogonal, el rayo es paralelo a la dirección de la vista.

self.stack.append(point)

Añadimos nuestro nuevo punto a la pila

if len(self.stack) == 2:

¿Tenemos ya suficientes puntos? si es así, entonces vamos a trazar la línea!

l = Part.LineSegment(self.stack[0], self.stack[1])

Aquí se utiliza la función line() del Módulo de Pieza que crea una línea a partir de dos vectores de FreeCAD. Todo lo que creamos y modificamos dentro del módulo de Pieza, se queda en el módulo de Pieza . Así, hasta ahora, hemos creado un elemento de línea. No está ligado a un objeto de nuestro documento activo, por lo que no aparece nada en la pantalla.

shape = l.toShape()

El documento de FreeCAD sólo puede aceptar formas desde el módulo de Pieza. Las formas son el tipo más genérico del módulo de Pieza. Por lo tanto, debemos convertir nuestra línea en una forma antes de añadirla al documento.

Part.show(shape)

El módulo de Pieza tiene una función, show(), que es muy útil ya que crea un nuevo objeto en el documento y le conecta a una forma. También podrías haber creado primero un nuevo objeto en el documento, y a continuación vincularle a la forma manualmente.

self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Como ya hemos terminado con nuestra línea, vamos a quitar el mecanismo de devolución de llamada, que consume unos preciosos ciclos de CPU.

Inicio

Pruebas y Uso del archivo de guión

Ahora, vamos a guardar nuestro archivo de guión en un lugar donde el intérprete de Python de FreeCAD lo encuentre. Cuando importa los módulos, el intérprete mirará en los siguientes lugares: las rutas de instalación de Python, el directorio bin de FreeCAD, y todos los directorios de módulos FreeCAD. Por lo tanto, la mejor solución es crear un nuevo directorio en una de los FreeCAD Mod directories, y salvar nuestro script en él. Por ejemplo, vamos a hacer un directorio "MyScripts", y salvamos nuestro script como "exercise.py".

Now let's save our script in a folder where the FreeCAD Python interpreter can find it. When importing modules, the interpreter will look in the following places: the Python installation paths, the FreeCAD bin folder, and all FreeCAD Mod (module) folders. So the best solution is to create a new folder in one of the Mod folders. Let's create a MyScripts folder there and save our script in it as exercise.py.

Ahora, todo está listo, vamos a empezar FreeCAD, cree un nuevo documento, y, en el intérprete de Python, ejecute:

import exercise

Si no aparece ningún mensaje de error, eso significa que nuestro script de ejercicio se ha cargado. Ahora puede comprobar su contenido con:

dir(exercise)

El comando dir() es un comando integrado de Python que muestra el contenido de un módulo. Podemos ver que nuestra clase line() está ahí, esperandonos. Ahora vamos a probarlo:

'line' in dir(exercise)

Now let's test it:

exercise.line()

A continuación, haz clic dos veces en la vista 3D, y .... ¡bingo!, ¡aquí está nuestra línea! Para hacerlo de nuevo, simplemente escribe exercise.line() otra vez, y otra vez, y otra vez ... Estas contento, ¿no?

Inicio

Incluyendo el archivo de guión en la interfaz de FreeCAD

Ahora, para que nuestra nueva herramienta línea sea realmente buena, debe tener un botón en la interfaz, para que no sea necesario escribir todas estas cosas cada vez. La forma más fácil es transformar nuestro nuevo directorio MyScripts en un completo entorno de FreeCAD. Es fácil, todo lo que se necesita es poner un archivo llamado InitGui.py dentro de tu directorio MyScripts. El InitGui.py contendrá las instrucciones para crear un nuevo entorno (workbench), y le añadimos nuestra nueva herramienta. Además, también habrá que transformar un poco nuestro código del ejercicio, para que la herramienta line() sea reconocida como un comando oficial de FreeCAD. Comencemos por crear un archivo InitGui.py, y escribir el siguiente código en él:

For our new line tool to be really useful, and to avoid having to type all that stuff, it should have a button in the interface. One way to do this is to transform our new MyScripts folder into a full FreeCAD workbench. This is easy, all that is needed is to put a file called InitGui.py inside the MyScripts folder. InitGui.py will contain the instructions to create a new workbench, and add our new tool to it. Besides that we will also need to change our exercise code a bit, so the line() tool is recognized as an official FreeCAD command. Let's start by creating an InitGui.py file, and writing the following code in it:

class MyWorkbench (Workbench):

    MenuText = "MyScripts"

    def Initialize(self):
        import exercise
        commandslist = ["line"]
        self.appendToolbar("My Scripts", commandslist)

Gui.addWorkbench(MyWorkbench())

A estas alturas, ya debes entender el archivo de guión anterior por ti mismo, supongo: Creamos una nueva clase que llamamos MyWorkbench, le damos un título (MenuText), y definimos una función initialize() que se ejecutará cuando el entorno se cargue en FreeCAD. En esa función, se carga el contenido de nuestro archivo del ejercicio, y los comandos de FreeCAD que se encuentran dentro se anexan en una lista de comandos. A continuación, hacemos una barra de herramientas llamada "Mi Scripts" y le asignamos nuestra lista de comandos. Finalmente, por supuesto, sólo tenemos una herramienta, por lo que nuestra lista de comandos contiene un solo elemento. Ahora, una vez que nuestro entorno está listo, lo añadimos a la interfaz principal.

Pero esto aún no funciona, porque un comando de FreeCAD debe estar formateado de una determinada manera para poder funcionar. Así que tendremos que transformar un poco nuestra herramienta line(). Nuestro nuevo archivo de guión exercise.py tendrá después este aspecto:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def Activated(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

    def GetResources(self):
        return {'Pixmap': 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'}

FreeCADGui.addCommand('line', line())

Lo que hicimos aquí es transformar nuestra función __init__() en una función Activated(), porque cuando se ejecutan comandos de FreeCAD, automáticamente se ejecuta la función Activated(). También hemos añadido una función GetResources(), que informa a FreeCAD de donde puede encontrar el icono de la herramienta, y cual será el nombre y la descripción de nuestra herramienta. Cualquier imagen jpg, png o svg funcionará como un icono. Puede ser de cualquier tamaño, pero lo mejor es utilizar un tamaño que esté cerca del aspecto final, como 16x16, 24x24 o 32x32. A continuación, añadimos la clase line() como un comando oficial de FreeCAD con el método addCommand().

Eso es todo, ahora sólo hay que reiniciar FreeCAD y tendremos un agradable entorno nuevo con una nueva herramienta line() de nuestra marca!

Inicio

¿Quieres más?

Si te gustó este ejercicio, ¿por qué no tratar de mejorar esta pequeña herramienta? Hay muchas cosas que se pueden hacer, como por ejemplo:

  • Agregar asistencia para los usuarios: hasta ahora hemos hecho una herramienta muy burda, el usuario podría verse un poco perdido cuando la utiliza. Se podría añadir alguna información, diciéndole qué hacer a continuación. Por ejemplo, podrías mostrar mensajes en la consola de FreeCAD. ¡Echa un vistazo en el módulo de FreeCAD.Console
  • Añadir la posibilidad de teclear de forma manual las coordenadas de los puntos 3D. Mira la función input() de Python, por ejemplo
  • Añadir la posibilidad de incluir más de 2 puntos
  • Añadir eventos para otras cosas: Ahora sólo comprobamos eventos de botón del ratón, ¿que tal si también hace algo cuando el ratón se mueva, como mostrar las coordenadas actuales?
  • Dar un nombre al objeto creado

No dudes en escribir tus preguntas o ideas en la forum!

Don't hesitate to ask questions or share ideas on the forum!

Inicio


Introduction

En esta página vamos a mostrar cómo crear un simple letrero de diálogo con Qt Designer, la herramienta oficial de Qt para el diseño de interfaces, después lo convertiremos en código de Python, para luego utilizarlo en FreeCAD. Vamos a suponer en el ejemplo que ya sabes cómo editar y ejecutar archivos de guión de Python, y que puedes hacer cosas simples en una ventana de terminal, como navegar, etc. También debes tener, por supuesto, PyQt instalado.

In this example, the entire interface is defined in Python. Although this is possible for small interfaces, for larger interfaces the recommendation is to load the created .ui files directly into the program.

Two general methods to create interfaces, by including the interface in the Python file, or by using .ui files.

En las aplicaciones de CAD, el diseño de una buena interfaz de usuario (UI, User Interface) es muy importante. Casi todo lo que el usuario haga será a través de alguna parte de la interfaz: leyendo los letreros de diálogo, pulsando los botones, eligiendo entre iconos, etc. Así que es muy importante pensar cuidadosamente lo que quieres hacer, cómo deseas que el usuario se comporte, y cómo será el flujo de trabajo de tu acción.

In CAD applications, designing a good UI (User Interface) is very important. About everything the user will do will be through some piece of interface: reading dialog boxes, pressing buttons, choosing between icons, etc. So it is very important to think carefully to what you want to do, how you want the user to behave, and how will be the workflow of your action.

Hay un par de conceptos que debes saber a la hora de diseñar la interfaz:

  • Letreros de diálogo Modales/no modales: Un letrero de diálogo modal aparece delante de la pantalla, deteniendo la acción de la ventana principal, obligando al usuario a responder al cuadro de diálogo, mientras que un cuadro de diálogo no modal permite seguir trabajando en la ventana principal. En algunos casos la primera opción es mejor, pero en otros casos no.
  • Identificación de lo que es necesario y lo que es opcional: Asegúrate de que el usuario sabe lo que debe hacer. Etiqueta todo con la descripción adecuada, utiliza etiquetas de información sobre el uso de las herramientas, etc.
  • Separar los comandos de los parámetros: Esto se hace generalmente con botones y cuadros de texto. El usuario sabe que al hacer clic en un botón, se produce una acción mientras que al cambiar un valor dentro de un cuadro de texto va a cambiar un parámetro en alguna parte. Hoy en día, sin embargo, los usuarios suelen conocer bien lo que es un botón, lo que es un cuadro de texto, etc. El conjunto de herramientas de interfaz que está utilizando, Qt, es el conjunto de herramientas más avanzado, y no tendrás que preocuparte mucho de hacer las cosas claras, puesto que ya va a ser muy clara por sí misma.

Así que, ahora que tenemos bien definido lo que haremos, es el momento para abrir el diseñador de Qt Designer. Diseñemos un letrero de diálogo muy sencillo, como este:

Después podremos utilizar este letrero de diálogo en FreeCAD para producir un bonito plano rectangular. Puede que no veas muy útil hacer planos rectangulares, pero será fácil cambiarlo más adelante para hacer cosas más complejas. Cuando lo abras, el aspecto de Qt Designer es el siguiente:

Es muy sencillo de utilizar. En la barra de la izquierda tienes elementos que pueden ser arrastrados a tu widget. En el lado derecho tienes los paneles de propiedades mostrando todo tipo de propiedades editables de los elementos seleccionados. Comencemos ahora con la creación de un nuevo widget o complemento. Selecciona "letrero de diálogo sin botones", ya que no queremos el formato predeterminado de botones Ok/Cancelar. A continuación, arrastra sobre tu widget 3 etiquetas, una para el título, una para escribir "Altura" y otra para escribir "Ancho". Las etiquetas son textos sencillos que aparecen en tu widget, simplemente para informar al usuario. Si seleccionas una etiqueta, en la parte derecha aparecerán varias propiedades que puedes cambiar si lo deseas, como el estilo de fuente, altura, etc.

Ten en cuenta que he elegido aquí controles muy sencillos, pero Qt tiene muchas más opciones, por ejemplo, podría utilizar Spinboxes en lugar de LineEdits, etc. Echa un vistazo a lo que está disponible, seguramente tendrás otras ideas.

Eso es prácticamente todo lo que necesitamos hacer en Qt Designer. Una última cosa, sin embargo, vamos a cambiar el nombre de todos nuestros elementos con nombres más adecuados, de modo que sea más fácil identificarlos en nuestros archivos de guión:

Convertir nuestro diálogo a Python

Ahora, vamos a salvar nuestro widget en alguna parte. Se guardará como un archivo .ui, que fácilmente se convertirá en un archivo de guión de Python por medio de pyuic. En Windows, el programa pyuic se ve enriquecido con PyQt (por verificar), en linux es probable que tengas que instalarlo por separado desde tu gestor de paquetes (en sistemas basados en Debian, es parte del paquete de herramientas PyQt4-dev-tools). Para realizar la conversión, tendrás que abrir una ventana de terminal (o una ventana de símbolo de sistema en Windows), ve a donde guardaste el archivo .ui, y escribe:

pyuic mywidget.ui > mywidget.py

In Windows pyuic.py is located in "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" For conversion create a batch file called "compQt4.bat:

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" -x %1.ui > %1.py

In the DOS console type without extension

compQt4 myUiFile

In macOS, you can retrieve the appropriate version (the same that is used internally in FreeCAD 0.19) of QT and Pyside with these commands (pip required)

python3 -m pip install pyqt5
python3 -m pip install pySide2

This will install uic in the folder "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/uic", and Designer in "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/Designer.app". For convenience you can create a link of uic in /usr/local/bin to be able to call it simply with uic -g python ... instead of typing the whole path of the program, and a link to Designer to retrieve it in the mac's Applications folder with

sudo ln -s /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/uic /usr/local/bin
ln -s /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/Designer.app /Applications

Into Linux : to do

Since FreeCAD progressively moved away from PyQt after version 0.13, in favour of PySide (Choose your PySide install building PySide), to make the file based on PySide now you have to use:

pyside-uic mywidget.ui -o mywidget.py

In Windows uic.py are located in "C:\Python27\Lib\site-packages\PySide\scripts\uic.py" For create batch file "compSide.bat":

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PySide\scripts\uic.py" %1.ui > %1.py

In the DOS console type without extension

compSide myUiFile

Into Linux : to do

En algunos sistemas el programa se llama pyuic4 en lugar de pyuic. Esta operación simplemente convertirá el archivo .ui en un archivo de guión de Python. Si abrimos el archivo mywidget.py, su contenido es muy fácil de entender:

from PySide import QtCore, QtGui

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(187, 178)
        self.title = QtGui.QLabel(Dialog)
        self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))
        self.title.setObjectName("title")
        self.label_width = QtGui.QLabel(Dialog)
        ...

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

   def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))
        ...

Como verás, tiene una estructura muy simple: se crea una clase denominada Ui_Dialog, que almacena los elementos de interfaz de nuestro widget o complemento. Esa clase tiene dos métodos, uno para la configuración del widget, y otro para la traducción de su contenido, eso es parte del mecanismo general de Qt para la traducción de elementos de la interfaz. El método de configuración simplemente crea, uno a uno, los widgets tal como los has definido en Qt Designer, y establece sus opciones, como hayamos decidido con anterioridad. Despues, toda la interfaz se traduce, y por último, se conectan las ranuras (slots) (hablaremos de eso más adelante).

Ahora podemos crear un nuevo widget, y utilizar esta clase para crear su interfaz. Ya podemos ver nuestro widget en acción, poniendo nuestro archivo mywidget.py en un lugar donde FreeCAD lo encuentre (en el directorio bin de FreeCAD, o en cualquiera de los subdirectorios Mod), y, en el intérprete de Python FreeCAD, ejecutamos:

from PySide import QtGui
import mywidget
d = QtGui.QWidget()
d.ui = mywidget.Ui_Dialog()
d.ui.setupUi(d)
d.show()

¡Y nuestro letrero de diálogo aparecerá! Ten en cuenta que nuestro intérprete de Python todavía está trabajando, ya que hemos usado un letrero de diálogo no modal. Por lo tanto, para cerrarlo, podemos (aparte de hacer clic en el icono de cerrar, por supuesto) escribir:

d.hide()

Ahora que podemos mostrar y ocultar nuestro letrero de diálogo, sólo tenemos que añadir una última parte: ¡que haga algo! Si juegas un poco con Qt Designer, descubrirás rápidamente toda una sección llamada "señales y slots". Básicamente, funciona así: los elementos de los widgets o complementos (en la terminología de Qt, estos elementos son a su vez widgets) pueden enviar señales. Estas señales varían según el tipo de widget. Por ejemplo, un botón puede enviar una señal cuando se presiona y cuando es soltado. Estas señales se pueden conectar a los slots, que puede ser una funcionalidad especial de otros widgets (por ejemplo, un cuadro de diálogo tiene un slot "close" (cerrado) en el que se puede conectar la señal de un botón close (de cierre)), o pueden ser funciones de usuario. La Documentación de referencia de PyQt enumera todos los widgets Qt, lo que pueden hacer, que señales pueden enviar, etc.

Lo que haremos aquí, es crear una nueva función que va a formar un plano basado en la altura y anchura, y conectar dicha función a la señal de "pulsado" emitida por nuestro botón "Create!". Empezaremos con la importación de nuestros módulos FreeCAD, poniendo la siguiente línea al comienzo del archivo de guión, donde ya hemos mandado también la importación de QtCore y QtGui:

import FreeCAD, Part

ahora, añadamos una nueva función a nuestra clase Ui_Dialog:

def createPlane(self):
    try:
        # first we check if valid numbers have been entered
        w = float(self.width.text())
        h = float(self.height.text())
    except ValueError:
        print("Error! Width and Height values must be valid numbers!")
    else:
        # create a face from 4 points
        p1 = FreeCAD.Vector(0,0,0)
        p2 = FreeCAD.Vector(w,0,0)
        p3 = FreeCAD.Vector(w,h,0)
        p4 = FreeCAD.Vector(0,h,0)
        pointslist = [p1,p2,p3,p4,p1]
        mywire = Part.makePolygon(pointslist)
        myface = Part.Face(mywire)
        Part.show(myface)
        self.hide()

A continuación, tenemos que informar a Qt para que conecte el botón con la función, mediante la colocación de la siguiente línea justo antes de QtCore.QMetaObject.connectSlotsByName(Dialog):

QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)

Como ves, esto conecta la señal pressed() de nuestro objeto create (el Botón "Create!"), a un slot llamado createPlane, que acabamos de definir. Eso es! Ahora, como toque final, podemos añadir una pequeña función para crear el cuadro de diálogo. Así será más fácil hacer las llamadas. Fuera de la clase Ui_Dialog, vamos a añadir este código:

class plane():
   def __init__(self):
       self.d = QtGui.QWidget()
       self.ui = Ui_Dialog()
       self.ui.setupUi(self.d)
       self.d.show()

(Python reminder: the __init__ method of a class is automatically executed whenever a new object is created!)

A continuación, en FreeCAD, sólo tenemos que hacer:

import mywidget
myDialog = mywidget.plane()

Y eso es todo amigos... Ahora puedes probar todo tipo de cosas, como por ejemplo insertar tu widget en la interfaz de FreeCAD (mira la página Pedazos de código), o la creación de herramientas personalizadas mucho más avanzado, mediante el uso de otros elementos en tu widget o complemento.

El archivo de guión completo

Este es el archivo de guión completo, como referencia:

# Form implementation generated from reading ui file 'mywidget.ui'
#
# Created: Mon Jun  1 19:09:10 2009
#      by: PyQt4 UI code generator 4.4.4
# Modified for PySide 16:02:2015 
# WARNING! All changes made in this file will be lost!

from PySide import QtCore, QtGui
import FreeCAD, Part 

class Ui_Dialog(object):
   def setupUi(self, Dialog):
       Dialog.setObjectName("Dialog")
       Dialog.resize(187, 178)
       self.title = QtGui.QLabel(Dialog)
       self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))
       self.title.setObjectName("title")
       self.label_width = QtGui.QLabel(Dialog)
       self.label_width.setGeometry(QtCore.QRect(10, 50, 57, 16))
       self.label_width.setObjectName("label_width")
       self.label_height = QtGui.QLabel(Dialog)
       self.label_height.setGeometry(QtCore.QRect(10, 90, 57, 16))
       self.label_height.setObjectName("label_height")
       self.width = QtGui.QLineEdit(Dialog)
       self.width.setGeometry(QtCore.QRect(60, 40, 111, 26))
       self.width.setObjectName("width")
       self.height = QtGui.QLineEdit(Dialog)
       self.height.setGeometry(QtCore.QRect(60, 80, 111, 26))
       self.height.setObjectName("height")
       self.create = QtGui.QPushButton(Dialog)
       self.create.setGeometry(QtCore.QRect(50, 140, 83, 26))
       self.create.setObjectName("create")

       self.retranslateUi(Dialog)
       QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)
       QtCore.QMetaObject.connectSlotsByName(Dialog)

   def retranslateUi(self, Dialog):
       Dialog.setWindowTitle("Dialog")
       self.title.setText("Plane-O-Matic")
       self.label_width.setText("Width")
       self.label_height.setText("Height")
       self.create.setText("Create!")
       print("tyty")
   def createPlane(self):
       try:
           # first we check if valid numbers have been entered
           w = float(self.width.text())
           h = float(self.height.text())
       except ValueError:
           print("Error! Width and Height values must be valid numbers!")
       else:
           # create a face from 4 points
           p1 = FreeCAD.Vector(0,0,0)
           p2 = FreeCAD.Vector(w,0,0)
           p3 = FreeCAD.Vector(w,h,0)
           p4 = FreeCAD.Vector(0,h,0)
           pointslist = [p1,p2,p3,p4,p1]
           mywire = Part.makePolygon(pointslist)
           myface = Part.Face(mywire)
           Part.show(myface)

class plane():
  def __init__(self):
      self.d = QtGui.QWidget()
      self.ui = Ui_Dialog()
      self.ui.setupUi(self.d)
      self.d.show()

More examples

Relevant links


Line drawing function/es
Licence/es

Desarrollando aplicaciones para FreeCAD


Licencias utilizadas

He aquí las tres licencias bajo las que se publica FreeCAD:

FreeCAD uses two different licenses, one for the application itself, and one for the documentation:

Lesser General Public Licence (LGPL2+)
Para las bibliotecas principales como se indica en los fichero .h y .cpp en src/App, src/Gui, sic/Base, y muchos de los módulos en src/Mod y para el ejecutable como se indica en los archivos .h y .cpp en el directorio src/main. Los iconos y otro material gráfico también son LGPL.
General Public Licence (GPL2+)
Para los archivo de guión de Python que construyen los binarios como se indica en los archivos .py en src/Tools
Open Publication Licence
Para la documentacion en http://free-cad.sourceforge.net/ salvo que se indique lo contrario por su autor

Creative Commons Attribution 3.0 License (CC-BY-3.0) For the documentation and the website.

Mira el archivo debian copyright file de FreeCAD, para tener más detalles sobre las licencias utilizadas en FreeCAD

Alcance de las licencias

Below is a friendlier explanation of what the LGPL license means for you:

All users

Usuarios particulares

Los usuarios particulares pueden utilizar FreeCAD de manera gratuita y pueden hacer básicamente cualquier cosa que quieran hacer con él ....

Professional users

Usuarios profesionales

Pueden usar libremente FreeCAD para cualquier tipo de trabajo particular o profesional. Se puede personalizar la aplicación como lo deseen. Pueden escribir extensiones para FreeCAD en código abierto o cerrado. Son siempre dueños de sus datos, no están obligados a actualizar FreeCAD, ni cambiar el uso que hacen de FreeCAD. El uso de FreeCAD no les vincula a ningún tipo de contrato u obligación.

Open-source software developers

Desarrolladores de código abierto (Open Source)

Puede utilizar FreeCAD como base para sus propios módulos de extensión para usos especiales. Pueden elegir entre GPL o LGPL para permitir, o no, el uso de su trabajo en software propietario.

Closed-source software developers

Desarrolladores profesionales

Los desarrolladores profesionales pueden utilizar FreeCAD como base para sus propios módulos de extensión para propósitos especiales y no están obligados a hacer sus módulos en código abierto. Pueden utilizar todos los módulos que utilizan LGPL. Se les permite distribuir FreeCAD junto con su software propietario. Se dará todo el apoyo del autor(es) siempre y cuando exista una actitud de correspondencia recíproca. Si quieres vender tu módulo necesitas una licencia de Coin3d, de lo contrario estás obligado por esta biblioteca a que tu módulo sea de código abierto.

1) You must clearly inform your users that your application is using FreeCAD and that FreeCAD is LGPL.

2) The LGPL license also stipulate your users must be able to swap your modified FreeCAD component with the original FreeCAD equivalent. That is would be done by dynamically linking to the FreeCAD components, so users are allowed to change it. However, this is often hard to achieve by today's requirements. At FreeCAD, we understand that the important point here is to not restrict the freedom given to FreeCAD users by the LGPL license. So an equivalent to dynamic linking is to offer the choice to your users, by making your users aware of the possibility to use FreeCAD for free. This can be done in a number of ways.

If any of the two conditions above are unacceptable to you or cannot be implemented, then you must make your FreeCAD component LGPL too and release the source code with all the modifications you made to it.

There is a special case called derivatives, which is when you publish basically a "rebranded" version of FreeCAD. Derivatives which are not open-source are prohibited by the LGPL license. The FreeCAD community is active and efficient in finding rebranded versions, reporting them to the platforms where they were found and exposing them until they are taken down.

Files

The models and other files produced with FreeCAD are not subject to any license stated above, nor bound to any kind of restriction or ownership. Your files are truly yours. You can set the owner of the file and specify your own license terms for the files you produce inside FreeCAD, via menu File → Project Information.

The FreeCAD logo is a trademark owned by the FPA (FreeCAD project association). This means the FPA is the sole body authorized to say who has the right to use the FreeCAD logo or not. The logo files, which are part of the FreeCAD source code or available elsewhere, for example on this wiki, are still all under the same licenses as the rest of FreeCAD (LGPL for the source code and Creative Commons for this wiki). You are still free to use the FreeCAD logo anywhere, on the same terms as the rest of FreeCAD, which means, basically, that you must use it to reference FreeCAD, and not use it, for example, for your own product, or any other way that is not referencing FreeCAD.

Statement of the main developer

Declaración del conservador/mantenedor

Sé que el debate sobre la licencia "adecuada" para el código abierto ocupa una parte importante del ancho de banda de Internet y esa es la razón por la que, en mi opinión, también FreeCAD debería tener aquí algo sobre el tema.

Elegí el LGPL y GPL para el proyecto y conozco los pros y los contras sobre LGPL, de modo que te explicaré algunos motivos para haber tomado esta elección.

FreeCAD es un híbrido entre una biblioteca y una aplicación, de modo que la licencia GPL sería demasiado fuerte para eso. No permitiría escribir módulos comerciales para FreeCAD porque impediría la vinculación con las librerías base de FreeCAD. Te puedes preguntar ¿por qué no prescindir totalmente de los módulos comerciales? En este ámbito Linux es un buen ejemplo. ¿Tendría Linux tanto éxito si la biblioteca GNU de C fuese GPL y, por tanto, incapacitada para ligarse con las aplicaciones no-GPL? Y aunque me encanta la libertad de Linux, yo también quiero ser capaz de usar el magnífico controlador gráfico NVIDIA 3D. Entiendo y acepto que NVIDIA tenga razones para no querer regalar el código de su controlador. Todos trabajamos para empresas y necesitamos el sueldo, o por lo menos comer. Por todo lo anterior, para mí, una coexistencia de software de código abierto y de código cerrado no es algo malo, cuando obedece a las reglas de la LGPL. Me gustaría ver a alguien escribiendo un módulo de importación/exportación de formato Catia para FreeCAD, y que se distribuyese, ya fuera gratis o por dinero. No me gusta obligar a nadie a que ceda más de lo que quiere. Eso no sería bueno ni para él, ni para FreeCAD.

No obstante, esta decisión se ha tomado sólo para el sistema básico de FreeCAD. Todo escritor de un módulo de aplicación puede tomar su propia decisión.

Jürgen Riegel

—15 October 2006


Dialog creation/es
Tracker/es


In February 2022 FreeCAD bug tracking was migrated to GitHub Issues. The Mantis bug tracker described below is now in read-only mode.
link=https://freecadweb.org/tracker/MantisBT is the bugtracker framework FreeCAD uses
link=https://freecadweb.org/tracker/MantisBT is the bugtracker framework FreeCAD uses

The FreeCAD BugTracker is the place toː report bugs, submit feature requests, patches, or request to merge your branch if you developed something using Git. The tracker is divided into 'Workbenches', so please be specific and file your request in the appropriate subsection. In case of doubt, leave it in the "FreeCAD" section.


Recommended Workflow

As shown in the above flowchart, before creating tickets, please always first search the forums and bugtracker to discover if your issue is a known issue. This saves a lot of time/work for developers and volunteers that could be spending said time making FreeCAD even more awesome.

Reportando errores

Si piensas que podrías haber encontrado un error, te invitamos a que lo informes allí. Pero antes de informar de un error, por favor, comprueba los elementos siguientes:

  • Asegúrate de que tu error es realmente un bug, es decir, algo que debería estar trabajando y que no está funcionando. Si no estás seguro, no dudes en explicar tu problema en el foro y pregunta qué hacer.
  • Antes de enviar cualquier cosa, lee las FAQ - Preguntas más frecuentes, haz una búsqueda en el foro, y asegúrate de que el mismo error no se ha informado antes, haciendo una búsqueda en el bug tracker.
  • Describe lo más claramente posible el problema, y cómo puede ser reproducido. Si no podemos verificar el error, puede que no seamos capaces de solucionarlo.
  • Incluye la siguiente información: Tu sistema operativo, si es 32 o 64 bits, y la versión de FreeCAD que estás ejecutando.
  • Por favor presenta un informe por separado para cada error.
  • Si estás en un sistema linux y tu error provoca un cuelgue en FreeCAD, puedes intentar ejecutar un backtrace debug: Desde un terminal ejecuta gdb freecad (suponiendo que el paquete gdb esté instalado), entonces, dentro de gdb, escribe run. FreeCAD se ejecutará. Después de que se produzca el fallo, teclea bt, para obtener el trazado completo. Incluye la salida del backtrace en tu informe de error.

Solicitar funcionalidades

Si quieres que aparezca algo en FreeCAD que aún no está implementado, no se trata de un error, sino una solicitud de funcionalidad. También puedes notificarlo en el mismo tracker (lo archivas como una petición de función, en lugar de errores), pero ten en cuenta que no hay garantías de que tus deseos se cumplan.

  1. IMPORTANTː Before requesting a potential Feature Request please be certain that you are the first one doing so by searching the forums and the bugtracker. If you have concluded that there are no pre-existing tickets/discussions the next step is toː
  2. Start a forum thread to discuss your feature request with the community via the Open Discussion forum.
  3. Once the community agrees that this is a valid Feature, you then can open a ticket on the tracker (file it under feature request instead of bug).
  • NOTE #1 To keep things organized please remember to link the forum thread URL into the ticket and the ticket number (as a link) in to the forum thread.
  • NOTE #2 Keep in mind there are no guarantees that your wish will be fulfilled.
FreeCAD Bugtracker report page - use the dropdown to correctly designate what the ticket is

Envío de parches

En caso de haber programado la corrección de un error, una extensión o algo que puede ser de uso público en FreeCAD, crea un parche con la herramienta Subversion diff y preséntalo en el mismo tracker (lo archivas como parche).

Requesting merge

(Same guidelines as Submiting patches)

If you have created a git branch containing changes that you would like to see merged into the FreeCAD code, you can ask there to have your branch reviewed and merged if the FreeCAD developers are OK with it. You must first publish your branch to a public git repository (github, gitlab, bitbucket, sourceforge etc...) and then give the URL of your branch in your merge request.

MantisBT Tips and Tricks

MantisBT Markup

MantisBT (Mantis Bug Tracker) has it's own unique markup.

  • @mention - works just like on GitHub where if you prepend '@' to someone's username they will receive an email that they have been 'mentioned' in a ticket thread
  • #1234 - By adding a hash tag in front of a number a shortcut to link to another ticket within MantisBT will present.
    Note: if you hover over a ticket it will show you the summary + if the ticket is closed, it will be struck-through like #1234.
  • ~5678 - a shortcut that links to a bug note within a ticket. This can be used to reference someone's response within the thread. Each person that posts will show a unique ~#### number next to their username. If you look at the image in the example, you see that the shortcut is referencing the ticket number:comment number of said ticket
  • <del></del> - Using these tags will strikeout text.
  • <code></code> - To present a line or block of code, use this tag and it will colorize and differentiate it elegantly.

MantisBT BBCode

In addition to the above MantisBT Markup one also has the possibility to use BBCode format. For a comprehensive list see the BBCode plus plugin page. Here is a list of supported BBCode tagsː
[img][/img] - Images
[url][/url] - Links
[email][/email] - Email addresses
[color=red][/color] - Colored text
[highlight=yellow][/highlight] - Highlighted text
[size][/size] - Font size
[list][/list] - Lists
[list=1][/list] - Numbered lists (number is starting number)
[*] - List items
[b][/b] - Bold
[u][/u] - underline
[i][/i] - Italic
[s][/s] - Strikethrough
[left][/left] - Left align
[center][/center] - Center
[right][/right] - Right align
[justify][/justify] - Justify
[hr] - Horizontal rule
[sub][/sub] - Subscript
[sup][/sup] - Superscript
[table][/table] - Table
[table=1][/table] - Table with border of specified width
[tr][/tr] - Table row
[td][/td] - Table column
[code][/code] - Code block
[code=sql][/code] - Code block with language definition
[code start=3][/code] - Code block with line numbers starting at number
[quote][/quote] - Quote by *someone* (no name)
[quote=name][/quote] - Quote by *name*

MantisBT <=> GitHub Markup

Below are special MantisBT Source-Integration plugin keywords which will link to the FreeCAD GitHub repo. See GitHub and MantisBT.

  • c:FreeCAD:git commit hash: - c stands for 'commit'. FreeCAD stands for the FreeCAD GitHub repo. 'git commit hash' is the specific git commit hash to reference. Note: the trailing colon is necessary. Exampleː cːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • d:FreeCAD:git commit hash: - similar to the above, d stands for 'diff' which will provide a Diff view of the commit. Exampleː dːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • p:FreeCAD:pullrequest: - similar to the above, p stands for Pull Request. Exampleː pːFreeCADː498ː

GitHub and MantisBT

The FreeCAD bugtracker has a plug-in called Source Integration which essentially ties both the FreeCAD GitHub repo to our MantisBT tracker. It makes it easier to track and associate git commits with their respective MantisBT tickets. The Source Integration plugin scans the git commit messages for specific keywords in order to execute the following actions:

Note The below keywords need to be added in the git commit message and not the PR subject

Remotely referencing a ticket

Using this pattern will automagically associate a git commit to a ticket (Note: this will not close the ticket.) The format MantisBT will recognize:

  • bug #1234
  • bugs #1234, #5678
  • issue #1234
  • issues #1234, #5678
  • report #1234
  • reports #1234, #5678

For the inquisitive here is the regex MantisBT uses for this operation:
/(?:bugs?|issues?|reports?)+\s*:?\s+(?:#(?:\d+)[,\.\s]*)+/i

Remotely resolving a ticket

The format MantisBT will recognize:

  • fix #1234
  • fixed #1234
  • fixes #1234
  • fixed #1234, #5678
  • fixes #1234, #5678
  • resolve #1234
  • resolved #1234
  • resolves #1234
  • resolved #1234, #5678
  • resolves #1234, #5678

For the inquisitive here is the regex MantisBT uses for this operation:
/(?:fixe?d?s?|resolved?s?)+\s*:?\s+(?:#(?:\d+)[,\.\s]*)+/i



Esta página explica paso a paso cómo compilar FreeCAD 0.19 o más reciente en Windows. Para otras plataformas ver Compilación.

Prerequisitos

La compilación de FreeCAD en Windows requiere varias herramientas y bibliotecas.

Requerido

  • Un compilador. FreeCAD está probado con Visual Studio (MSVC)-otros compiladores pueden funcionar, pero las instrucciones de uso no se incluyen aquí. Más detalles en #Compiler, más abajo.
  • Git (También hay frontales de GUI disponibles para Git, ver la siguiente sección).
  • CMake version 3.11.x or newer.
    Hint: Choosing the option Add CMake to the system PATH for all users when installing CMake will make CMake accessible from the Windows command prompt, which can be useful.
  • The LibPack. This is a single package containing all of the libraries necessary to compile FreeCAD on Windows. Download the version of the LibPack that corresponds to the version of FreeCAD you want to compile. To compile FreeCAD 0.20 download the LibPack version 2.6, for FreeCAD 0.19 download the LibPack version 1.0. Extract the LibPack to a convenient location. (If your computer does not recognize the .7z extension, you must install the program 7-zip.)
    Note: It is highly recommended to compile FreeCAD with the compiler version the LibPack is designed for. For example, you might run into problems compiling FreeCAD 0.20 using MSVC 2017 because the LibPack is designed to be built with MSVC 2019 or newer.
    To update your LibPack later, see the section Updating the LibPack.

Programas opcionales

  • A GUI frontend for Git. There are several frontends available, see this list. The main benefit of a frontend is that you don't have to learn the Git commands to get the source code of FreeCAD or to send patches to the GitHub repository of FreeCAD.

In the following we describe source code handling using the TortoiseGit frontend. This frontend integrates directly into Windows file explorer and has a large user community to get help in case you have problems.

  • NSIS is used to generate the FreeCAD Windows installer.

Código fuente

Ahora puedes obtener el código fuente de FreeCAD:

Usando un frontend

When using the Git frontend TortoiseGit:

  1. Create a new folder where the source code will be downloaded.
  2. Right-click on this folder in the Windows file explorer and select Git Clone in the context menu.
  3. A dialog will appear. In it, enter the URL for the FreeCAD Git repository

https://github.com/FreeCAD/FreeCAD.git

and click OK.

The latest source code will be downloaded from the FreeCAD Git repository and the folder will be tracked by Git.

Usando la línea de comando

To create a local tracking branch and download the source code, open a terminal (command prompt) and switch there to the directory you want the source, then type:

git clone https://github.com/FreeCAD/FreeCAD.git

Compilador

The default (recommended) compiler is MS Visual Studio (MSVC). Though it may be possible to use other compilers, for example gcc via Cygwin or MinGW, it is not tested or covered here.

You can get a free version of MSVC (for individual usage) by downloading the Community edition of MS Visual Studio.

For those who want to avoid installing the huge MSVC for the mere purpose of having a compiler, see CompileOnWindows - Reducing Disk Footprint.

Note: Although the Community edition of MSVC is free, to use the IDE for more than a 30-day trial period you must create a Microsoft account. If you will only compile using the command line, you don't need the IDE and thus no Microsoft account.

As a free and OpenSource alternative IDE you can use KDevelop. You can use KDevelop to modify and write C++ code but must use the command line to compile.

Configuración opcional de la ruta del sistema

Optionally you can include the paths to some folders to the system PATH variable. This is helpful if you want to access programs in these folders from the command line/powershell or if you want special programs to be found by the compiler or CMake. Besides this, adding folders to the PATH might be necessary if you did not use the corresponding options when installing the program.

  • You can include the folder of your LibPack in your system PATH variable. This is useful if you plan to build multiple configurations/versions of FreeCAD.
  • If you did not use the option to add CMake to the PATH while installing it, add its installation folder

C:\Program Files\CMake\bin to the PATH.

  • If you did not use the option to add TortoiseGit to the PATH while installing it, add its installation folder

C:\Program Files\TortoiseGit\bin to the PATH.

To add folder paths to the PATH variable:

  1. In the Windows Start menu Right click on Computer and choose Properties.
  2. In the appearing dialog click on Advanced system settings.
  3. Another dialog will open. Click there in the tab Advanced on Environment Variables.
  4. Again another dialog will open. Select then the variable Path and click on Edit.
  5. And again another dialog will open. Click there on New and add to path to the folder of Git or the LibPack.
  6. Finally press OK and close all dialogs by pressing OK as well.

Configuración

Once you have all of the necessary tools, libraries, and FreeCAD source code, you are ready to begin the configuration and compilation process. This process will proceed in five steps:

  1. Run CMake once to examine your system and begin the configuration progress (this will report that it failed).
  2. Adjust necessary CMake settings to set the locations of the LibPack and enable Qt5.
  3. Re-run CMake to finalize the configuration (this time it should succeed).
  4. Use CMake to generate the Visual Studio build system.
  5. Use Visual Studio to build FreeCAD.

CMake

First, configure the build environment using CMake:

  1. Open the CMake GUI
  2. Specify the source folder of FreeCAD.
  3. Specify a build folder. This can be build in the folder you cloned the repo because this path is ignored by git. Do not use the source folder. CMake will create this folder if it does not exist.
  4. Click Configure.
  5. In the dialog that appears specify the generator you want to use: in most cases you will use the defaults in this dialog. For the standard MS Visual Studio use Visual Studio xx 2yyy where xx is the compiler version and 2yyy the year of its release. It is recommended to use the default option Use default native compilers.

Note: It is important to specify the correct bit variant. If you have the 64-bit variant of the LibPack you must also use the x64 compiler.

This will begin the configuration and will fail because of missing settings. This is normal, you have not yet specified the location of the LibPack. However, there are other failures that might occur that require some further action on your part.

If it fails with the message that Visual Studio could not be found, the CMake support in MSVC is not yet installed. To do this:

  1. Open the MSVC IDE
  2. Use the menu Tools → Get Tools and Features
  3. In the Workloads tab enable Desktop development with C++
  4. On the right side you should now see that the component Visual C++ tools for CMake will be installed.
  5. Install it.

If it fails with a message about the wrong Python version or missing Python, then:

  1. Use the "Search:" box in CMake to search for the string "Python"
  2. If you see there a path like C:/Program Files/Python38/python.exe, CMake recognized the Python that is already installed on your PC, but that version is not compatible with the LibPack. Since the LibPack includes a compatible version of Python, modify the following Python settings in CMake to its paths (assuming the LibPack is in the folder D:/FreeCAD-build/FreeCADLibs_2_8_x64_VC2019):

If there is no error about Visual Studio or Python, everything is fine, but CMake does not yet know all necessary settings. Therefore now:

  1. Search in CMake for the variable FREECAD_LIBPACK_DIR and specify the location of the LibPack folder you downloaded earlier.
  2. (If building FreeCAD 0.19) Search for the variable BUILD_QT5 and enable this option.
  3. (If planning on running directly from the build folder such as for debugging) Search for and enable the following options:
    • FREECAD_COPY_DEPEND_DIRS_TO_BUILD
    • FREECAD_COPY_LIBPACK_BIN_TO_BUILD
    • FREECAD_COPY_PLUGINS_BIN_TO_BUILD
  4. Click Configure again.

There should now be no errors. If you continue to encounter errors that you cannot diagnose, visit the Install/Compile forum on the FreeCAD forum website. If CMake proceeded correctly, click on Generate. After this is done you can close CMake and start the compilation of FreeCAD using Visual Studio. However, for the first compilation keep it open in case you want or need to change some options for the build process.

Opciones para el proceso de construcción

The CMake build system gives you control over some aspects of the build process. In particular, you can switch on and off some features or modules using CMake variables.

Here is a description of some of these variables:

Variable name Description Default
BUILD_XXX Build FreeCAD with the component XXX. If you don't want/need to compile e.g. the workbench OpenSCAD, disable the variable BUILD_OPENSCAD. FreeCAD will then not have this workbench.

Note: Some components are required for other components. If you for example uncheck BUILD_ROBOT CMake will inform you that then the component Path cannot be compiled correctly. Therefore check the CMake output after you changed a BUILD_XXX option!

depends
BUILD_ENABLE_CXX_STD The version of the C++ language standard. C++14 is the highest possible for FreeCAD 0.19 while at least C++17 is required for FreeCAD 0.20. See also the note in the section Building with Visual Studio 15 (2017) and 16 (2019) depends
BUILD_DESIGNER_PLUGIN To build the Qt Designer plugin, see this section below OFF
BUILD_FLAT_MESH Necessary to have a build that includes the CreateFlatMesh feature OFF
CMAKE_INSTALL_PREFIX The output folder when building the target INSTALL, see also the section Running and installing FreeCAD Windows default program installation folder
FREECAD_COPY_DEPEND_DIRS_TO_BUILD Copies depending libraries needed to execute the FreeCAD.exe to the build folder. See also the section Running and installing FreeCAD.
Note: the options FREECAD_COPY_XXX only appear if the libraries were not already copied. If you only need to upgrade/change to another LibPack version, see the section Updating the LibPack. If you want to bring back the options for some reason, you need to delete all folders in your build folder, except for the LibPack folder. In CMake delete the cache and start as if you compile for the first time.
OFF
FREECAD_COPY_LIBPACK_BIN_TO_BUILD Copies the LibPack binaries needed to execute the FreeCAD.exe to the build folder. See also the section Running and installing FreeCAD. OFF
FREECAD_COPY_PLUGINS_BIN_TO_BUILD Copies Qt's plugin files needed to execute the FreeCAD.exe to the build folder. See also the section Running and installing FreeCAD. OFF
FREECAD_LIBPACK_USE Switch the usage of the FreeCAD LibPack on or off ON
FREECAD_LIBPACK_DIR Directory where the LibPack is FreeCAD's source code folder
FREECAD_RELEASE_PDB Create debug libraries (*.pdb) also for release builds. It doesn't affect the speed (like a real debug build would do) and can be very useful to locate crashes in FreeCAD code. In case FreeCAD crashes a crash.dmp file will be created that can be loaded with MSVC and if you have the corresponding PDB files plus the source code of that version you can debug through the code. Without the PDB files it's not possible to debug the code and all what the debugger shows is the name of the DLL where the crash has occurred. ON
FREECAD_USE_MP_COMPILE_FLAG Adds the /MP (multiprocessor) option to the Visual Studio projects, enabling speedups on multi-core CPUs. This can greatly accelerate builds on modern processors.
Note: If you turn off FREECAD_USE_PCH, the compilation can quickly overload your heap space, even if you have 16 GB RAM.
ON
FREECAD_USE_PCH Precompiles the headers in order to save compilation time. ON
FREECAD_USE_PYBIND11 Includes the PyBind11 library. Necessary to have a build that includes the CreateFlatMesh feature.
Note: after turning it on you might get a configuration error. Just configure again and the problem should go away.
OFF

Construyendo FreeCAD

Depending on your compiler, the process for building FreeCAD will be slightly different. In the following sections known workflows are described. If you are building with Qt Creator, jump to Building with Qt Creator (outdated), otherwise proceed directly:

Building with Visual Studio 15 (2017) or newer

Release Build

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Release.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build.

This will now take quite a long time.

To compile a ready-to use FreeCAD, compile the target INSTALL, see the section Running and installing FreeCAD.

If you don't get any errors you are done. Congratulations! You can exit MSVC or keep it open.

Important: Since Visual Studio 17.4 you cannot use the code optimization that is on by default for the target SketcherGui. If you do, angle constraints will be misplaced in sketches. To fix this, right-click on this target in the MSVC solution explorer and select the last entry Properties in the context menu. In the appearing dialog go to C/C++ → Optimization and there disable the setting Optimization. Finally build the target ALL_BUILD again.

Debug Build

For a debug build it is necessary that the Python is used that is included in the LibPack. To assure this:

  1. Search in the CMake GUI for "Python"
  2. If you see there a path like C:/Program Files/Python38/python.exe, CMake recognized the Python that is installed on your PC and not the one of the LibPack. In this case adapt these different Python settings in CMake to this (assuming the LibPack is in the folder D:\FreeCAD-build\FreeCADLibs_12.5.2_x64_VC17):

As prerequisite for the debug build, you need to do this:

  1. Copy the content of the LibPack folder bind to the bin folder of the FreeCAD build folder (overwrite the existing files).
  2. Copy the content of the LibPack folder libd to the lib folder of the FreeCAD build folder.

Now you can compile:

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Debug.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build in the context menu.

This will now take quite a long time.

If there were no compilation errors, and if the FREECAD_COPY_* options mentioned in the CMake Configuration step above were enabled, you can start the debug build:

  1. Right-click on the target FreeCADMain and then choose Set as Startup Project in the context menu.
  2. Finally click in the toolbar on the button with the green triangle named Local Windows Debugger.

This will start the debug build of FreeCAD and you can use the MSVC IDE to debug it.

Video Resource

An English language tutorial that begins with configuration in CMake Gui and continues to the `Build` command in Visual Studio 16 2019 is available unlisted on YouTube at Tutorial: Build FreeCAD from source on Windows 10.

Building with Qt Creator (outdated)

Installation and configuration of Qt Creator

  • Download and install Qt Creator
  • Tools → Options → Text Editor → Behavior tab:
    • File Encodings → Default Encodings:
    • Set to: ISO-8859-1 /...csISOLatin1 (Certain characters create errors/warnings with Qt Creator if left set to UTF-8. This seems to fix it.)
  • Tools → Options → Build & Run:
    • CMake tab
      • Fill Executable box with path to cmake.exe
    • Kits tab
      • Name: MSVC 2008
      • Compiler: Microsoft Visual C++ Compiler 9.0 (x86)
      • Debugger: Auto detected...
      • Qt version: None
    • General tab
      • Uncheck: Always build project before deploying it
      • Uncheck: Always deploy project before running it

Import project and building

  • File → Open File or Project
  • Open CMakeLists.txt which is in the top level of the source
  • This will start CMake
  • Choose build directory and click next
  • Set generator to NMake Generator (MSVC 2008)
  • Click Run CMake. Follow the instructions depicted above to configure CMake to your liking.

Now FreeCAD can be built

  • Build → Build All
  • This will take a long time...

Once complete, it can be run: There are 2 green triangles at the bottom left. One is debug. The other is run. Pick whichever you want.

Command line build

The steps how to compile from the command line depends on the compiler. For MSVC 2017 the steps are:

  1. In Windows start menu go to Visual Studio 2017 → Visual Studio Tools and choose Developer Command Prompt for VS 2017
  2. Change to your build folder.
  3. Execute the command
msbuild ALL_BUILD.vcxproj /p:Configuration=Release

or

msbuild INSTALL.vcxproj /p:Configuration=Release

These steps can also be automaized. Here is for example a solution for MSVC 2017:

  1. Download the script compile-FC.txt.
  2. Rename it to compile-FC.bat
  3. In Windows file explorer Shift+Right-click on your build folder and use from the context menu Command prompt here.
  4. Execute the command
compile-FC install

Instead of calling compile-FC with the option install you can also use debug or release:

debug   - compile FreeCAD in debug configuration

release - compile FreeCAD in release configuration

install    - compile FreeCAD in release configuration and create an install setup

Running and installing FreeCAD

There are 2 methods to run the compiled FreeCAD:

Method 1: You execute the FreeCAD.exe that you find in your build folder in the subfolder bin

Method 2: You build the target INSTALL

Method 2 is the simpler one because it automatically assures that all libraries needed to run the FreeCAD.exe are in the correct folder. The FreeCAD.exe and the libraries will be output in the folder you specified in the CMake variable CMAKE_INSTALL_PREFIX.

For Method 1 you need to enable the FREECAD_COPY_* options mentioned in the CMake Configuration step above.

Troubleshooting

When running FreeCAD you may encounter missing DLLs when using certain workbenches or features of workbenches. The error message in FreeCAD's console will not tell you what DLL is missing. To find this out you must use an external tool:

import os
os.system(r"~\DependenciesGui.exe")

Note: Instead of the ~ you must specify the full path to the DependenciesGui.exe on your system.

  • Now drag in the *.pyd file of the workbench with which you get missing DLLs reported.

Updating the build

FreeCAD is very actively developed. Therefore its source code changes almost daily. New features are added and bugs are fixed. To benefit from these source code changes, you must rebuild your FreeCAD. This is done in two steps:

  1. Updating the source code
  2. Recompilation

Updating the source code

Using a frontend

When using the Git frontend TortoiseGit:

  1. Right-click on your FreeCAD source code folder in the Windows file explorer and select Pull in the context menu.
  2. A dialog will appear. Select there what development branch you want to get. master is the main branch. Therefore use this unless you want to compile a special new feature from a branch that has not yet been merged to master. (For more about Git branches, see Git development process.)

Finally click OK.

Using the command line

Open a terminal (command prompt) and switch there to your source directory. Then type:

git pull https://github.com/FreeCAD/FreeCAD.git master

where master the the name of the main development branch. If you want to get code from another branch, use its name instead of master.

Recompilation

  1. Open the MSVC IDE by double-clicking either on the file FreeCAD.sln or on the file ALL_BUILD.vcxproj in your build folder.
  2. Continue with step 2 from the section Building with Visual Studio 15 2017.

Updating the LibPack

If a new major version of a third-party dependency like Open Cascade is released, or if a third-party dependency has important bug fixes, a new LibPack is released. You can find the latest version here.

To update your LibPack the following recipe is best practice:

  1. Delete the bin folder in your build folder.
  2. Switch to your local LibPack folder and delete everything there.
  3. Extract the content of the new LibPack ZIP file into the existing, but now empty, local LibPack folder.
  4. Open CMake and there press the button Configure and then the button Generate. This recreates the bin folder you just deleted and also copies the new LibPack files into it.
  5. In CMake click the button Open Project and the MSVC IDE will open.
  6. In the MSVC IDE build the target INSTALL.

Tools

In order to join the FreeCAD development you should compile and install the following tools:

Qt Designer plugin

FreeCAD uses Qt as toolkit for its user interface. All dialogs are setup in UI-files that can be edited using the program Qt Designer that is part of any Qt installation and also included in the LibPack. FreeCAD has its own set of Qt widgets to provide special features like adding a unit to input fields and to set preferences properties.

Compilation

The plugin cannot be loaded by the Qt Designer if it was compiled using another Qt version than the one your Qt Designer/Qt Creator is based on. Therefore the plugin must be compiled together with FreeCAD:

  • In the CMake options (see this section above) enable the option BUILD_DESIGNER_PLUGIN and reconfigure.
  • open MSVC and build the target FreeCAD_widgets

As result you will get the plugin file 'FreeCAD_widgets.dll in the folder
~\src\Tools\plugins\widget\Release

Installation

To install the plugin, copy the DLL either to:

  • If you use the LibPack: to the folder
    ~\FreeCADLibs_2_8_x64_VC2019\plugins\designer
  • If you have a full Qt installation: you can choose between the folder
    C:\Qt\5.15.2\msvc2019_64\plugins\designer
    or
    C:\Qt\5.15.2\msvc2019_64\bin\designer (you must first create the designer subfolder.)
    (adapt the paths to your installation!).

Finally (re)start Qt Designer and check its menu Help → Plugins. If the plugin FreeCAD_widgets.dll is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must compile the DLL by yourself.

If you prefer using Qt Creator instead of Qt Designer, the plugin file must be placed in this folder:
C:\Qt\Qt5.15.2\Tools\QtCreator\bin\plugins\designer
Then (re)start Qt Creator, switch to the mode Design and then check the menu Tools → Form Editor → About Qt Designer Plugins. If the plugin FreeCAD_widgets.dll is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must compile the DLL by yourself.

Thumbnail Provider

FreeCAD has the feature to provide preview thumbnails for *.FCStd files. That means that in the Windows file explorer *.FCStd files are shown with a screenshot of the model it contains. To provide this feature, FreeCAD needs to have the file FCStdThumbnail.dll installed to Windows.

Installation

The DLL is installed this way:

  1. Download this ZIP file and extract it.
  2. Open a Windows command prompt with administrator privileges (these privileges are a requirement).
  3. Change to the folder where the DLL is.
  4. Execute this command
    regsvr32 FCStdThumbnail.dll

So check if it works, assure that in FreeCAD the preferences option Save thumbnail into project file when saving document is enabled and save a model. Then view in Windows Explorer the folder of the saved model using a symbol view. You should now see a screenshot of the model in the folder view.

Compilation

To compile the FCStdThumbnail.dll

  1. Change to the FreeCAD source folder
    ~\src\Tools\thumbs\ThumbnailProvider
  2. Open the CMake GUI
  3. Specify there as source folder the one you are currently in.
  4. Use the same folder as build folder.
  5. Click Configure
  6. In the appearing dialog, specify the generator according to the one you want to use. For the standard MS Visual Studio use Visual Studio xx 2yyy where xx is the compiler version and 2yyy the year of its release. It is recommended to use the default option Use default native compilers.
    Note: It is important to specify the correct bit variant. If you have the 64bit variant of LibPack you must also use the x64 compiler.
  7. Click on Generate.
  8. You should now have the file ALL_BUILD.vcxproj in the folder ~\src\Tools\thumbs\ThumbnailProvider. Double-click on it and the MSVC IDE will open.
  9. In the toolbar of the MSVC IDE assure that you use the compilation target Release.
  10. There is a window called Solution Explorer. Right-click there on ALL_BUILD and then choose Build.
  11. As result you should now have a FCStdThumbnail.dll in the folder ~\src\Tools\thumbs\ThumbnailProvider\release that you can install as described above.

Compiling Open Cascade

The LibPack comes with a version of Open Cascade that is suitable for general use. However, under some circumstances you may wish to compile against an alternate version of Open Cascade, such as one of their official releases, or a patched fork.

When compiling Open Cascade for FreeCAD note that there is no guarantee that FreeCAD will work with all versions of Open Cascade. Note also that when you are using the Netgen library, you must use the a NetGen version that it approved to compile with the Open Cascade version you like to compile.

To compile:

  • Then open the CMake GUI to configure the build system in a similar manner to building FreeCAD. These CMake options have to be set (or explicitly not set):
Variable name Description Default
3RDPARTY_DIR The path to 3rdparty components. It is recommended to use the folder as input where your used LibPack is. Explicitly leave this field empty. empty
3RDPARTY_DOXYGEN_EXECUTABLE The path to the executable of the 3rdparty component Doxygen. It is recommended to install Doxygen. CMake will then find it automatically. empty
3RDPARTY_FREETYPE_DIR The path to the necessary 3rdparty component Freetype. It is recommended to use the folder as input where your used LibPack is. empty
3RDPARTY_RAPIDJSON_DIR Only available if USE_RAPIDJSON is used. The path to the 3rdparty component RapidJSON. It is recommended NOT to use an existing LibPack folder as input. You can use the RapidJSOn folder from a LibPack, but copy it to a new folder and use this new folder as input. empty
3RDPARTY_TCL_DIR The path to the necessary 3rdparty component TCL. It is recommended NOT to use an existing LibPack folder as input. Take for example one of these releases, extract it and take this as input folder for CMake. empty
3RDPARTY_TK_DIR The path to the necessary 3rdparty component TK. It is recommended NOT to use an existing LibPack folder as input. Take for example one of these releases, extract it and take this as input folder for CMake. empty
3RDPARTY_VTK_DIR Only available if USE_VTK is used. The path to the necessary 3rdparty component VTK. It is recommended to use the folder as input where your used LibPack is. If you use another folder please assure that you don't use VTK 9.x or newer. empty
BUILD_RELEASE_DISABLE_EXCEPTIONS Disables exception handling for release builds. For FreeCAD you must set it to OFF. ON
INSTALL_DIR The output folder when building the target INSTALL. If the build was successful, take the files from this folder to update your LibPack. Windows default program installation folder
INSTALL_DIR_BIN The output subfolder for the DLL when building the target INSTALL. You must change it to bin win64/vc14/bin
INSTALL_DIR_LIB The output subfolder for the .lib files when building the target INSTALL. You must change it to lib win64/vc14/lib
USE_RAPIDJSON To compile Open Cascade with support for RapidJSON. Enabling this is mandatory in order to get support for the file format glTF. OFF
USE_VTK To compile Open Cascade with support for VTK. Enabling this is optimal. You can use this to build Open Cascade's VTK bridge. OFF
  • Open the project in Visual Studio and first build the ALL_BUILD and then INSTALL targets in the Release mode.
  • Repeat building the two targets in the Debug mode.

To build FreeCAD using the self-compiled Open Cascade, you must do the following:

  • Copy all folders from the INSTALL_DIR to your LibPack folder (overwrite the existing files)
  • Switch to the LibPack folder and go there to the subfolder cmake
  • Open there the file OpenCASCADEDrawTargets.cmake with a text editor
  • Search there for absolute paths to your LibPack folder and remove them. So e.g. the absolute path
    D:/FreeCADLibs_12.5.4_x64_VC17/lib/freetype.lib
    becomes just
    freetype.lib
  • Do the same for the file OpenCASCADEVisualizationTargets.cmake

Compiling Netgen

The LibPack comes with a version of Netgen that will was tested to be build with the Open Cascade version of the LibPack. The problem is that every new release of Netgen changes the API. Also every new release of Open Cascade does the same. Therefore one cannot just easily change the Netgen version.

However, you might build Netgen nevertheless. This is an easy task:

  • First obtain the Netgen source code, either directly from Netgen 's git repository.
  • Then open the CMake GUI to configure the build system in a similar manner to building FreeCAD. These CMake options have to be set:
Variable name Description Default
CMAKE_INSTALL_PREFIX The output folder when building the target INSTALL. If the build was successful, take the files from this folder to update your LibPack. C:/netgen
OpenCasCade_DIR The path to the CMake files of Open Cascade. If you built Open Cascade as described in the section Compiling Open Cascade you can use the subfolder cmake of there folder you used as INSTALL_DIR. If not, use the subfolder cmake of your LibPack. Note hereby that the LibPack must then already contain a proper Open Cascade build. Independent what folder you use, you must now also create there a subfolder lib and copy in the files freetype.lib and freetyped.lib from your LibPack. empty
USE_GUI set it to OFF ON
USE_NATIVE_ARCH set it to OFF; this is only necessary important to support older CPU that don't have the AVX2 instruction set ON
USE_OCC set it to ON OFF
USE_PYTHON set it to OFF ON
USE_SUPERBUILD set it to OFF ON
ZLIB_INCLUDE_DIR The path to the necessary 3rdparty component zlib. It is recommended to use the folder as input where your used LibPack is. empty
ZLIB_LIBRARY_DEBUG The path to the ZLib file zlibd.lib. It is located in the subfolder lib of your LibPack folder. empty
ZLIB_LIBRARY_RELEASE The path to the ZLib file zlib.lib. It is located in the subfolder lib of your LibPack folder. empty
  • Additionally you need to add a new CMake entry:

name: CMAKE_DEBUG_POSTFIX, type: string, content: _d
This assures that he file names of the debug libraries get another name than the release libraries and can later not be accidentally exchanged.

  • Press the Configure button in CMake to generate the *.cmake files.
  • Only necessary if older CPU should be supported that don't have the AVX2 instruction set:
    • Search your Netgen build folder for the file netgen-targets.cmake and open it with a text editor. Remove the setting ;/arch:AVX2 in the Option INTERFACE_COMPILE_OPTIONS.
    • Press the Configure button in CMake again.
  • Press the Generate button in CMake.
  • Open the project in Visual Studio and first build the ALL_BUILD and then INSTALL targets in the Release mode.
  • Repeat building the two targets in the Debug mode.

To build FreeCAD using the self-compiled Netgen, you must do the following:

  • Copy all folders from the CMAKE_INSTALL_PREFIX to your LibPack folder (overwrite the existing files)

References

See also



Hay un contenedor experimental FreeCAD Docker que se está probando para el desarrollo de FreeCAD. Lea más sobre ello en Compilar en Docker

Vista general

En las distribuciones recientes de Linux, FreeCAD es generalmente fácil de construir, ya que todas las dependencias suelen ser proporcionadas por el administrador de paquetes. Básicamente implica 3 pasos:

  1. Obtener el código fuente de FreeCAD
  2. Obtener las dependencias o paquetes de los que depende FreeCAD
  3. Configurar con cmake y compilar con make

A continuación, encontrará explicaciones detalladas de todo el proceso, algunos build scripts, y las particularidades que puede encontrar. Si encuentras algo incorrecto o desactualizado en el texto de abajo (las distribuciones de Linux cambian a menudo), o si usas una distribución que no está en la lista, discute el tema en el forum, y ayúdanos a corregirlo.

Flujo de trabajo general para compilar FreeCAD desde la fuente. Las dependencias de terceros deben estar en el sistema, así como el propio código fuente de FreeCAD. CMake configura el sistema de manera que con una sola instrucción de creación se compila todo el proyecto.

Obtener la fuente

Git

La mejor manera de obtener el código es clonar el repositorio Git de sólo lectura [1]. Para ello se necesita el programa git que se puede instalar fácilmente en la mayoría de las distribuciones de Linux. También puede obtenerse en el sitio web oficial.

Git se puede instalar mediante el siguiente comando:

sudo apt install git

El siguiente comando colocará una copia de la última versión del código fuente de FreeCAD en un nuevo directorio llamado freecad-source.

git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad-source

Para más información sobre el uso de Git y la contribución de código al proyecto, véase Gestión del código fuente.

Archivo Fuente

También puede descargar el código fuente como un archivo [2], un archivo .zip o .tar.gz, y descomprimirlo en el directorio deseado.

Obtener las dependencias

Para compilar FreeCAD tienes que instalar las dependencias necesarias mencionadas en Bibliotecas de terceros; los paquetes que contienen estas dependencias están listados abajo para diferentes distribuciones de Linux. Tenga en cuenta que los nombres y la disponibilidad de las bibliotecas dependerán de su distribución particular; si su distribución es antigua, algunos paquetes pueden no estar disponibles o tener un nombre diferente. En este caso, busque en la sección Distribuciones antiguas y no convencionales más abajo.

Una vez que tengas todas las dependencias instaladas, procede a compilar FreeCAD.

Ten en cuenta que el código fuente de FreeCAD tiene un tamaño de unos 500 MB; puede ser tres veces mayor si clonas el repositorio Git con todo su historial de modificaciones. Obtener todas las dependencias puede requerir la descarga de 500 MB o más de nuevos archivos; cuando estos archivos se descomprimen pueden requerir 1500 MB o más de espacio. También ten en cuenta que el proceso de compilación puede generar hasta 1500 MB de archivos adicionales ya que el sistema copia y modifica todo el código fuente. Por lo tanto, asegúrese de tener suficiente espacio libre en su disco duro, al menos 4 GB, cuando intente la compilación.

Debian y Ubuntu

En los sistemas basados en Debian (Debian, Ubuntu, Mint, etc.) es bastante fácil conseguir instalar todas las dependencias necesarias. La mayoría de las bibliotecas están disponibles a través de apt o del gestor de paquetes Synaptic.

Si ya has instalado FreeCAD desde los repositorios oficiales, puedes instalar sus dependencias de construcción con esta única línea de código en un terminal:

sudo apt build-dep freecad

Sin embargo, si la versión de FreeCAD en los repositorios es antigua, las dependencias pueden ser las incorrectas para compilar una versión reciente de FreeCAD. Por lo tanto, comprueba que tienes instalados los siguientes paquetes.

Estos paquetes son esenciales para que cualquier tipo de compilación tenga éxito:

  • build-essential, instala los compiladores C y C++, las librerías de desarrollo C y el programa make.
  • cmake, herramienta esencial para configurar el código fuente de FreeCAD. También puedes querer instalar cmake-gui y cmake-curses-gui para una opción gráfica.
  • libtool, herramientas esenciales para producir bibliotecas compartidas.
  • lsb-release, la utilidad estándar de informes de base normalmente ya está instalada en un sistema Debian, y le permite distinguir mediante programación entre una instalación Debian pura o una variante, como Ubuntu o Linux Mint. No elimine este paquete, ya que muchos otros paquetes del sistema pueden depender de él.

La compilación de FreeCAD utiliza el lenguaje Python, y también se utiliza en tiempo de ejecución como lenguaje de scripting. Si estás usando una distribución basada en Debian el intérprete de Python normalmente ya está instalado.

  • python3
  • swig, la herramienta que crea interfaces entre el código C++ y Python.

Por favor, comprueba que tienes instalado Python 3. Python 2 quedó obsoleto en 2019, por lo que los nuevos desarrollos en FreeCAD no se prueban con esta versión del lenguaje.

Es necesario instalar las bibliotecas Boost:

  • libboost-dev
  • libboost-date-time-dev
  • libboost-filesystem-dev
  • libboost-graph-dev
  • libboost-iostreams-dev
  • libboost-program-options-dev
  • libboost-python-dev
  • libboost-regex-dev
  • libboost-serialization-dev
  • libboost-thread-dev

Es necesario instalar las bibliotecas de Coin:

  • libcoin80-dev, para Debian Jessie, Stretch, Ubuntu 16.04 a 18.10, o
  • libcoin-dev, para Debian Buster, Ubuntu 19.04 y más recientes, así como para Ubuntu 18.04/18.10 con los PPAs freecad-stable/freecad-daily añadidos a sus fuentes de software.

Varias bibliotecas que se ocupan de las matemáticas, las superficies trianguladas, la ordenación, las mallas, la visión por ordenador, las proyecciones cartográficas, la visualización 3D, el sistema de ventanas X11, el análisis sintáctico de XML y la lectura de archivos Zip:

  • libeigen3-dev
  • libgts-bin
  • libgts-dev
  • libkdtree++-dev
  • libmedc-dev
  • libopencv-dev or libcv-dev
  • libproj-dev
  • libvtk7-dev or libvtk6-dev
  • libx11-dev
  • libxerces-c-dev
  • libyaml-cpp-dev
  • libzipios++-dev

Python 2 y Qt4

Esto no se recomienda para las instalaciones más recientes, ya que tanto Python 2 como Qt4 están obsoletos. A partir de la versión 0.20, FreeCAD ya no los soporta.

Para compilar FreeCAD para Debian Jessie, Stretch, Ubuntu 16.04, usando Python 2 y Qt4, instala las siguientes dependencias.

  • qt4-dev-tools
  • libqt4-dev
  • libqt4-opengl-dev
  • libqtwebkit-dev
  • libshiboken-dev
  • libpyside-dev
  • pyside-tools
  • python-dev
  • python-matplotlib
  • python-pivy
  • python-ply
  • python-pyside

Python 3 y Qt5

Para compilar FreeCAD para Debian Buster, Ubuntu 19.04 y posteriores, así como Ubuntu 18.04/18.10 con el freecad-stable/freecad-daily PPAs añadido a sus fuentes de software, instale las siguientes dependencias.

  • qtbase5-dev
  • qttools5-dev
  • qt5-default (if compiling 0.20 on a machine that still has Qt4)
  • libqt5opengl5-dev
  • libqt5svg5-dev
  • qtwebengine5-dev
  • libqt5xmlpatterns5-dev
  • libqt5x11extras5-dev
  • libpyside2-dev
  • libshiboken2-dev
  • pyside2-tools
  • pyqt5-dev-tools
  • python3-dev
  • python3-matplotlib
  • python3-packaging
  • python3-pivy
  • python3-ply
  • python3-pyside2.qtcore
  • python3-pyside2.qtgui
  • python3-pyside2.qtsvg
  • python3-pyside2.qtwidgets
  • python3-pyside2.qtnetwork
  • python3-pyside2.qtwebengine
  • python3-pyside2.qtwebenginecore
  • python3-pyside2.qtwebenginewidgets
  • python3-pyside2.qtwebchannel
  • python3-pyside2uic

Núcleo OpenCascade

El núcleo de OpenCascade es el núcleo de la biblioteca de gráficos para crear formas 3D. Existe una versión oficial OCCT, y una versión comunitaria OCE. La versión de la comunidad ya no se recomienda, ya que está obsoleta.

Para Debian Buster y Ubuntu 18.10 y posteriores, así como para Ubuntu 18.04 con el freecad-stable/freecad-daily PPAs añadido a sus fuentes de software, instale los paquetes oficiales.

  • libocct*-dev
    • libocct-data-exchange-dev
    • libocct-draw-dev
    • libocct-foundation-dev
    • libocct-modeling-algorithms-dev
    • libocct-modeling-data-dev
    • libocct-ocaf-dev
    • libocct-visualization-dev
  • occt-draw

Para Debian Jessie, Stretch, Ubuntu 16.04 y posteriores, instale los paquetes de la edición comunitaria.

  • liboce*-dev
    • liboce-foundation-dev
    • liboce-modeling-dev
    • liboce-ocaf-dev
    • liboce-ocaf-lite-dev
    • liboce-visualization-dev
  • oce-draw

Puede instalar las bibliotecas individualmente, o utilizando la expansión de asterisco. Cambie occ por oce si desea instalar las bibliotecas comunitarias.

sudo apt install libocct*-dev

Paquetes opcionales

Opcionalmente, también puede instalar estos paquetes adicionales:

  • libsimage-dev, para que Coin soporte formatos de archivo de imagen adicionales.
  • doxygen y libcoin-doc (o libcoin80-doc para los sistemas más antiguos), si quieres generar documentación del código fuente.
  • libspnav-dev, para soporte de Dispositivos de entrada 3D, como el "Space Navigator" o el "Space Pilot" de 3Dconnexion.
  • checkinstall, si pretende registrar los archivos instalados en el gestor de paquetes de su sistema, para poder desinstalarlo más tarde.

Comando único para Python 3 y Qt5

Requiere Pyside2 disponible en Debian buster y el freecad-stable/freecad-daily PPAs.

sudo apt install cmake cmake-gui libboost-date-time-dev libboost-dev libboost-filesystem-dev libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev libboost-python-dev libboost-regex-dev libboost-serialization-dev libboost-thread-dev libcoin-dev libeigen3-dev libgts-bin libgts-dev libkdtree++-dev libmedc-dev libocct-data-exchange-dev libocct-ocaf-dev libocct-visualization-dev libopencv-dev libproj-dev libpyside2-dev libqt5opengl5-dev libqt5svg5-dev qtwebengine5-dev libqt5x11extras5-dev libqt5xmlpatterns5-dev libshiboken2-dev libspnav-dev libvtk7-dev libx11-dev libxerces-c-dev libzipios++-dev occt-draw pyside2-tools python3-dev python3-matplotlib python3-packaging python3-pivy python3-ply python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qtsvg python3-pyside2.qtwidgets python3-pyside2.qtnetwork python3-pyside2.qtwebengine python3-pyside2.qtwebenginecore python3-pyside2.qtwebenginewidgets python3-pyside2.qtwebchannel python3-markdown python3-git python3-pyside2uic qtbase5-dev qttools5-dev swig libyaml-cpp-dev

NOTA: En algunas versiones de Ubuntu y algunas versiones de Qt, obtendrá un error de que no se puede encontrar python3-pyside2uic - en esos sistemas puede omitirlo con seguridad. En Ubuntu 20.04 tendrá que añadir pyqt5-dev-tools. Puede encontrar más información en esta discusión del foro.

Comando único para Python 2 y Qt4

Esto no se recomienda para las instalaciones más recientes, ya que tanto Python 2 como Qt4 están obsoletos.

sudo apt install cmake debhelper dh-exec dh-python libboost-date-time-dev libboost-dev libboost-filesystem-dev libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev libboost-python-dev libboost-regex-dev libboost-serialization-dev libboost-thread-dev libcoin80-dev libeigen3-dev libgts-bin libgts-dev libkdtree++-dev libmedc-dev libocct-data-exchange-dev libocct-ocaf-dev libocct-visualization-dev libopencv-dev libproj-dev libpyside-dev libqt4-dev libqt4-opengl-dev libqtwebkit-dev libshiboken-dev libspnav-dev libvtk6-dev libx11-dev libxerces-c-dev libzipios++-dev lsb-release occt-draw pyside-tools python-dev python-matplotlib python-pivy python-ply swig

Los usuarios de Ubuntu 16.04 por favor vean también la discusión de compilación en el foro: Compilación en Linux (Kubuntu): CMake no puede encontrar VTK.

Raspberry Pi

Siga los mismos pasos que en Debian y Ubuntu.

Hay problemas reportados cuando se intenta compilar en Raspbian con Python 3 y Qt5, pero la combinación Python 3 y Qt4 parece funcionar para versiones antiguas de FreeCAD.

Para las nuevas versiones de FreeCAD la compilación con Py3/Qt5 tiene éxito si el sistema operativo instalado es Ubuntu 20.04.

Debido a diferentes problemas con Qt, en esta versión no se encontrarán las herramientas normales de PySide.

E: Unable to locate package python3-pyside2uic

En este caso, podemos instalar los paquetes desde PyQt y crear enlaces simbólicos a las herramientas necesarias.

sudo apt-get install pyqt5-dev
sudo apt-get install pyqt5-dev-tools
cd /usr/bin/
ln -s pyrcc5 pyside2-rcc
ln -s pyuic5 pyside2-uic

Ahora la compilación puede continuar.

cd freecad-build/
cmake ../freecad-source -DBUILD_QT5=ON -DPYTHON_EXECUTABLE=/usr/bin/python3 -DUSE_PYBIND11=ON
make -j2

La opción -j de make no debe ser más de 3 porque la Raspberry Pi tiene memoria limitada. Tardará varias horas en compilar, por lo que es mejor hacerlo durante la noche.

Más información, FreeCAD y Raspberry Pi 4.

Fedora

There is a bug in cmake distributed by Fedora 34/35 which results in cmake failing to find the opencascade libraries. This can easily be fixed by making one minor change to the top level cmake file of opencascade installed on Fedora. Details here: https://bugzilla.redhat.com/show_bug.cgi?id=2083568.

Near the top of the file OpenCASCADEConfig.cmake, change the following line to use REAL_PATH(). This fixes a bug introduced by the use of a symlink from /lib to /usr/lib of Fedora, which causes cmake to fail.

This file is usually installed in /usr/lib64/cmake/opencascade/OpenCASCADEConfig.cmake.

get_filename_component (OpenCASCADE_INSTALL_PREFIX "${OpenCASCADE_INSTALL_PREFIX}" PATH)

change this to:

file (REAL_PATH ${OpenCASCADE_INSTALL_PREFIX} OpenCASCADE_INSTALL_PREFIX)

This trivial change needs to be made inside the build directory once cmake has been run and failed. Re-running cmake will then correctly detect the OCCT libraries in the normal way.

Fedora38/39

Now install Python 3.11. This includes a notable change in how Python initializes when running a program. As a result FreeCAD fails to find OpenCamLib, meaning 3D Surface and Waterline are not available in the CAM Workbench. This was fixed in the master branch on 20th Mar 2024 (Pull request #13059).

Necesita los siguientes paquetes :

  • gcc-c++ (or possibly another C++ compiler?)
  • cmake
  • doxygen
  • swig
  • gettext
  • dos2unix
  • desktop-file-utils
  • libXmu-devel
  • freeimage-devel
  • mesa-libGLU-devel
  • opencascade-devel
  • openmpi-devel
  • python3
  • python3-devel
  • python3-pyside2
  • python3-pyside2-devel
  • pyside2-tools
  • boost-devel
  • tbb-devel
  • eigen3-devel
  • qt-devel
  • qt5-qtwebengine-devel
  • qt5-qtxmlpatterns
  • qt5-qtxmlpatterns-devel
  • qt5-qtsvg-devel
  • qt5-qttools-static
  • ode-devel
  • xerces-c
  • xerces-c-devel
  • opencv-devel
  • smesh-devel
  • Coin3
  • Coin3-devel
  • yaml-cpp

(Abril 2021, Coin4 y Coin4-devel están disponibles ) (si coin2 es el último disponible para su versión de Fedora, utilice los paquetes de http://www.zultron.com/rpm-repo/)

  • SoQt-devel
  • freetype
  • freetype-devel
  • vtk
  • vtk-devel
  • med
  • med-devel

Y opcionalmente:

To install all dependencies at once (tested on fedora 36 and 37):

sudo dnf install gcc-c++ cmake doxygen swig gettext dos2unix desktop-file-utils libXmu-devel freeimage-devel mesa-libGLU-devel opencascade-devel openmpi-devel python3 python3-devel python3-pyside2 python3-pyside2-devel pyside2-tools boost-devel tbb-devel eigen3-devel qt-devel qt5-qtwebengine-devel qt5-qtxmlpatterns qt5-qtxmlpatterns-devel qt5-qtsvg-devel qt5-qttools-static ode-devel xerces-c xerces-c-devel opencv-devel smesh-devel Coin3 Coin3-devel SoQt-devel freetype freetype-devel vtk vtk-devel med med-devel libspnav-devel python3-pivy python3-markdown python3-GitPython yaml-cpp

Gentoo

La forma más fácil de comprobar qué paquetes son necesarios para compilar FreeCAD es comprobarlo a través de portage:

emerge -pv freecad

Esto debería dar una buena lista de paquetes adicionales que necesitas instalar en tu sistema.

Si FreeCAD no está disponible en Portage, está disponible en waebbl overlay. El rastreador de problemas en el Github de la superposición waebbl puede ayudar a guiar a través de algunos problemas que puede encontrar. El overlay proporciona freecad-9999, que puedes elegir para compilar, o simplemente usar para obtener las dependencias.

layman -a waebbl

openSUSE

Tumbleweed

Los siguientes comandos instalarán los paquetes necesarios para construir FreeCAD con Qt5 y Python 3.

zypper in --no-recommends -t pattern devel_C_C++ devel_qt5

zypper in libqt5-qtbase-devel libqt5-qtsvg-devel libqt5-qttools-devel boost-devel swig libboost_program_options-devel libboost_mpi_python3-devel libboost_system-devel libboost_program_options-devel libboost_regex-devel libboost_python3-devel libboost_thread-devel libboost_system-devel libboost_headers-devel libboost_graph-devel python3 python3-devel python3-matplotlib python3-matplotlib-qt5 python3-pyside2 python3-pyside2-devel python3-pivy gcc gcc-fortran cmake occt-devel libXi-devel opencv-devel libxerces-c-devel Coin-devel SoQt-devel freetype2-devel eigen3-devel libode6 vtk-devel libmed-devel hdf5-openmpi-devel openmpi2-devel netgen-devel freeglut-devel libspnav-devel f2c doxygen dos2unix glew-devel yaml-cpp

El siguiente comando instalará Qt Creator y el depurador de proyectos GNU.

zypper in libqt5-creator gdb

Si falta algún paquete, puedes comprobar el archivo Tumbleweed "FreeCAD.spec" en el Open Build Service.

Además, compruebe si hay algún parche que deba aplicar (como 0001-find-openmpi2-include-files.patch).

Leap

Si hay una diferencia entre los paquetes disponibles en Tumbleweed y Leap, entonces puedes leer el archivo Leap "FreeCAD.spec" en el Open Build Service para determinar los paquetes necesarios.

Ver piano_jonas guía no oficial "Compilar en openSUSE".

Arch Linux

Necesitará las siguientes bibliotecas de los depósitos oficiales:

  • boost
  • cmake
  • coin
  • curl
  • desktop-file-utils
  • eigen
  • gcc-fortran
  • git
  • glew
  • hicolor-icon-theme
  • jsoncpp
  • libspnav
  • med
  • nlohmann-json
  • opencascade
  • pyside2-tools
  • pyside2
  • python-matplotlib
  • python-netcdf4
  • python-packaging
  • python-pivy
  • qt5-svg
  • qt5-tools
  • qt5-webengine
  • shared-mime-info
  • shiboken2
  • swig
  • utf8cpp
  • verdict
  • xerces-c
  • yaml-cpp
sudo pacman -S --needed boost cmake coin curl desktop-file-utils eigen gcc-fortran git glew hicolor-icon-theme jsoncpp libspnav med nlohmann-json opencascade pyside2-tools pyside2 python-matplotlib python-netcdf4 python-packaging python-pivy qt5-svg qt5-tools qt5-webengine shared-mime-info shiboken2 swig utf8cpp xerces-c yaml-cpp

Note: Since version 5.0.1 of the openmpi package the binary libmpi_cxx.so stopped being shipped, this breaks the compilation with the current CMake process. To fix this you need to downgrade the package, see this forum post.

Distribuciones antiguas y no convencionales

En otras distribuciones, tenemos muy pocos comentarios de los usuarios, por lo que podría ser más difícil encontrar los paquetes necesarios.

Intente primero localizar las bibliotecas necesarias mencionadas en bibliotecas de terceros en su gestor de paquetes. Tenga en cuenta que algunas de ellas pueden tener un nombre de paquete ligeramente diferente; busque nombre, pero también libname, nombre-dev, nombre-devel, y similares. Si no es posible, intente compilar esas bibliotecas usted mismo.

FreeCAD requiere una versión del compilador GNU g++ igual o superior a la 3.0.0, ya que FreeCAD está escrito principalmente en C++. Durante la compilación se ejecutan algunos scripts de Python, por lo que el intérprete de Python tiene que funcionar correctamente. Para evitar cualquier problema con el enlazador también es una buena idea tener las rutas de las bibliotecas en la variable LD_LIBRARY_PATH o en el archivo ld.so.conf. Esto ya se hace en las distribuciones modernas de Linux, pero puede ser necesario configurarlo en las más antiguas.

Pivy

Pivy (envoltorios de Python para Coin3d) no es necesario para construir FreeCAD o para iniciarlo, pero es necesario como una dependencia en tiempo de ejecución por el Ambiente de Trabajo Borrador. Si no vas a utilizar este ambiente de trabajo, no necesitarás Pivy. Sin embargo, ten en cuenta que el Ambiente de Trabajo Borrador es utilizado internamente por otros ambientes de trabajo, como Arquitectura y BIM, por lo que Pivy necesita ser instalado para utilizar estos ambientes de trabajo también.

En noviembre de 2015 la versión obsoleta de Pivy incluida con el código fuente de FreeCAD ya no compilará en muchos sistemas. Esto no es un gran problema ya que normalmente deberías obtener Pivy desde el gestor de paquetes de tu distribución; si no puedes encontrar Pivy, puede que tengas que compilarlo tú mismo, ver Instrucciones de compilación de Pivy.

Símbolos de depuración

Para solucionar los fallos en FreeCAD, es útil tener los símbolos de depuración de las bibliotecas de dependencia importantes como Qt. Para ello, intenta instalar los paquetes de dependencia que terminan con -dbg, -dbgsym, -debuginfo o similares, dependiendo de tu distribución de Linux.

Para Ubuntu, es posible que tenga que habilitar repositorios especiales para poder ver e instalar estos paquetes de depuración con el gestor de paquetes. Consulte Debug Symbol Packages para obtener más información.

Compila FreeCAD

Compilación contra Python 2 y Qt4 ya no está bien soportada, y a partir de la versión 0.20 ya no está soportada en absoluto. Debería compilar contra Python 3 y Qt5. 0.20 requiere al menos Python3.6 y Qt 5.9.

FreeCAD utiliza CMake como su principal sistema de compilación, ya que está disponible en los principales sistemas operativos. La compilación con CMake es normalmente muy simple y ocurre en dos pasos.

  1. CMake comprueba que todos los programas y bibliotecas necesarios están presentes en tu sistema, y genera un Makefile que se configura para el segundo paso. FreeCAD tiene varias opciones de configuración entre las que elegir, pero viene con unos valores por defecto razonables. Algunas alternativas se detallan a continuación.
  2. La compilación propiamente dicha, que se realiza con el programa make, que genera los ejecutables de FreeCAD.

Dado que FreeCAD es una aplicación de gran tamaño, la compilación de todo el código fuente puede tardar entre 10 minutos y una hora, dependiendo de tu CPU y del número de núcleos de la CPU utilizados para la compilación.

Creación fuera-fuente

Para construir fuera-fuente, simplemente crea un directorio de construcción, freecad-build, distinto de tu carpeta de fuentes de FreeCAD, freecad-source; entonces desde este directorio de construcción apunta cmake a la carpeta de fuentes correcta. Puedes usar cmake-gui o ccmake en lugar de cmake en las instrucciones de abajo también. Una vez que cmake termine de configurar el entorno, utilice make para iniciar la compilación real.

# from your freecad source folder:
mkdir build
cd build
cmake ../
make -j$(nproc --ignore=2)

La opción -j de make controla cuántos trabajos (archivos) se compilan en paralelo. El programa nproc imprime el número de núcleos de la CPU en su sistema; usándolo junto con la opción -j puede elegir procesar tantos archivos como núcleos tenga, para acelerar la compilación general del programa. En el ejemplo anterior, utilizará todos los núcleos de tu sistema excepto dos; esto mantendrá a tu ordenador respondiendo para otros usos mientras la compilación se realiza en segundo plano. El ejecutable de FreeCAD aparecerá finalmente en el directorio freecad-build/bin. Ver también Compilación (aceleración) para mejorar la velocidad de compilación.

Resolving cmake issues

If you have done a build before and get stuck on a dependency that is not recognized or can't seem to be resolved, try the following:

  • Delete the contents of the build directory before running cmake again. FreeCAD is a rapidly moving target, you may be tripping over cached cmake information that points at an older version than the new repository head can use. Clearing the cache may allow cmake to recover and recognize the version you actually need.
  • If cmake complains about missing a specific file, use a tool such as "apt-file search", or its equivalent in other package systems, to discover what package that file belongs to and install it. Bear in mind that you are likely to need the -dev version of the package that carries header or config files files required for FreeCAD to use the package.

Compiling against GNU libc 2.34 and later

GNU libc 2.34 introduces a change to the library that can cause builds on some Linux systems to fail with an error like:

No rule to make target '/usr/lib/x86_64-linux-gnu/libdl.so

To resolve this, a symbolic link must be manually created from the (now empty) system-installed libdl.so.* to the location your compiler says it is looking for the file. For example (if the actual installed copy of libdl.so on your system is /usr/lib/x86_64-linux-gnu/libdl.so.2):

sudo ln -s /usr/lib/x86_64-linux-gnu/libdl.so.2 /usr/lib/x86_64-linux-gnu/libdl.so

Adapt the command for the structure of your system by searching for libdl.so* and linking it to the appropriate location.

Cómo reparar su directorio de código fuente

Si accidentalmente realizaste una compilación dentro del directorio de código fuente, o agregaste archivos extraños, y quisieras restaurar el contenido a sólo el código fuente original, puedes realizar los siguientes pasos.

> .gitignore
git clean -df
git reset --hard HEAD

La primera línea borra el archivo .gitignore. Esto asegura que los siguientes comandos de limpieza y reinicio afectarán a todo el directorio y no ignorarán los elementos que coincidan con las expresiones en .gitignore. La segunda línea borra todos los archivos y directorios que no son rastreados por el repositorio git; luego el último comando restablecerá cualquier cambio en los archivos rastreados, incluyendo el primer comando que borró el archivo .gitignore.

Si no borra el directorio de fuentes, las siguientes ejecuciones de cmake pueden no capturar las nuevas opciones del sistema si el código cambia.

Configuración

Pasando diferentes opciones a cmake, puedes cambiar cómo se compila FreeCAD. La sintaxis es la siguiente.

cmake -D <var>:<type>=<value> $SOURCE_DIR

Donde $SOURCE_DIR es el directorio que contiene el código fuente. El <tipo> puede omitirse en la mayoría de los casos. El espacio después de la opción -D también puede omitirse.

Por ejemplo, para evitar construir el Ambiente de trabajo MEF:

cmake -D BUILD_FEM:BOOL=OFF ../freecad-source
cmake -DBUILD_FEM=OFF ../freecad-source

Todas las variables posibles están listadas en el archivo InitializeFreeCADBuildOptions.cmake, ubicado en el directorio cMake/FreeCAD_Helpers. En este archivo, busque la palabra option para llegar a las variables que se pueden establecer, y ver sus valores por defecto.

# ==============================================================================
# =================   All the options for the build process    =================
# ==============================================================================

option(BUILD_FORCE_DIRECTORY "The build directory must be different to the source directory." OFF)
option(BUILD_GUI "Build FreeCAD Gui. Otherwise you have only the command line and the Python import module." ON)
option(FREECAD_USE_EXTERNAL_ZIPIOS "Use system installed zipios++ instead of the bundled." OFF)
option(FREECAD_USE_EXTERNAL_SMESH "Use system installed smesh instead of the bundled." OFF)
...

Alternativamente, utilice el comando cmake -LH para listar la configuración actual, y por tanto todas las variables que pueden ser modificadas. También puede instalar y utilizar cmake-gui para lanzar una interfaz gráfica que muestra todas las variables que pueden ser modificadas. En las siguientes secciones enumeramos algunas de las opciones más relevantes que puede querer utilizar.

Para una creación de depuración

Crea una compilación Debug para solucionar fallos en FreeCAD. Ten en cuenta que con esta compilación el Croquizador se vuelve muy lento con croquis complejos.

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Debug ../freecad-source

Para una creación de versión

Crea una compilación Release para probar el código que no se bloquea. Una compilación Release se ejecutará mucho más rápido que una compilación Debug.

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Release ../freecad-source

Creación contra Python 3 y Qt5

Por defecto, FreeCAD 0.19 y anteriores construyen para Python 2 y Qt4. Dado que estos dos paquetes son obsoletos, es mejor construir para Python 3 y Qt5. El soporte para Python 2 y Qt4 se ha eliminado en FreeCAD 0.20 y no es necesario activar explícitamente Qt5 y Python 3 si se compilan las últimas versiones de desarrollo.

Por 0.20_dev:

cmake ../freecad-source

Tenga en cuenta que al cambiar entre las compilaciones 0.19 y 0.20, puede ser necesario borrar CMakeCache.txt antes de ejecutar cmake.

Creación para una versión específica de Python

Si el ejecutable python por defecto en tu sistema es un enlace simbólico a Python 2, cmake intentará configurar FreeCAD para esta versión. Puedes elegir otra versión de Python dando la ruta a un ejecutable específico:

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 ../freecad-source

Si eso no funciona, es posible que tenga que definir variables adicionales que apunten a las bibliotecas de Python deseadas y a los directorios de inclusión:

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3.6 \
    -DPYTHON_INCLUDE_DIR=/usr/include/python3.6m \
    -DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
    -DPYTHON_PACKAGES_PATH=/usr/lib/python3.6/site-packages/ \
    ../freecad-source

Es posible tener varias versiones independientes de Python en el mismo sistema, por lo que las ubicaciones y números de versión de sus archivos de Python dependerán de su distribución particular de Linux. Utilice python3 -V para mostrar la versión de Python que está utilizando actualmente; sólo son necesarios los dos primeros números; por ejemplo, si el resultado es Python 3.6.8, necesita especificar los directorios que se refieren a la versión 3.6. Si no conoce los directorios correctos, intente buscarlos con el comando locate.

locate python3.6

Puede utilizar python3 -m site en un terminal para determinar el directorio site-packages, o dist-packages para los sistemas Debian.

Some components of FreeCAD, such as PySide, try to autodetect the most recent Python version installed on your system, which might fail if it is different from what you entered above. Adding the following cMake option might solve the issue:

-DPython3_FIND_STRATEGY=LOCATION

Creación con Qt Creator contra Python 3 y Qt5

1. Inicie Qt Creator.

2. Haga clic en Abierto Proyecto.

3. Navega hasta el directorio donde está el código fuente, freecad-source/, y elige el archivo CMakeLists.txt más alto.

4. Al seleccionar el archivo, se ejecutará automáticamente cmake en él, pero puede fallar si las opciones apropiadas no están correctamente configuradas.

5. Vaya a Projects → Build & Run → Imported Kit → Build → Build Settings → CMake. Establezca el directorio de compilación adecuado, freecad-build/.

6. Establezca las variables apropiadas en el diálogo Clave-Valor, de tipos String y Bool.

PYTHON_EXECUTABLE=/usr/bin/python3

7. Si las variables no cargan el proyecto correctamente, puede que tenga que ir a Projects → Manage Kits → Kits → Default (o Kit importado o similar) → CMake Configuration. A continuación, pulse Cambiar, y añada la configuración adecuada como se ha descrito anteriormente. Puede que tenga que añadir más variables sobre las rutas de Python, si no se encuentra el Python del sistema.

PYTHON_EXECUTABLE:STRING=/usr/bin/python3.7
PYTHON_INCLUDE_DIR:STRING=/usr/include/python3.7m
PYTHON_LIBRARY:STRING=/usr/lib/x86_64-linux-gnu/libpython3.7m.so
PYTHON_PACKAGES_PATH:STRING=/usr/lib/python3.7/site-packages

7.1. Pulse Aplicar y luego Aceptar.

7.2. Asegúrese de que el resto de las opciones están correctamente configuradas, por ejemplo, Versión de Qt debe ser una versión presente instalada en el sistema, como Qt 5.9.5 en PATH (qt5).

Pulse Aplicar y luego Aceptar para cerrar la configuración.

El programa cmake debería ejecutarse automáticamente de nuevo, y debería rellenar todo el diálogo Clave-Valor con todas las variables configurables.

8. Vaya a Projects → Build & Run → Imported Kit → Run → Run Settings → Run Configuration y elija FreeCADMain para compilar la versión gráfica de FreeCAD, o FreeCADMainCMD para compilar sólo la versión de línea de comandos.

9. Finalmente, vaya al menú Build → Build Project "FreeCAD". Si se trata de una nueva compilación, debería tardar varios minutos, incluso horas, dependiendo del número de procesadores que tengas disponibles.

Qt designer complemento

Si quieres desarrollar código Qt para FreeCAD, necesitarás el plugin Qt Designer que proporciona todos los widgets personalizados de FreeCAD.

Entra en un directorio auxiliar del código fuente, ejecuta qmake con el archivo de proyecto indicado para crear un Makefile; luego ejecuta make para compilar el plugin.

cd freecad-source/src/Tools/plugins/widget
qmake plugin.pro
make

Si estás compilando para Qt5, asegúrate de que el binario qmake es el correspondiente a esta versión, para que el Makefile resultante contenga la información necesaria para Qt5.

cd freecad-source/src/Tools/plugins/widget
$QT_DIR/bin/qmake plugin.pro
make

donde $QT_DIR es el directorio que almacena las bibliotecas binarias de Qt, por ejemplo, /usr/lib/x86_64-linux-gnu/qt5.

La biblioteca creada es libFreeCAD_widgets.so, que debe copiarse en $QT_DIR/plugins/designer.

sudo cp libFreeCAD_widgets.so $QT_DIR/plugins/designer

Pivy externo o interno

Anteriormente, una versión de Pivy estaba incluida en el código fuente de FreeCAD (interno). Si querías usar la copia de Pivy de tu sistema (externo), necesitabas usar <código>-DFREECAD_USE_EXTERNAL_PIVY=1</código>.

El uso de Pivy externo se convirtió en el valor por defecto durante el desarrollo de FreeCAD 0.16, por lo que ya no es necesario configurar esta opción manualmente.

Documentación de Doxygen

Si tienes Doxygen instalado puedes construir la documentación del código fuente. Consulte documentación de origen para obtener instrucciones.

Documentación adicional

El código fuente de FreeCAD es muy extenso, y con CMake es posible configurar muchas opciones. Aprender a usar CMake completamente puede ser útil para elegir las opciones adecuadas para tus necesidades particulares.

Hacer un paquete debian

Si planea construir un paquete Debian a partir de las fuentes, necesita instalar primero ciertos paquetes:

sudo apt install dh-make devscripts lintian

Vaya al directorio de FreeCAD y llame a

debuild

Una vez construido el paquete, puede utilizar lintian para comprobar si el paquete contiene errores

lintian freecad-package.deb

*.deb package with checkinstall

The Debian script checkinstall allows to create a *.deb package that can be installed and removed with the standard dpkg commands. It may need to be installed first (on Ubuntu use sudo apt install checkinstall). It's interactive and asks for the required information providing helpful defaults. During the process the package is installed and a *.deb file and a backup archive are created.

It's a good idea to define a name and a short description for the package. The name must be entered to uninstall it again and the desription will be listed by dpkg -l. The default name "build" is not very informative.

Example:

cd freecad-source/build
cmake ..
make
sudo checkinstall                                  # e.g. name=freecad-test1

The result is a *.deb file in the build folder. checkinstall will install the build by default. This is how you can install or uninstall it:

cd freecad-source/build
ls | grep freecad
        freecad-test1_20220814-1_amd64.deb
sudo dpkg -i freecad-test1_20220814-1_amd64.deb   # install
dkpg -l | grep freecad                            # find by name
sudo dpkg -r freecad-test1                        # uninstall by name

Actualización del código fuente

El sistema CMake permite actualizar de forma inteligente el código fuente, y sólo recompilar lo que ha cambiado, haciendo que las compilaciones posteriores sean más rápidas.

Muévete a la ubicación donde el código fuente de FreeCAD fue descargado por primera vez, y saca el nuevo código:

cd freecad-source
git pull

A continuación, muévete al directorio de compilación donde el código fue compilado inicialmente, y ejecuta cmake especificando el directorio actual (denotado por un punto); luego activa la re-compilación con make.

cd ../freecad-build
cmake .
make -j$(nproc --ignore=2)

Uninstalling the source code

In case the compiled source code was installed with sudo make install (for Debian) the files were copied to the /usr/local folder into several subfolders. For uninstallation the file install_manifest.txt can be used. It has been created into the build folder during compilation and contains all installed files. As long as this file exists, the installation can be uninstalled.

cd freecad-source/freecad-build
xargs sudo rm < install_manifest.txt

Solución de problemas

Para sistemas de 64 bits

Cuando se compone FreeCAD para 64 bits hay un problema conocido con el paquete OpenCASCADE (OCCT) de 64 bits. Para que FreeCAD funcione correctamente puede ser necesario ejecutar el script configure y establecer CXXFLAGS adicionales:

./configure CXXFLAGS="-D_OCC64"

Para los sistemas basados en Debian, esta opción no es necesaria cuando se utilizan los paquetes precompilados de OpenCASCADE porque éstos establecen el CXXFLAGS adecuado internamente.

Scripts de creación automática

Aquí está todo lo que necesitas para una construcción completa de FreeCAD. Es un enfoque de un solo script y funciona en una distribución de Linux recién instalada. Los comandos pedirán la contraseña de root para la instalación de paquetes y nuevos repositorios online. Estos scripts deberían funcionar en versiones de 32 y 64 bits. Están escritos para diferentes versiones, pero también es probable que funcionen en una versión posterior con o sin cambios importantes.

Si tienes un script de este tipo para tu distribución preferida, por favor discútelo en el foro de FreeCAD para que podamos incorporarlo.

Ubuntu

Estos scripts proporcionan una forma fiable de instalar el conjunto correcto de dependencias necesarias para construir y ejecutar FreeCAD en Ubuntu. Hacen uso de los archivos de paquetes personales de Ubuntu (PPA), y deberían funcionar en cualquier versión de Ubuntu a la que se dirija el PPA. El freecad-daily PPA se dirige a versiones recientes de Ubuntu, mientras que el freecad-stable PPA se dirige a las versiones oficialmente soportadas de Ubuntu.

Este script instala la instantánea diaria compilada de FreeCAD y sus dependencias. Añade el repositorio diario, obtiene las dependencias para construir esta versión, e instala los paquetes necesarios. Después procede a sacar el código fuente en un directorio particular, crea un directorio de compilación y cambia en él, configura el entorno de compilación con cmake, y finalmente construye el programa completo con make. Guarda el script en un archivo, hazlo ejecutable y ejecútalo, pero no utilices sudo; se pedirán privilegios de superusuario sólo para los comandos seleccionados. Pulsa "CTRL-ENTER" para cambiar de canal, "ALT-SHIFT-D" para subir, "ALT-SHIFT-B" para hacer un resumen, o pulsa "ALT" para hacer otros comandos.

#!/bin/sh
sudo add-apt-repository --enable-source ppa:freecad-maintainers/freecad-daily && sudo apt-get update
sudo apt-get build-dep freecad-daily
sudo apt-get install freecad-daily

git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad-source
mkdir freecad-build
cd freecad-build
cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DFREECAD_USE_PYBIND11=ON ../freecad-source
make -j$(nproc --ignore=2)

Si lo deseas, puedes desinstalar la versión precompilada de FreeCAD (freecad-daily) dejando las dependencias en su lugar, sin embargo, dejar este paquete instalado permitirá al gestor de paquetes mantener sus dependencias actualizadas también; esto es sobre todo útil si tienes la intención de seguir el desarrollo de FreeCAD, y actualizar y compilar constantemente las fuentes desde el repositorio Git.

El script anterior asume que quieres compilar la última versión de FreeCAD, por lo que estás usando el repositorio "diario" para obtener las dependencias. Sin embargo, puedes obtener las dependencias de la versión "estable" de tu versión actual de Ubuntu. Si este es el caso, reemplace la parte superior del script anterior con las siguientes instrucciones. Para Ubuntu 12.04, omita --enable-source del comando.

#!/bin/sh
sudo add-apt-repository --enable-source ppa:freecad-maintainers/freecad-stable && sudo apt-get update
sudo apt-get build-dep freecad
sudo apt-get install libqt5xmlpatterns5-dev   # Needed for 0.20; should go away on next packaging update 
sudo apt-get install freecad

Una vez que instales el paquete freecad desde el repositorio freecad-stable, sustituirá al ejecutable de FreeCAD que está disponible en el repositorio de Universe Ubuntu. El ejecutable se llamará simplemente freecad, y no freecad-stable.

openSUSE

No se necesitan repositorios externos para compilar FreeCAD. Sin embargo, hay una incompatibilidad con python3-devel que debe ser eliminada. FreeCAD puede ser compilado desde GIT

# install needed packages for development
sudo zypper install gcc cmake OpenCASCADE-devel libXerces-c-devel \
python-devel libqt4-devel python-qt4 Coin-devel SoQt-devel boost-devel \
libode-devel libQtWebKit-devel libeigen3-devel gcc-fortran git swig
 
# create new dir, and go into it
mkdir FreeCAD-Compiled 
cd FreeCAD-Compiled
 
# get the source
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git free-cad
 
# Now you will have a subfolder in this location called free-cad. It contains the source
 
# make another dir for compilation, and go into it
mkdir FreeCAD-Build1
cd FreeCAD-Build1 
 
# build configuration 
cmake ../free-cad
 
# build FreeCAD
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Como estás usando git, la próxima vez que desees compilar no tienes que clonar todo, simplemente tira de git y compila una vez más

# go into free-cad dir created earlier
cd free-cad
 
# pull
git pull
 
# get back to previous dir
cd ..
 
# Now repeat last few steps from before.
 
# make another dir for compilation, and go into it
mkdir FreeCAD-Build2
cd FreeCAD-Build2
 
# build configuration 
cmake ../free-cad
 
# build FreeCAD
# Note: to speed up build use all CPU cores: make -j$(nproc)
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Debian Squeeze

# get the needed tools and libs
sudo apt-get install build-essential python libcoin60-dev libsoqt4-dev \
libxerces-c2-dev libboost-dev libboost-date-time-dev libboost-filesystem-dev \
libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev \
libboost-serialization-dev libboost-signals-dev libboost-regex-dev \
libqt4-dev qt4-dev-tools python2.5-dev \
libsimage-dev libopencascade-dev \
libsoqt4-dev libode-dev subversion cmake libeigen2-dev python-pivy \
libtool autotools-dev automake gfortran
 
# checkout the latest source
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad
 
# go to source dir
cd freecad
 
# build configuration 
cmake .
 
# build FreeCAD
# Note: to speed up build use all CPU cores: make -j$(nproc)
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Fedora 27/28/29

Enviado por el usuario [PrzemoF] en el foro.

#!/bin/bash

ARCH=$(arch)

MAIN_DIR=FreeCAD
BUILD_DIR=build

#FEDORA_VERSION=27
#FEDORA_VERSION=28
FEDORA_VERSION=29

PACKAGES="gcc cmake gcc-c++ boost-devel zlib-devel swig eigen3 qt-devel \
shiboken shiboken-devel pyside-tools python-pyside python-pyside-devel xerces-c \
xerces-c-devel OCE-devel smesh graphviz python-pivy python-matplotlib tbb-devel \
 freeimage-devel Coin3 Coin3-devel med-devel vtk-devel"

FEDORA_29_PACKAGES="boost-python2 boost-python3 boost-python2-devel boost-python3-devel"

if [ "$FEDORA_VERSION" = "29" ]; then
    PACKAGES="$PACKAGES $FEDORA_29_PACKAGES"
fi

echo "Installing packages required to build FreeCAD"
sudo dnf -y install $PACKAGES
cd ~
mkdir $MAIN_DIR || { echo "~/$MAIN_DIR already exist. Quitting.."; exit; }
cd $MAIN_DIR
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git
mkdir $BUILD_DIR || { echo "~/$BUILD_DIR already exist. Quitting.."; exit; }
cd $BUILD_DIR
cmake ../FreeCAD 
make -j$(nproc)

Arch usando AUR

Repositorio de usuarios Arch (AUR) es una colección de recetas hechas por el usuario para construir paquetes que no están oficialmente soportados por los mantenedores de la distribución / comunidad. Por lo general, son seguros. Puedes ver quién mantiene el paquete y durante cuánto tiempo lo ha hecho. Se recomienda comprobar los archivos de construcción. También hay software que no es de código abierto disponible en esta área, incluso si es mantenido por la compañía oficial propietaria.

Requisito previo : git

Pasos :

  1. Abrir un terminal. Opcionalmente, crear un directorio, por ejemplo, mkdir git. Opcionalmente, cambiar de directorio, por ejemplo, cd git.
  2. Clonar el repositorio AUR : git clone http://aur.archlinux.org/packages/freecad-git
  3. Entrar en la carpeta del repositorio AUR : cd freecad-git
  4. Compilar usando Arch makepkg : makepkg -s. La bandera -s o --syncdeps también instalará las dependencias necesarias.
  5. Instalar el paquete creado : makepkg --install o hacer doble clic en el pkgname-pkgver.pkg.tar.xz dentro de su navegador de archivos.

Para actualizar FreeCAD a la última compilación simplemente repite el paso 3.Actualiza el repo de AUR cuando haya algún cambio de ruptura en la receta o nuevas características usando git checkout -f dentro de la carpeta.



There is an experimental FreeCAD Docker container that is being tested for FreeCAD development. Read more about it at Compile on Docker

Overview

This page describes how to compile the FreeCAD source code on macOS. For other platforms, see Compiling.

These instructions have been tested on macOS Catalina with standard XCode 11.6. It is known to work on macOS BigSur Beta with XCode 12.0 beta. If you plan to use XCode Beta, please be sure to download Command Line Tools add on through a dmg package to workaround some libz dependency issues.

This page serves as a quick start, and is not intended to be comprehensive with regard to describing all the available build options.

If you just want to evaluate the latest pre-release build of FreeCAD, you can download pre-built binaries from here.

Install Prerequisites

The following software must be installed to support the build process.

Homebrew Package Manager

Homebrew is a command line based package manager for macOS. The Homebrew main page provides an installation command line that you simply paste into a terminal window.

CMake

CMake is a build tool that generates a build configuration based on variables you specify. You then issue the 'make' command to actually build that configuration. The command-line version of CMake is automatically installed as part of the Homebrew installation, above. If you prefer to use a GUI version of CMake, you can download it from here.

Install Dependencies

FreeCAD maintains a Homebrew 'cask' which installs the required formulas and dependencies. Issue the following brew commands in your terminal.

brew tap freecad/freecad
brew install eigen
brew install --only-dependencies freecad

brew install may take quite a while, so you may want go grab a beverage. :-).

Alternately, you can install the individual dependencies manually by installing the following packages using brew install ...:

  • cmake
  • swig
  • boost
  • boost-python3
  • eigen
  • gts
  • vtk
  • xerces-c
  • qt@5 - Only Qt5 is currently supported, support for Qt6 is a work-in-progress
  • opencascade
  • doxygen
  • pkgconfig
  • coin3d - Note that as of this writing (Nov. 2022) this will install an unusable version of pyside@2 as a dependency.

There are several packages that are only available when you have tapped the freecad cask: you must do that (brew tap freecad/freecad). Due to some historical bug workarounds, at the time of this writing (Nov. 2022) the versions of PySide2 and Shiboken2 installed by Homebrew are not usable because they force the use of Py_Limited_API, which FreeCAD does not support. It is expected that this workaround will be removed in the coming months, but in the meantime you must use the FreeCAD cask versions of PySide and Shiboken. Use brew install ..., install the following packages:

  • freecad/freecad/pyside2@5.15.5
  • freecad/freecad/shiboken2@5.15.5
  • freecad/freecad/med-file
  • freecad/freecad/netgen

You will also need to "link" PySide and Shiboken:

brew link freecad/freecad/pyside2@5.15.5 freecad/freecad/shiboken2@5.15.5

In some cases the packages installed by Homebrew do not use the same Python version: for example, at the time of this writing PySide2 uses Python 3.10, but boost-python3 uses Python 3.11. While it is possible to "roll back" the more advanced version (so that in this case boost-python3 uses Python 3.10) this is an advanced operation, and in many cases it is best to wait for an update to the other package. If you want to pursue that path anyway, look at the "brew extract" command, which you can use to extract a formula into a new cask (typically freecad/freecad). You can then edit that formula as needed.

You will need to set the path to Qt: Qt5 is currently supported, while support for Qt6 is a work-in-progress. Set FREECAD_QT_VERSION to "Auto" or "5" to select Qt5 (the default). On the command line, use something like:

cmake \
  -DCMAKE_BUILD_TYPE="Release" \
  -DPYTHON_EXECUTABLE="/usr/local/bin/python3" \
  -DQt5_DIR="/usr/local/Cellar/qt@5/5.15.7/lib/cmake/Qt5" \
  -DPySide2_DIR="/usr/local/Cellar/pyside2@5.15.5/5.15.5/lib/cmake/PySide2-5.15.5" \
  -DShiboken2_DIR="/usr/local/Cellar/shiboken2@5.15.5/5.15.5_1/lib/cmake/Shiboken2-5.15.5" \
  ../freecad-source

Get the source

In the following instructions, the source and build folders are created side-by-side under

/Users/username/FreeCAD

but you can use whatever folders you want.

mkdir ~/FreeCAD
cd ~/FreeCAD

The following command will clone the FreeCAD git repository into a directory called FreeCAD-git.

git clone https://github.com/FreeCAD/FreeCAD FreeCAD-git

Create the build folder.

mkdir ~/FreeCAD/build

Run CMake

Next, we will run CMake to generate the build configuration. Several options must be passed to CMake. The following table describes the options and gives some background.

CMake Options

Name Value Notes
CMAKE_BUILD_TYPE Release (STRING) Release or Debug. Debug is generally used for developer-level testing but may also be required for user-level testing and troubleshooting.
CMAKE_PREFIX_PATH "/usr/local/opt/qt5152;" ... (PATH) Required to build with Qt5. See note below. You also need to add path to VTK libraries and NGLIB libraries cmake configuration file.
FREECAD_CREATE_MAC_APP 1 (BOOL) Create a FreeCAD.app bundle at the location specified in CMAKE_INSTALL_PREFIX, when the 'make install' command issued.
CMAKE_INSTALL_PREFIX "./.." (PATH) Path where you want to generate the FreeCAD.app bundle.
FREECAD_USE_EXTERNAL_KDL 1 (BOOL) Required.
BUILD_FEM_NETGEN 1 (BOOL) Required if choosing to build the FEM tools.

Note: Command line to generate CMAKE_PREFIX_PATH:

ls -d $(brew list -1 | grep qt | tail -1 | xargs brew --cellar)/*/lib/cmake

CMake GUI

Open the CMake app, and fill in the source and build folder fields. In this example, it would be /Users/username/FreeCAD/FreeCAD-git for the source, and /Users/username/FreeCAD/build for the build folder.

Next, click the Configure button to populate the list of configuration options. This will display a dialog asking you to specify what generator to use. Leave it at the default Unix Makefiles. Configuring will fail the first time because there are some options that need to be changed. Note: You will need to check the Advanced checkbox to get all of the options.

Set options from the table above, then click Configure again and then Generate.

CMake command line

Enter the following in the terminal.

export PREFIX_PATH="/usr/local/opt/qt5152;\
/usr/local/Cellar/nglib/v6.2.2007/Contents/Resources;\
/usr/local/Cellar/vtk@8.2/8.2.0_1/lib/cmake;"
$cd ~/FreeCAD/build
$cmake \
  -DCMAKE_BUILD_TYPE="Release"   \
  -DBUILD_QT5=1                  \
  -DWITH_PYTHON3=1               \
  -DCMAKE_PREFIX_PATH="$PREFIX_PATH" \
  -DPYTHON_EXECUTABLE="/usr/local/bin/python3" \
  -DFREECAD_USE_EXTERNAL_KDL=1   \
  -DCMAKE_CXX_FLAGS='-std=c++14' \
  -DBUILD_FEM_NETGEN=1           \
  -DFREECAD_CREATE_MAC_APP=1     \
  -DCMAKE_INSTALL_PREFIX="./.."  \
  ../FreeCAD-git/

Run make

Finally, from a terminal run make to compile and link FreeCAD, and generate the app bundle.

cd ~/FreeCAD/build
make -j5 install

The -j option specifies how many make processes to run at once. One plus the number of CPU cores is usually a good number to use. However, if compiling fails for some reason, it is useful to rerun make without the -j option, so that you can see exactly where the error occurred.

See also Compiling - Speeding up.

If make finishes without any errors, you can now launch FreeCAD by double clicking the executable in the Finder.

Updating from Github

FreeCAD development happens fast; every day or so there are bug fixes or new features. To get the latest changes, use git to update the source directory (see Source code management), then re-run the CMake and make steps above. It is not usually necessary to start with a clean build directory in this case, and subsequent compiles will generally go much faster than the first one.

Building with Qt4 and Python 2.7

FreeCAD has transitioned from Qt 4 to Qt 5 as well as homebrew. Qt 4 is no longer available as an option for new build on macOS following Qt 5 transition. Python 2.7 has been deprecated within homebrew and upcoming macOS and we do not support it anymore for macOS build either.

Troubleshooting

Segfault on Qt5 launch

If Qt4 was previously installed via brew, and you then build with Qt5, you may get a EXC_BAD_ACCESS (SEGSEGV) exception when launching the new Qt5 build. The fix for this is to manually uninstall Qt4.

brew uninstall --ignore-dependencies --force cartr/qt4/shiboken@1.2 cartr/qt4/pyside@1.2 cartr/qt4/pyside-tools@1.2 cartr/qt4/qt-legacy-formula

Fortran

"No CMAKE_Fortran_COMPILER could be found." during configuration - Older versions of FreeCAD will need a fortran compiler installed. With Homebrew, do "brew install gcc" and try configuring again, giving cmake the path to Fortran ie -DCMAKE_Fortran_COMPILER=/opt/local/bin/gfortran-mp-4.9 . Or, preferably use a more current version of FreeCAD source!

FreeType

When using CMake versions older than 3.1.0, it's necessary to set CMake variable FREETYPE_INCLUDE_DIR_freetype2 manually, eg /usr/local/include/freetype2

Additional Build Instructions

FreeCAD can be built against the latest git master hosted on github, and launched from a CLI using libraries provided by the homebrew-freecad tap. For a complete list of build instructions see here.


Resumen

Estas son bibliotecas que FreeCAD utiliza como dependencias de terceros durante la compilación. Normalmente son bibliotecas enlazadas dinámicamente y tienen una extensión .so en Linux/MacOS y .dll en Windows, y van acompañadas de sus archivos de cabecera .h o .hpp o similares. Si se necesita una biblioteca modificada, o una clase envolvente, el código de la biblioteca modificada, o la envolvente, tiene que formar parte del código fuente de FreeCAD, y compilarse junto con él.

Las dependencias deben ser instaladas en el sistema antes de proceder a la compilación; ver compilar en Linux, compilar en Windows, y compilar en MacOS para más información.

Si está compilando con Windows, considere usar el LibPack en lugar de intentar instalar las bibliotecas individualmente.

Enlaces

Nombre biblioteca Versión necesaria Enlace para obtenerla
Python >= 3.6 http://www.python.org/
Boost >= 1.33 http://www.boost.org/
OpenCASCADE >= 7.3 http://www.opencascade.org
Qt >= 5.4 https://www.qt.io/
Shiboken2 same as Qt https://wiki.qt.io/Qt_for_Python/Shiboken
PySide2 same as Qt https://wiki.qt.io/Qt_for_Python/Shiboken
Coin3D >= 3.x https://github.com/coin3d/coin
SoQt (deprecated) >= 1.2 https://github.com/coin3d/soqt
Quarter >= 1.0 https://github.com/coin3d/quarter
Pivy >= 0.6.5 https://github.com/coin3d/pivy/
FreeType >= XXX XXX
PyCXX >= XXX XXX
KDL >= XXX XXX
Point Cloud Library >= XXX XXX
Salome SMESH >= XXX XXX
VTK >= 6.0 XXX
Ply >= 3.11 https://www.dabeaz.com/ply/
Xerces-C++ >= 3.0 https://xerces.apache.org/xerces-c/
Eigen3 >= 3.0 http://eigen.tuxfamily.org/index.php?title=Main_Page
Zipios++ >= 0.1.5 https://snapwebsites.org/project/zipios, https://github.com/Zipios/Zipios
Zlib >= 1.0 http://www.zlib.net/, https://github.com/madler/zlib
libarea >= 0.0.20140514-1 https://github.com/danielfalck/libarea

Detalles

Python

Versión: 3.3 o superior

Licencia: Python 3.3 licencia

Python 2 quedó obsoleto en 2019. El futuro desarrollo de FreeCAD utilizará exclusivamente Python 3; no se probará la compatibilidad con Python 2, por lo que los antiguos ambientes de trabajo y macros que utilizan esta versión tendrán que ser actualizados o pueden dejar de funcionar. Por favor, publica en el foro de FreeCAD si encuentras problemas con Python 3.

Python es un popular lenguaje de guionización multipropósito que es ampliamente utilizado en Linux y en el software de código abierto. En FreeCAD, Python se utiliza durante la compilación y también en tiempo de ejecución de diferentes maneras. Se utiliza

  • para escribir guiónes de prueba para comprobar diferentes condiciones, como fugas de memoria, para asegurar la funcionalidad del software después de los cambios, para las comprobaciones posteriores a la compilación, y las pruebas de cobertura,
  • para escribir macros y grabación de macros,
  • para implementar la lógica de la aplicación para los paquetes estándar,
  • para implementar herramientas auxiliares como el Gestor Complementos,
  • para implementar bancos de trabajo completos como Borrador y Arquitectura,
  • para cargar dinámicamente paquetes,
  • para implementar reglas de diseño (ingeniería del conocimiento),
  • para hacer interacciones de lujo en Internet como grupos de trabajo y PDM

En Linux, Python suele estar ya instalado en tu distribución. Para Windows puedes obtener un binario precompilado de Python.org o utilizar ActiveState Python, aunque es más difícil obtener las librerías de depuración de esta última.

Python fue elegido como el lenguaje de guionización para FreeCAD por diferentes razones:

  • Es más orientado a objetos que Perl y Tcl.
  • El código es más legible que Perl y Visual Basic.
  • Es más fácil de incrustar en otra aplicación, a diferencia de, por ejemplo, Java.

En sinopsis, Python está bien documentado y es fácil de integrar y extender en una aplicación C++. También está bien probado y tiene un fuerte apoyo de la comunidad de código abierto. Lee más sobre Python y explora la documentación oficial en Python.org.

Boost

Versión: 1.33 o superior

Licencia: Boost Software Licencia - Versión 1.0

Las bibliotecas Boost C++ son colecciones de bibliotecas de código abierto revisadas por pares que amplían la funcionalidad de C++. Están pensadas para ser ampliamente útiles en un amplio espectro de aplicaciones, y para funcionar bien con la biblioteca estándar de C++. La licencia de Boost está diseñada para fomentar su uso tanto en proyectos de código abierto como de código cerrado.

Due to their popularity and stability, many Boost libraries have been accepted for incorporation into the C++11 standard, and more are planned for inclusion in subsequent C++ standards.

En orden de asegurar la eficiencia y flexibilidad, Boost hace un uso extensivo de las plantillas. Boost ha sido una fuente de trabajo extensivo e investigación en programación general y meta-programación en C++. Para saber más sobre Boost, visite la página Boost página inicio.

OpenCASCADE Tecnología

Versión: 6.7 o superior

Licencia: versión 6.7.0 y posteriores se rigen por la Licencia Pública General Reducida de GNU (LGPL) versión 2.1 con una excepción adicional. Las versiones anteriores utilizan la Open CASCADE Licencia pública tecnológica.

La tecnología OpenCASCADE (OCCT) es un kernel CAD profesional con todas las funciones. Fue desarrollado en 1993 y originalmente llamado CAS.CADE, por Matra Datavision en Francia para las aplicaciones Strim (Styler) y Euclid Quantum. En 1999 se publicó como software de código abierto, y desde entonces se llama OpenCASCADE.

OCCT is a big and complex set of C++ libraries that provide functionality required by a CAD application:

  • A complete STEP compliant geometry kernel.
  • A topological data model and needed functions to work with shapes (cut, fuse, extrude, and many others).
  • Standard import and export processors for files like STEP, IGES, VRML.
  • A 2D and 3D viewer with selection support.
  • A document and project data structure with support for save and restore, external linking of documents, recalculation of design history (parametric modeling) and a facility to load new data types as an extension package dynamically.

There are two main versions of OpenCASCADE in existence in different Linux distributions. One is distributed by the original developers; it is known as OCCT, and is packaged under the names occ or occt. The other version is the "community edition", abbreviated OCE, and is normally found with the oce name. FreeCAD can compile against either version, however, since 2016 FreeCAD recommends compiling against the official OCCT libraries rather than the OCE ones. The reason is that the community edition lacks important bug fixes and functions that make using FreeCAD better.

Para obtener más información, visite el OpenCASCADE sitio web.

Qt

Versión: 4.1 o superior

Licencia: GPL v2.0/v3.0 o Comercial; desde versión 4.5 también en LPGL v2.1.

Qt es uno de los juegos de herramientas de interfaz gráfica de usuario (GUI) más populares disponibles en el mundo del código abierto. FreeCAD utiliza este kit de herramientas para dibujar la interfaz del programa. Para ello, la aplicación Qt Designer es muy útil, ya que permite a los desarrolladores dibujar rápidamente los diálogos y ventanas, exportarlos como archivos de recursos XML, y luego cargar estas interfaces en tiempo de ejecución.

Further information about Qt libraries and their programming documentation are available at Qt Documentation.

Shiboken2 and Pyside2

Shiboken is the Python binding generator that Qt for Python uses to create the PySide module, in other words, it is the system that is used to expose the Qt C++ API to the Python language.

The original Shiboken and PySide packages were meant to be used with Python 2 and Qt4; since these two versions are considered obsolete in 2019, please use Shiboken2 and PySide2, which work with Python 3 and Qt5. New development of FreeCAD is done with Python 3 and Qt5, so compatibility with Python 2 and Qt4 is not guaranteed after FreeCAD 0.18.

Read more about Shiboken and Pyside on Qt for Python.

Coin3D

Versión: 3.0 o superior

Licencia: Licencia BSD de 3 cláusulas

Coin3D es una biblioteca de gráficos 3D de alto nivel con una interfaz de programación de aplicaciones C++. Utiliza estructuras de datos scenegraph para renderizar gráficos en tiempo real adecuados para todo tipo de aplicaciones de visualización científica y de ingeniería.

Coin3D se basa en la biblioteca de renderizado de modo inmediato OpenGL, estándar industrial, y añade abstracciones para primitivas de nivel superior, proporciona interactividad 3D y contiene muchas funciones de optimización complejas para un renderizado rápido y transparente para el programador de la aplicación.

Coin3D es compatible con la API Open Inventor 2.1 de SGI. Esta API se ha convertido en la interfaz gráfica estándar de facto para la visualización 3D en la comunidad científica y de ingeniería. Desde el año 2000 ha demostrado su valía como elemento fundamental en miles de aplicaciones de ingeniería de todo el mundo.

Coin3D (Open Inventor) se utiliza como visor 3D en FreeCAD porque el visor de OpenCASCADE (AIS y Graphics3D) tiene limitaciones y cuellos de botella en el rendimiento, especialmente con el renderizado de ingeniería a gran escala; otras cosas como las texturas o el renderizado volumétrico no son totalmente compatibles con el visor de OpenCASCADE.

Coin3D es portátil en una amplia gama de plataformas: Sistemas operativos UNIX, Linux, BSD, MacOS X y Microsoft Windows. Para obtener más información sobre esta biblioteca, visite Coin3D página de inicio.

SoQt (obsoleto)

Versión: 1.2.0 o superior

Licencia: Licencia BSD de 3 cláusulas

SoQt es el enlace de Coin3D (Open Inventor) con el juego de herramientas de interfaz gráfica de usuario Qt.

SoQt is no longer used in FreeCAD, it was replaced by Quarter which is a more recent Qt binding.

Quarter

Versión: 1.0 o superior

Licencia: Licencia BSD de 3 cláusulas

Quarter is a newer Coin3D binding to the Qt toolkit. A version of it is included in the source code of FreeCAD so it is compiled together with it.

Pivy

Versión: 0.6.3 o superior

Licencia: Licencia BSD de 3 cláusulas

Pivy is a library that wraps the Coin3d library for use in Python. It is not needed to build FreeCAD or to start it, but it is needed as a runtime dependency by the Draft Workbench, and by other workbenches that use it internally, like Arch and BIM.

If you are not going to use these workbenches, you won't need Pivy.

Ply

Versión: 3.11 o superior

Licencia: Licencia BSD de 3 cláusulas

Ply is the Python-Lex-Yacc parser. It is used as a runtime dependency by the OpenSCAD Workbench. If you don't use this workbench, you may not need this package.

For more information see Ply homepage

Xerces-C++

Versión: 3.0 o superior

Licencia: Apache Software Licencia Versión 2.0

Xerces-C++ es un analizador sintáctico XML de validación escrito en un subconjunto portátil de C++. Xerces-C++ hace que sea fácil dar a su aplicación la capacidad de leer y escribir datos XML. Se proporciona una biblioteca compartida para analizar, generar, manipular y validar documentos XML. Xerces-C++ es fiel a la recomendación XML 1.0 y a los estándares asociados.

El analizador sintáctico se utiliza para guardar y restaurar parámetros en FreeCAD. Para más información, consulte Página de inicio de Xerces-C++.

Eigen3

Versión: 3.0 o superior

License: Starting from the 3.1.1 version, it is licensed under the Mozilla Public License 2.0. Earlier versions were licensed under the GNU Lesser General Public License 3.

Eigen is a C++ template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms.

If you just want to use Eigen, you can use the header files right away. There is no binary library to link to, and no configured header file. Eigen is a pure template library defined in the headers.

Eigen is used in FreeCAD for many vector operations in 3D space. To learn more, visit Eigen homepage.

Zipios++

Versión: 0.1.5 o superior

Licencia: Licencia Pública General Reducida de GNU 2.1

Zipios++ is a C++ library for reading and writing .zip files. Access to individual entries is provided through standard C++ iostreams. A simple read-only virtual file system that mounts regular directories and .zip files is also provided. The structure and public interface of Zipios++ are loosely based on the java.util.zip package of Java.

FreeCAD's native file format .FCstd is in reality a .zip file that stores and compresses other types of data within it, such as BREP and XML files. Therefore, Zipios++ is used to save and open compressed archives, including FreeCAD files.

A copy of Zipios++ is included in the source code of FreeCAD so it is compiled together with it. If you want to use an external Zipios++ library, provided by your operating system, you may set -DFREECAD_USE_EXTERNAL_ZIPIOS=ON with cmake.

Zipios++ uses the Zlib library to perform the actual decompression of files.

Zlib

Versión: 1.0 o superior

Licencia: zlib licencia

Zlib está diseñado para ser una biblioteca de compresión de datos gratuita, de propósito general y sin pérdidas, para su uso en cualquier hardware y sistema operativo. Implementa el algoritmo de compresión DEFLATE comúnmente utilizado en los archivos .zip y .gzip.

A copy of this library is included in the source code of FreeCAD so it is compiled together with it.

libarea

Version: 0.0.20140514-1 or higher

Licencia: Licencia BSD de 3 cláusulas

Libarea is a software library to compute profile and pocket operations which are used in computer aided manufacturing (CAM) software. It was created by Dan Heeks for his HeeksCNC project.

A copy of the library is included with the source code of the Path Workbench, so it is compiled together with it.

LibPack

LibPack es un conveniente paquete con las dependencias de compilación de FreeCAD reunidas. Sólo es necesario si estás compilando FreeCAD en Windows con Visual Studio 2015 y superior. Puedes encontrar el último LibPack en la página releases.

Si estás trabajando bajo Linux, no necesitas el LibPack, ya que puedes obtener las dependencias de los repositorios de tu distribución como se menciona en la página compilar en Linux.

FreeCAD 12.1.2

See the announcement in the forum: New libpacks for Windows with Qt5.12, OCC7.3 and Python 3.6 by apeltauer

It includes among other things: Boost 1.67, Coin3D 4.0.0a, Eigen3, Open CASCADE Technology 7.3.0, Python 3.6.8, PySide2, Qt 5.12.1, Salome SMESH, Shiboken2, vtk7, Xerces-C, Zipios++, zlib 1.2.11



Página Herramienta

Para todo desarrollo de software serio se necesitan herramientas. Aquí hay una lista de herramientas que usamos para desarrollar FreeCAD:

Herramientas independientes de la plataforma

Qt-juego de herramientas

El Qt-juego de herramientas es una herramienta de diseño de interfaces de usuario de última generación e independiente de la plataforma. Está contenido en el LibPack de FreeCAD, pero también puede descargarse en Qt proyecto.

Inkscape

Este es un gran programa de dibujo vectorial. Se adhiere al estándar SVG y se utiliza para dibujar iconos e imágenes. Inkscape es un software libre y de código abierto con licencia GPL. Consíguelo en www.inkscape.org.

Doxygen

Una herramienta muy buena y estable para generar documentación del codigo a partir de los archivos .h y .cpp.

Gimp

No hay mucho que decir sobre el programa de manipulación de imágenes de GNU. Además de que puede manejar archivos .xpm que es un modo muy conveniente de manejar iconos en los programas de QT. XPM es básicamente código en C que puede compilarse en un programa.

Consigue GIMP aquí: www.gimp.org

Gitkraken

This is a proprietary git GUI that is very helpful to learn how git works if you're interested in wanting to contribute to FreeCAD. Relevant pages to research:

OBS Studio

Software libre y de código abierto para la grabación de vídeo y la transmisión en directo. Más detalles en el sitio web oficial : obsproject.com

OpenCamLib

OpenCamLib/es (OCL) es una biblioteca de código abierto cuyo objetivo es proporcionar algoritmos de fabricación asistida por ordenador (CAM). FreeCAD utiliza OCL en las operaciones experimentales de trazado de superficies en 3D y otras características experimentales.

StarUML

Un programa UML de código libre lleno de características. Tiene un montón de características de las grandes, incluyendo ingeniería inversa del código fuente C++.

Descargalo aquí: staruml.io

Herramientas en Windows

Visual Studio Community

Visual Studio Comunidad es gratuito para proyectos de código abierto y pequeñas estructuras. La instalación es modular. Puedes añadir soporte para un gran número de lenguajes, incluyendo C++ y Python.

Puede descargarse en [3]

CamStudio

Es una herramienta Open Source para grabar Screen-casts (Webcasts). Es una muy buena herramienta para crear tutoriales grabándolos. No es tan aburrido como escribir documentación.

Mira camstudio.org para más detalles.

Herramientas en Linux

PENDIENTE



In FreeCAD version 0.20 the default location of the program's configuration, data and cache files was changed for Linux.
See Release notes 0.20 for more information. This page has not yet been updated accordingly.

Overview

Vista general

Esta página muestra las diferentes formas de iniciar FreeCAD y las características de configuración más importantes.

Iniciando FreeCAD desde la línea de comandos

FreeCAD puede iniciarse normalmente, haciendo doble clic en el icono del escritorio o seleccionándolo en el menú de inicio, pero también sr puede iniciar directamente desde la línea de comandos. Esto te permite cambiar algunos de las opciones por defecto de inicio.

Using command line options without a command line shell

Usar las opciones de la línea de comandos sin un shell de línea de comandos

  • En Ubuntu puedes crear un icono de escritorio y editar sus propiedades. Añade las opciones de la línea de comandos separadas por espacios detrás del nombre del programa en el campo "Comando".
  • En Windows crea un acceso directo y edita las propiedades. Añade las opciones de la línea de comandos separadas por espacios en el campo "Objetivo".

Opciones de la línea de comandos

Las opciones de la línea de comandos están sujetas a cambios frecuentes, por lo que es conveniente comprobar las opciones actuales escribiendo:

FreeCAD --help

En la respuesta puedes leer los posibles parámetros:

 Usage: FreeCAD [options] File1 File2 ...
 
 Allowed options:
 
 Generic options:
   -v [ --version ]          Prints version string
   -h [ --help ]             Prints help message
   -c [ --console ]          Starts in console mode
   --response-file arg       Can be specified with '@name', too
   --dump-config             Dumps configuration
   --get-config arg          Prints the value of the requested configuration key
 
 Configuration:
   -l [ --write-log ]        Writes a log file to:
                             /home/username/.FreeCAD/FreeCAD.log
   --log-file arg            Unlike --write-log this allows logging to an 
                             arbitrary file
   -u [ --user-cfg ] arg     User config file to load/save user settings
   -s [ --system-cfg ] arg   System config file to load/save system settings
   -t [ --run-test ] arg     Test case - or 0 for all
   -M [ --module-path ] arg  Additional module paths
   -P [ --python-path ] arg  Additional python paths
   --single-instance         Allow to run a single instance of the application

In the following table, selected options are described in more detail:

Long option Corresponding config var name Synopsis
--user-cfg <filename> UserParameter Filename or relative path that ends with a filename. Defaults to user.cfg.
--module-path <dir> Prepends to AdditionalModulePaths Directory that contains modules. This option can be given repeatedly to specify multiple directories.
--get-config <config-var-name> most Outputs the requested value in a popup dialog. Exits upon confirmation with OK. Cannot be used repeatedly. If an unknown/illegal variable name is used, the response is empty. The --console flag is not honored.

Options can written in two forms: --long-option arg and --long-option=arg.

Respuesta y archivos de configuración

FreeCAD puede leer algunas de estas opciones desde un archivo de configuración. Este archivo debe estar en la ruta de la papelera y debe llamarse FreeCAD.cfg. Tenga en cuenta que las opciones especificadas en la línea de comandos anulan el archivo de configuración.

Algunos sistemas operativos tienen límites de longitud muy bajos para la línea de comandos. El modo más habitual de evitar esas limitaciones es utilizar un archivo de respuesta. Un archivo de respuesta es simplemente un archivo de configuración que utiliza la misma sintaxis que la línea de comandos. Si la línea de comandos especifica un nombre de archivo de respuesta a utilizar, es cargado y analizado sintáticamente en adición a la línea de comandos:

FreeCAD @ResponseFile.txt 

o:

FreeCAD --response-file=ResponseFile.txt

or:

FreeCAD --response-file ResponseFile.txt

Opciones ocultas

Existen varias opciones no visibles por el usuario. Estas opciones son por ejemplo los parámetros de X-Window analizados por el sistema Windows:

  • -display display, establece la visualización de X (por defecto es $DISPLAY).
  • -geometry geometry, establece la geometría cliente de la primera ventana que es mostrada.
  • -fn or -font font, Define la fuente de letra de la aplicación. La fuente de letra debería estar especificada utilizando una descripción de fuente lógica de X.
  • -bg or -background color, establece el color de fondo por defectoy una paleta para la aplicación (se calculan las sombras iluminadas y oscuras).
  • -fg or -foreground color, establece el color de primer planor.
  • -btn or -button color, establece el color por defecto de los botones.
  • -name name, establece el nombre de la aplicación.
  • -title title, establece el título de la aplicación.
  • -visual TrueColor, fuerza a la aplicación a utilizar la visualización TrueColor en una visualización de 8-bit.
  • -ncols count, limita el número de colores asignados en el cubo de color de visualización de 8-bit, si la aplicación está utilizando la especificación del color QApplication::ManyColor. Si el computo es 216 entonces se utiliza un cubo de color de 6x6x6 (por ejemplo 6 niveles de rojo, 6 de verde y 6 de azul); para otros valores, se utiliza un cubo aproximadamente proporcional a un cubo de 2x3x1.
  • -cmap, cause que la aplicación instale un mapa de color privado en una visualización de 8-bit.

Ejecución de FreeCAD sin interfaz de usuario

FreeCAD normalmente se inicia en el modo de interfaz de usuario gráfico GUI, pero puedes forzar que inicie en modo consola escribiendo:

FreeCAD --console

desde la línea de comandos. En el modo consola, no se mostrará el interfaz de usuario, y tendrás presente la consola del interprete de Python. Desde ella tienes la misma funcionalidad que desde el interprete de Python que se ejecuta dentro del interfaz de usuario gráfico GUI de FreeCAD, y acceso normal a todos los módulos y plugins de FreeCAD, exceptuando el módulo FreeCADGui. Ten en cuenta que los módulos que dependan del FreeCADGui podrían tampoco estar disponibles.

To read more about console or headless mode, refer to Headless FreeCAD.

Running modules, macros and scripts

File type System Command line example
Module Windows "C:\Program Files\FreeCAD\bin\FreeCAD.exe" -M "C:\FreeCAD\Mod\Draft"
Linux FreeCAD_0.19 -M ~/.FreeCAD/Mod/Draft
Linux (AppImage) path/to/FreeCADXXX.AppImage -M ~/.FreeCAD/Mod/Draft
.FCMacro or .py Windows "C:\Program Files\FreeCAD\bin\FreeCAD.exe" "C:\Users\userName\AppData\Roaming\FreeCAD\Mod\WorkFeature\start_WF.FCMacro"
Linux FreeCAD_0.19 ~/.FreeCAD/Mod/WorkFeature/start_WF.FCMacro
Linux (AppImage) path/to/FreeCADXXX.AppImage ~/.FreeCAD/Mod/WorkFeature/start_WF.FCMacro

See Macro at Startup on how to set up a macro to automatically run at FreeCAD startup.

Environment variables

FreeCAD supports the following environment variables, which can be used to configure directories: introduced in version 0.19

Environment variable Corresponding config var name Synopsis
FREECAD_USER_HOME UserHomePath FreeCAD's "base" directory for keeping local user data.
FREECAD_USER_DATA UserAppData If not set, defaults to FREECAD_USER_HOME/.FreeCAD, but only if FREECAD_USER_HOME is set.
FREECAD_USER_TEMP AppTempPath If not set, defaults to FREECAD_USER_HOME/temp, but only if FREECAD_USER_HOME is set.

If the specified path does not exist, the setting is ignored!

The above environment variables are meant to be used to realize a portable FreeCAD environment. For an example how environment variables can be used from the command line on Linux refer to the notes for Linux users on the downloads page.

HOME

FreeCAD uses Qt, which does honor the HOME environmental variable. Thus, setting HOME can be used to specify the base directory of Qt-related configuration files (.config/FreeCAD/FreeCAD.conf).

FreeCad itself does not honor the HOME environmental variable (because it determines the user's home directory from a lower-level system API). Use FREECAD_USER_HOME for this pupose.

TMPDIR

The default temporary directory is /tmp/. The TMPDIR environmental variable can be used to override the default. (Editor: precedence?).

Libraries

Algunas bibliotecas necesitan llamar a variables de entorno del sistema. A veces cuando existe un problema con una instalación de FreeCAD, es porque algunas variables de entorno no están o se han definido mal. Por tanto, algunas variables importantes son duplicadas en la Configuración y guardadas en el archivo de registro.

Variables de entorno relativas a Python:

  • PYTHONPATH
  • PYTHONHOME
  • TCL_LIBRARY
  • TCLLIBPATH

Variables de entorno relativas a OpenCascade:

  • CSF_MDTVFontDirectory
  • CSF_MDTVTexturesDirectory
  • CSF_UnitsDefinition
  • CSF_UnitsLexicon
  • CSF_StandardDefaults
  • CSF_PluginDefaults
  • CSF_LANGUAGE
  • CSF_SHMessage
  • CSF_XCAFDefaults
  • CSF_GraphicShr
  • CSF_IGESDefaults
  • CSF_STEPDefaults

El conjunto de configuración

En cada inicio FreeCAD examina sus alrededores y los parámetros de la línea de comandos. Esto construye un conjunto de configuración que guarda la esencia de toda la información de la ejecución. Esta información es después utilizada para determinar la ubicación donde guardar los datos del usuario o archivos de registro. También es muy importante para los análisis postmortem. Por lo tanto es guardado en el archivo de registro.

Información relativa al usuario

Entradas de configuración de usuario
Nombre variable configuración Sinopsis Ejemplo M$ Ejemplo Posix (Linux)
UserAppData Ruta donde FreeCAD almacena los datos de la aplicación relativos al usuario. C:\Documents and Settings\username\Application Data\FreeCAD /home/username/.FreeCAD
UserParameter Archivo donde FreeCAD almacena los datos de la aplicación relativos al usuario. C:\Documents and Settings\username\Application Data\FreeCAD\user.cfg /home/username/.FreeCAD/user.cfg
SystemParameter Archivo donde FreeCAD almacena datos relativos a la aplicación. C:\Documents and Settings\username\Application Data\FreeCAD\system.cfg /home/username/.FreeCAD/system.cfg
UserHomePath Ruta de la carpeta de inicio del usuario actual C:\Documents and Settings\username\My Documents /home/username

Note: For Linux distributions, an additional configuration file that relates to Qt may exist at path /home/username/.config/FreeCAD/FreeCAD.conf.

Argumentos de la línea de comando

Entradas de configuración de usuario
Nombre variable configuración Sinopsis Ejemplo
LoggingFile 1 si el logging está activado 1
LoggingFileName Nombre de archivo en el que está ubicado el registro C:\Documents and Settings\username\Application Data\FreeCAD\FreeCAD.log
RunMode Esto indica como funcionará el bucle principal. "Script" significa que el archivo de guión dado se llamará y luego se saldrá. "Cmd" ejecuta el interprete de la línea de comandos. "Internal" ejecuta un archivo de guión interno. "Gui" introduce el bucle de eventos de la interfaz de usuario gráfica GUI. "Module" carga un módulo de Python dado. "Cmd"
FileName Su significado depende del modo de ejecución
ScriptFileName Su significado depende del modo de ejecución
Verbose Nivel de verborrea de FreeCAD "" o "strict"
OpenFileCount Mantiene el número de archivos abiertos a través de argumentos de la línea de comandos "12"
AdditionalModulePaths Mantiene las rutas de módulos adicionales dados en la línea de comandos "extraModules/"

Relativos al sistema

Entradas de configuración de usuario
Nombre variable configuración Sinopsis Ejemplo M$ Ejemplo Posix (Linux)
AppHomePath c:/Progam Files/FreeCAD_0.7 /user/local/FreeCAD_0.7
PythonSearchPath Mantiene una lista de las rutas en las cuales Python busca módulos. Esto es al inicio se puede cambiar durante la ejecución

Información relativa a la construcción

La tabla de abajo muestra la información disponible sobre la versión de construcción. La mayoría proviene del repositorio de Subversion. Esto es necesario para reconstruir exactamente una versión!

Entradas de configuración de usuario
Nombre variable configuración Sinopsis Ejemplo
BuildVersionMajor Número de versión principal de la construcción. Definida en src/Build/Version.h.in 0
BuildVersionMinor Número de versión secundario de la construcción. Definida en src/Build/Version.h.in 7
BuildRevision Número de revisión del repositorio SVN del src en la construcción. Generado por SVN 356
BuildRevisionRange Rango de diferentes cambios 123-356
BuildRepositoryURL URL del repositorio https://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk/src
BuildRevisionDate Fecha de la revisión de arriba 2007/02/03 22:21:18
BuildScrClean Indica si el código fuente fue modificado después de su descarga Src modified
BuildScrMixed Src not mixed

Relativos al marcado

Estas entradas de configuración son relativas al mecanismo de marcado de FreeCAD. Mira Marcado para más detalles.

Entradas de configuración de usuario
Nombre variable configuración Sinopsis Ejemplo
ExeName Nombre del archivo ejecutable de la construcción. Puede diferir de la de FreeCAD si es utilizado un main.cpp diferente. FreeCAD.exe
ExeVersion Versión global mostrada al inicio V0.7
AppIcon Icono que es utilizado por el ejecutable, mostrado en Application MainWindow. "FCIcon"
ConsoleBanner Banner que es mostrado en modo consola
SplashPicture Nombre del icono utilizado por la pantalla de bienvenida "FreeCADSplasher"
SplashAlignment Alineación del texto en el letrero de diálogo de bienvenida Left"
SplashTextColor Color del texto de bienvenida "#000000"
StartWorkbench Nombre del entorno que comenzará automáticamente después del inicio "Part design"
HiddenDockWindow Lista de dockwindows (separadas por un punto y coma) que serán mostradas "Property editor"

Querying the configuration

From FreeCAD's Python console

Entries of the configuration set can be queried with the config var name (see tables above) from the Python console. For example:

 >>> FreeCAD.ConfigGet("ExeVersion")
 '0.19'

If the name is not found, an empty string is returned.

From command line

Use the --get-config <config-var-name> option to query a single name. Not all names are supported. For example:

 FreeCAD --get-config ExeVersion

Use the --dump-config option to get a list of names and their values. Not all names are supported.

From FreeCAD console

Start FreeCAD in console mode with --console and query with Python code. For example:

 $ FreeCAD --console
 [FreeCAD Console mode <Use Ctrl-D (i.e. EOF) to exit.>]
 >>> FreeCAD.ConfigGet("ExeVersion")
 '0.19'
 >>> exit()

For Linux (bash shell) you can modify the following command line to suit your needs:

 $ FreeCAD --console <<EOF
 print( "FREECAD_USER_HOME: " + ( "not set" if ( os.environ.get('FREECAD_USER_HOME') is None ) else os.environ.get('FREECAD_USER_HOME') ) )
 print( "UserHomePath: " + FreeCAD.ConfigGet("UserHomePath") )
 exit()
 EOF

Starting FreeCAD from the desktop

Linux: Creating an additional start option

The following assumes that your desktop is configured such that you can launch FreeCAD from it. Depending on your Linux distribution and desktop environment, you may have to adapt the following steps:

  1. Copy the freedesktop entry file for FreeCAD from /usr/share/applications/freecad.desktop to ~/.local/share/applications.
  2. Change the name from freecad.desktop to something else (e.g. MyFreeCADConfig.desktop).
  3. Open the file with a text editor and change how FreeCAD is invoked by modifying the line starting with Exec.
  4. As a result, an additional entry in your start menu/application launcher is available. This way, you can have multiple FreeCAD entries with various launch options.

Starting FreeCAD from a portable USB medium

Windows

Put the FreeCAD executable, FreeCAD.exe, on the USB medium. Create a batch file, FreeCAD.bat, and put it into the same directory as FreeCAD.exe. Inside the batch file write:

set CURRENTDIR=%cd%
set FREECAD_USER_HOME=%CURRENTDIR%
start FreeCAD.exe -u FreeCAD/user.cfg -s FreeCAD/system.cfg --write-log

Or with FREECAD_USER_DATA (see):

set CURRENTDIR="%cd%"
set FREECAD_USER_DATA=%CURRENTDIR%/..
start FreeCAD.exe -u %FREECAD_USER_DATA%/user.cfg -s %FREECAD_USER_DATA%/system.cfg

With the batch in the root of the USB medium:

set CURRENTDIR=%cd%
set FREECAD_USER_DATA=%CURRENTDIR%FreeCAD\
start %cd%FreeCAD\bin\FreeCAD.exe -u %FREECAD_USER_DATA%user.cfg -s %FREECAD_USER_DATA%system.cfg

Now double-click the batch file to start FreeCAD. (see)


Third Party Tools/es
FreeCAD Build Tool/es

Build Support Tools/es


La Utilidad de construcción de FreeCAD (FreeCAD build tool o fcbt) es un archivo de guión en Python ubicado en

trunc/src/Tools/fcbt.py

Se puede utilizar para simplificar algunas tareas frecuentes de construcción, distribución y extensión de FreeCAD.

Utilización

Con Python correctamente instalado, fcbt se puede invocar por el comando

python fbct.py

Muestra un menú, donde puedes seleccionar la tarea para el que lo quieres utilizar:

FreeCAD Build Tool
 Usage:
    fcbt <command name> [command parameter]
 possible commands are:
  - DistSrc         (DS)   Build a source Distr. of the current source tree
  - DistBin         (DB)   Build a binary Distr. of the current source tree
  - DistSetup       (DI)   Build a Setup Distr. of the current source tree
  - DistSetup       (DUI)  Build a User Setup Distr. of the current source tree
  - DistAll         (DA)   Run all three above modules
  - NextBuildNumber (NBN)  Increase the Build Number of this Version
  - CreateModule    (CM)   Insert a new FreeCAD Module (Workbench) in the module directory
 
 For help on the modules type:
   fcbt <command name> ?

Introduce el nombre abreviado del comando que quieres utilizar. Por ejemplo escribe "CM" para crear un módulo.

DistSrc

El comando "DS" crea un distribución de código fuente del árbol de código fuente actual.

DistBin

El comando "DB" crea una distribución binaria del árbol de código fuente actual.

DistSetup

El comando "DI" crea una distribución de setup del árbol de código fuente actual.

DistSetup

El comando "DUI" crea una distribución de setup de usuario del árbol de código fuente actual.

DistAll

El comando "DA" executes "DS", "DB" y "DI" en secuencia.

NextBuildNumber

El comando "NBN" incrementa el número de la construcción para crear una nueva versión de FreeCAD.

CreateModule

El comando "CM" crea un nuevo módulo de aplicación.


Start up and Configuration/es
Module Creation/es


Introduction

This page will show you how to add a new workbench to the FreeCAD interface. Workbenches are containers for FreeCAD commands. They can be coded in Python, in C++, or in a mix of both, which has the advantage to ally the speed of C++ to the flexibility of Python. In all cases, though, your workbench will be launched by a set of two Python files. They can be "internal" workbenches, included with FreeCAD's distribution, or "external" workbenches, distributed via the Addon Manager or installed manually by downloading from some online repository. Internal workbenches may be coded in either C++, Python, or a combination of the two, whereas external workbenches must be Python-only.

The workbench structure

You need a folder, with any name you like, placed in the user Mod directory, with an Init.py file, and, optionally an InitGui.py file. The Init file is executed when FreeCAD starts, and the InitGui.py file is executed immediately after, but only when FreeCAD starts in GUI mode. That's all it needs for FreeCAD to find your workbench at startup and add it to its interface.

The user Mod directory is a sub-directory of the user application data directory (you can find the latter by typing App.getUserAppDataDir() in the Python console):

  • On Linux it is usually /home/<username>/.local/share/FreeCAD/Mod/ (version 0.20 and above) or /home/<username>/.FreeCAD/Mod/ (version 0.19 and below).
  • On Windows it is %APPDATA%\FreeCAD\Mod\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\.
  • On macOS it is usually /Users/<username>/Library/Application Support/FreeCAD/Mod/.

The Mod directory should look like this:

/Mod/
 +-- MyWorkbench/
     +-- Init.py
     +-- InitGui.py

Inside those files you can do whatever you want. Usually they are used like this:

  • In the Init.py file you just add a couple of things used even when FreeCAD works in console mode, for example the file importers and exporters
  • In the InitGui.py file you usually define a workbench, which contains a name, an icon, and a series of FreeCAD commands (see below). That python file also defines functions that are executed when FreeCAD loads (you try to do as little as possible there, so you don't slow down the startup), another that gets executed when the workbench is activated (that's where you'll do most of the work), and a third one when the workbench is deactivated (so you can remove things if needed).

The structure and file content for a workbench described here is the classic way of creating a new workbench. One can use a slight variation in the structure of files when making a new Python workbench, that alternative way is best described as a "namespaced workbench", opening up the possibility to use pip to install the workbench. Both structures work, so it is more a question of preference when creating a new workbench. The style and structure for workbenches presented here are available in the global namespace of FreeCAD, whereas for the alternative style and structure the workbench resides in a dedicated namespace. For further readings on the topic see Related.

C++ workbench structure

If you are going to code your workbench in python, you don't need to take special care, and can simply place your other python files together with your Init.py and InitGui.py files. When working with C++, however, you should take greater care, and start with respecting one fundamental rule of FreeCAD: The separation of your workbench between an App part (that can run in console mode, without any GUI element), and a Gui part, which will only be loaded when FreeCAD runs with its full GUI environment. So when developing a C++ workbench, you will actually most likely create two modules, an App and a Gui. These two modules must of course be callable from python. Any FreeCAD module (App or Gui) consists, at the very least, of a module init file. This is a typical AppMyModuleGui.cpp file:

extern "C" {
    void MyModuleGuiExport initMyModuleGui()  
    {
         if (!Gui::Application::Instance) {
            PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
            return;
        }
        try {
            // import other modules this one depends on
            Base::Interpreter().runString("import PartGui");
            // run some python code in the console
            Base::Interpreter().runString("print('welcome to my module!')");
        }
        catch(const Base::Exception& e) {
            PyErr_SetString(PyExc_ImportError, e.what());
            return;
        }
        (void) Py_InitModule("MyModuleGui", MyModuleGui_Import_methods);   /* mod name, table ptr */
        Base::Console().Log("Loading GUI of MyModule... done\n");
    
        // initializes the FreeCAD commands (in another cpp file)
        CreateMyModuleCommands();
    
        // initializes workbench and object definitions
        MyModuleGui::Workbench::init();
        MyModuleGui::ViewProviderSomeCustomObject::init();
    
         // add resources and reloads the translators
        loadMyModuleResource();
    }
}

The Init.py file

"""FreeCAD init script of XXX module"""

# ***************************************************************************
# *   Copyright (c) 2015 John Doe john@doe.com                              *   
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   FreeCAD is distributed in the hope that it will be useful,            *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Lesser General Public License for more details.                   *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with FreeCAD; if not, write to the Free Software        *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************/

FreeCAD.addImportType("My own format (*.own)", "importOwn")
FreeCAD.addExportType("My own format (*.own)", "exportOwn")
print("I am executing some stuff here when FreeCAD starts!")

You can choose any license you like for your workbench, but be aware that if you wish to see your workbench integrated into and distributed with the FreeCAD source code at some point, it needs to be LGPL2+ like the example above. See Licence.

The FreeCAD.addImportType() and addEXportType() functions allow you to give the name and extension of a file type, and a Python module responsible for its import. In the example above, an importOwn.py module will handle .own files. See Code snippets for more examples.

Python workbenches

This is the InitGui.py file:

class MyWorkbench (Workbench):

    MenuText = "My Workbench"
    ToolTip = "A description of my workbench"
    Icon = """paste here the contents of a 16x16 xpm icon"""

    def Initialize(self):
        """This function is executed when the workbench is first activated.
        It is executed once in a FreeCAD session followed by the Activated function.
        """
        import MyModuleA, MyModuleB # import here all the needed files that create your FreeCAD commands
        self.list = ["MyCommand1", "MyCommand2"] # a list of command names created in the line above
        self.appendToolbar("My Commands", self.list) # creates a new toolbar with your commands
        self.appendMenu("My New Menu", self.list) # creates a new menu
        self.appendMenu(["An existing Menu", "My submenu"], self.list) # appends a submenu to an existing menu

    def Activated(self):
        """This function is executed whenever the workbench is activated"""
        return

    def Deactivated(self):
        """This function is executed whenever the workbench is deactivated"""
        return

    def ContextMenu(self, recipient):
        """This function is executed whenever the user right-clicks on screen"""
        # "recipient" will be either "view" or "tree"
        self.appendContextMenu("My commands", self.list) # add commands to the context menu

    def GetClassName(self): 
        # This function is mandatory if this is a full Python workbench
        # This is not a template, the returned string should be exactly "Gui::PythonWorkbench"
        return "Gui::PythonWorkbench"
       
Gui.addWorkbench(MyWorkbench())

Other than that, you can do anything you want: you could put your whole workbench code inside the InitGui.py if you want, but it is usually more convenient to place the different functions of your workbench in separate files. So those files are smaller and easier to read. Then you import those files into your InitGui.py file. You can organize those files the way you want, a good example is one for each FreeCAD command you add.

Preferences

You can add a Preferences page for your Python workbench. The Preferences pages look for a preference icon with a specific name in the Qt Resource system. If your icon isn't in the resource system or doesn't have the correct name, your icon won't appear on the Preferences page.

Adding your workbench icon:

  • the preferences icon needs to be named "preferences-" + "modulename" + ".svg" (all lowercase)
  • make a qrc file containing all icon names
  • in the main *.py directory, run pyside-rcc -o myResources.py myqrc.qrc
  • in InitGui.py, add import myResource(.py)
  • update your repository(git) with myResources.py and myqrc.qrc

You'll need to redo the steps if you add/change icons.

@kbwbe has created a nice script to compile resources for the A2Plus workbench. See below.

Adding your preference page(s):

  • You need to compile the Qt designer plugin that allows you to add preference settings with Qt Designer
  • Create a blank widget in Qt Designer (no buttons or anything)
  • Design your preference page, any setting that must be saved (preferences) must be one of the Gui::Pref* widgets that were added by the plugin)
  • In any of those, make sure you fill the PrefName (the name of your preference value) and PrefPath (ex: Mod/MyWorkbenchName), which will save your value under BaseApp/Preferences/Mod/MyWorkbenchName
  • Save the ui file in your workbench, make sure it's handled by cmake
  • In your workbench, for ex. inside the InitGui file, inside the Initialize method (but any other place works too), add: FreeCADGui.addPreferencePage("/path/to/myUiFile.ui","MyGroup"), "MyGroup" being one of the preferences groups on the left. FreeCAD will automatically look for a "preferences-mygroup.svg" file in its known locations (which you can extend with FreeCADGui.addIconPath())
  • Make sure the addPreferencePage() method is called only once, otherwise your pref page will be added several times

Distribution

To distribute your Python workbench, you may either simply host the files in some location and instruct your users to download them and place them in their Mod directory manually, or you may host them in an online git repository (GitHub, GitLab, Framagit, and Debian Salsa are currently supported locations) and configure them for the Addon Manager to install. Instructions for inclusion on FreeCAD's official Addons list can be found on the FreeCAD Addons GitHub repository. To use the Addon Manager, a package.xml metadata file should be included, which instructs the Addon Manager how to find your workbench's icon, and allows display of a description, version number, etc. It can also be used to specify other workbenches or Python packages that your Workbench either depends on, is blocked by, or is intended to replace.

For a quick guide on how to create a basic package.xml file and add a workbench to the Addon Manager see: Add Workbench to Addon Manager.

Optionally, you can include a separate metadata file describing your Python dependencies. This may be either a file called metadata.txt describing your workbench's external dependencies (on either other Addons, Workbenches, or Python modules), or a requirements.txt describing your Python dependencies. Note that if using a requirements.txt file, only the names of the specified packages are used for dependency resolution: pip command options, include options and version information are not supported by the Addon Manager. Users may manually run the requirements file using pip if those features are required.

The format of the metadata.txt file is plain text, with three optional lines:

workbenches=
pylibs=
optionalpylibs=

Each line should consist of a comma-separated list of items your Workbench depends on. Workbenches may be either an internal FreeCAD Workbench, e.g. "FEM", or an external Addon, for example "Curves". The required and optional Python libraries should be specified with their canonical Python names, such as you would use with pip install. For example:

workbenches=FEM,Curves
pylibs=ezdxf
optionalpylibs=metadata,git

You may also include a script that is run when your package is uninstalled. This is a file called "uninstall.py" located at the top level of your Addon. It is executed when a user uninstalls your Addon using the Addon Manager. Use it to clean up anything your Addon may have done to the users system that should not persist when the Addon is gone (e.g. removing cache files, etc.).

To ensure that your addon is being read correctly by the Addon Manager, you can enable a "developer mode" in which the Addon Manager examines all available addons and ensures their metadata contains the required elements. To enable this mode select: Edit → Preferences... → Addon Manager → Addon manager options → Addon developer mode, see Preferences Editor.

C++ workbenches

If you are going to code your workbench in C++, you will probably want to code the workbench definition itself in C++ too (although it is not necessary: you could also code only the tools in C++, and leave the workbench definition in Python). In that case, the InitGui.py file becomes very simple: It might contain just one line:

import MyModuleGui

where MyModule is your complete C++ workbench, including the commands and workbench definition.

Coding C++ workbenches works in a pretty similar way. This is a typical Workbench.cpp file to include in the Gui part of your module:

namespace MyModuleGui {
    class MyModuleGuiExport Workbench : public Gui::StdWorkbench
    {
        TYPESYSTEM_HEADER();

    public:
        Workbench();
        virtual ~Workbench();

        virtual void activated();
        virtual void deactivated();

    protected:
        Gui::ToolBarItem* setupToolBars() const;
        Gui::MenuItem*    setupMenuBar() const;
    };
}

Preferences

You can add a Preferences page for C++ workbenches too. The steps are similar to those for Python.

Distribution

There are two options to distribute a C++ workbench, you can either host precompiled versions for the different operating systems yourself, or you can request for your code to be merged into the FreeCAD source code. As mentioned above this requires a LGPL2+ license, and you must first present your workbench to the community in the FreeCAD forum for review.

FreeCAD commands

FreeCAD commands are the basic building block of the FreeCAD interface. They can appear as a button on toolbars, and as a menu entry in menus. But it is the same command. A command is a simple Python class, that must contain a couple of predefined attributes and functions, that define the name of the command, its icon, and what to do when the command is activated.

Python command definition

class My_Command_Class():
    """My new command"""

    def GetResources(self):
        return {"Pixmap"  : "My_Command_Icon", # the name of a svg file available in the resources
                "Accel"   : "Shift+S", # a default shortcut (optional)
                "MenuText": "My New Command",
                "ToolTip" : "What my new command does"}

    def Activated(self):
        """Do something here"""
        return

    def IsActive(self):
        """Here you can define if the command must be active or not (greyed) if certain conditions
        are met or not. This function is optional."""
        return True

FreeCADGui.addCommand("My_Command", My_Command_Class())

C++ command definition

Similarly, you can code your commands in C++, typically in a Commands.cpp file in your Gui module. This is a typical Commands.cpp file:

DEF_STD_CMD_A(CmdMyCommand);

CmdMyCommand::CmdMyCommand()
  :Command("My_Command")
{
  sAppModule    = "MyModule";
  sGroup        = QT_TR_NOOP("MyModule");
  sMenuText     = QT_TR_NOOP("Runs my command...");
  sToolTipText  = QT_TR_NOOP("Describes what my command does");
  sWhatsThis    = QT_TR_NOOP("Describes what my command does");
  sStatusTip    = QT_TR_NOOP("Describes what my command does");
  sPixmap       = "some_svg_icon_from_my_resource";
}

void CmdMyCommand::activated(int iMsg)
{
    openCommand("My Command");
    doCommand(Doc,"print('Hello, world!')");
    commitCommand();
    updateActive();
}

bool CmdMyCommand::isActive(void)
{
  if( getActiveGuiDocument() )
    return true;
  else
    return false;
}

void CreateMyModuleCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
    rcCmdMgr.addCommand(new CmdMyCommand());
}

"Compiling" your resource file

compileA2pResources.py from the A2Plus workbench:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2019 kbwbe                                              *
#*                                                                         *
#*   Portions of code based on hamish's assembly 2                         *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

# This script compiles the A2plus icons for py2 and py3
# For Linux only
# Start this file in A2plus main directory
# Make sure pyside-rcc is installed

import os, glob

qrc_filename = 'temp.qrc'
if os.path.exists(qrc_filename):
    os.remove(qrc_filename)

qrc = '''<RCC>
\t<qresource prefix="/">'''
for fn in glob.glob('./icons/*.svg'):
    qrc = qrc + '\n\t\t<file>%s</file>' % fn
qrc = qrc + '''\n\t</qresource>
</RCC>'''

print(qrc)

f = open(qrc_filename,'w')
f.write(qrc)
f.close()

os.system(
    'pyside-rcc -o a2p_Resources2.py {}'.format(qrc_filename))
os.system(
    'pyside-rcc -py3 -o a2p_Resources3.py {}'.format(qrc_filename))

os.remove(qrc_filename)

Related



Prueba primero

Antes de pasar por la molestia de la depuración, utilice el Marco de pruebas para comprobar si las pruebas estándar funcionan correctamente. Si no se ejecutan por completo, es posible que haya una instalación defectuosa.

Línea de comandos

La depuración de FreeCAD está respaldada por algunos mecanismos internos. La versión de línea de comandos de FreeCAD proporciona algunas opciones para soporte de depuración.

Estas son las opciones reconocidas actualmente en FreeCAD 0.19:

Opciones genéricas:

  -v [ --version ]          Imprime la cadena de versión
  -h [ --help ]             Imprime el mensaje de ayuda
  -c [ --console ]          Comienza en modo consola
  --response-file arg       También se puede especificar con '@nombre'
  --dump-config             Configuración de volcados
  --get-config arg          Imprime el valor de la clave de configuración solicitada

Configuración:

  -l [ --write-log ]        Escribe un archivo de registro en:
                            $HOME/.local/share/FreeCAD/FreeCAD.log (Linux)
                            $HOME/Library/Application\ Support/FreeCAD/FreeCAD.log (macOS)
                            %APPDATA%\FreeCAD\FreeCAD.log 
  --log-file arg            A diferencia de --write-log, esto permite iniciar sesión en un 
                            archivo arbitrario
  -u [ --user-cfg ] arg     Archivo de configuración de usuario para cargar/guardar configuraciones de usuario
  -s [ --system-cfg ] arg   Archivo de configuración del sistema para cargar/guardar la configuración del sistema
  -t [ --run-test ] arg     Caso de prueba - o 0 para todos
  -M [ --module-path ] arg  Rutas de módulos adicionales
  -P [ --python-path ] arg  Rutas adicionales de Python
  --single-instance         Permite ejecutar una única instancia de la aplicación

Generating a Backtrace

If you are running a version of FreeCAD from the bleeding edge of the development curve, it may "crash". You can help solve such problems by providing the developers with a "backtrace". To do this, you need to be running a "debug build" of the software. "Debug build" is a parameter that is set at compile time, so you'll either need to compile FreeCAD yourself, or obtain a pre-compiled "debug" version.

Para Linux

Depuración de Linux →

Requisitos previos:

  • paquete de software gdb instalado
  • una versión de depuración de FreeCAD (en este momento solo está disponible mediante la compilación desde el código fuente)
  • un modelo de FreeCAD que provoca un problema

Pasos: Ingrese lo siguiente en la ventana de su terminal:

Encuentre el binario FreeCAD en su sistema:

$ whereis freecad
freecad: /usr/local/freecad <--- for example

$ cd /usr/local/freecad/bin
$ gdb FreeCAD

GNUdebugger generará información de inicialización. El (gdb) muestra que GNUDebugger se está ejecutando en la terminal, ahora ingrese:

(gdb) handle SIG33 noprint nostop
(gdb) run

FreeCAD ahora se iniciará. Realice los pasos que hacen que FreeCAD se bloquee o se congele, luego ingrese en la ventana de terminal:

(gdb) bt

Esto generará una lista larga de exactamente lo que estaba haciendo el programa cuando falló o se congeló. Incluya esto con su informe de problemas.

(gdb) bt full

Imprima también los valores de las variables locales. Esto se puede combinar con un número para limitar la cantidad de fotogramas mostrados.

Para macOS

Depuración de macOS →

Requisitos previos:

  • software package lldb installed
  • a debug build of FreeCAD
  • a FreeCAD model that causes a crash

Steps: Enter the following in your terminal window:

$ cd FreeCAD/bin
$ lldb FreeCAD

LLDB will output some initializing information. The (lldb) shows the debugger is running in the terminal, now input:

(lldb) run

FreeCAD will now start up. Perform the steps that cause FreeCAD to crash or freeze, then enter in the terminal window:

(lldb) bt

This will generate a lengthy listing of exactly what the program was doing when it crashed or froze. Include this with your problem report.

List Libraries Loaded by FreeCAD

(Applicable to Linux and macOS)

Sometimes it's helpful to understand what libraries FreeCAD is loading, specifically if there are multiple libraries being loaded of the same name but different versions (version collision). In order to see which libraries are loaded by FreeCAD when it crashes you should open a terminal and run it in the debugger. In a second terminal window, find out the process id of FreeCAD:

ps -A | grep FreeCAD

Use the returned id and pass it to lsof:

lsof -p process_id

This prints a long list of loaded resources. So for example, if trying to ascertain if more than one Coin3d library versions is loaded, scroll through the list or search directly for Coin in the output:

lsof -p process_id | grep Coin

Python Debugging

For a more modern approach to debugging Python, see these posts:

winpdb

winpdb Debugging →

Here is an example of using Winpdb inside FreeCAD:

We need the Python debugger: Winpdb. If you do not have it installed, on Ubuntu/Debian install it with:

sudo apt-get install winpdb

Now lets setup the debugger.

  1. Start Winpdb.
  2. Set the debugger password to "test": Go to menu FilePassword" and set the password.

Now we will run a test Python script in FreeCAD step by step.

  1. Run winpdb and set the password (e.g. test)
  2. Create a Python file with this content
import rpdb2
rpdb2.start_embedded_debugger("test")
import FreeCAD
import Part
import Draft
print "hello"
print "hello"
import Draft
points=[FreeCAD.Vector(-3.0,-1.0,0.0),FreeCAD.Vector(-2.0,0.0,0.0)]
Draft.makeWire(points,closed=False,face=False,support=None)
  1. Start FreeCAD and load the above file into FreeCAD
  2. Press F6 to execute it
  3. Now FreeCAD will become unresponsive because the Python debugger is waiting
  4. Switch to the Windpdb GUI and click on "Attach". After a few seconds an item "<Input>" appears where you have to double-click
  5. Now the currently executed script appears in Winpdb.
  6. Set a break at the last line and press F5
  7. Now press F7 to step into the Python code of Draft.makeWire

Visual Studio Code (VS Code)

VS Code Debugging →

Prerequisites:

  • The ptvsd package needs to be installed in a Python 3 outside of FreeCAD, then the module must be copied to FreeCAD's Python library folder.
# In a cmd window that has a path to you local Python 3:
pip install ptvsd
# Then if your Python is installed in C:\Users\<userid>\AppData\Local\Programs\Python\Python37
# and your FreeCAD is installed in C:\freecad\bin
xcopy "C:\Users\<userid>\AppData\Local\Programs\Python\Python37\Lib\site-packages\ptvsd" "C:\freecad\bin\Lib\site-packages\ptvsd"

pypi page

Visual Studio Code documentation for remote debugging

Steps:

  • Add following code at the beginning of your script
import ptvsd
print("Waiting for debugger attach")
# 5678 is the default attach port in the VS Code debug configurations
ptvsd.enable_attach(address=('localhost', 5678), redirect_output=True)
ptvsd.wait_for_attach()
  • Add a debug configuration in Visual Studio Code Debug → Add Configurations….
  • The config should look like this:
    "configurations": [
        {
            "name": "Python: Attacher",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "."
                }
            ]
        },
  • In VS Code add a breakpoint anywhere you want.
  • Launch the script in FreeCAD. FreeCAD freeze waiting for attachment.
  • In VS Code start debugging using created configuration. You should see variables in debugger area.
  • When setting breakpoints, VS Code will complain about not finding the .py file opened in the VS Code editor.
    • Change "remoteRoot": "." to "remoteRoot": "<directory of file>"
      • For example, if the Python file resides in /home/FC_myscripts/myscript.py
      • Change to: "remoteRoot": "/home/FC_myscripts"
    • If you're just debugging FreeCAD macros from the FreeCAD macro folder, and that folder is "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro", then use:
      • "localRoot": "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro",
      • "remoteRoot": "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro"
  • If your macro can't find ptvsd despite having installed it somewhere precede 'import ptvsd' with
from sys import path
sys.path.append('/path/to/site-packages')

Where the path is to the directory where ptvsd was installed.

  • On the left bottom edge of VSCode you can choose the Python executable - it's best to make this the version packaged with FreeCAD.

In the Mac package it is /Applications/FreeCAD.App/Contents/Resources/bin/python.

You can locate it on your system by typing

import sys
print(sys.executable)

into FreeCAD's Python console.

With LiClipse and AppImage

LiClipse Debugging →

  • Extract AppImage.
> ./your location/FreeCAD_xxx.AppImage --appimage-extract
> cd squashfs-root/
  • The sqashfs-root location is where the debugger later on is hooked up to.
  • Make sure you can start a FreeCAD session from within the squashfs-root location.
squashfs-root> ./usr/bin/freecadcmd
  • Should start up a FreeCAD commandline session.
  • Install LiClipse.
    • Comes ready with pydev and has installers for all platforms.
    • For linux it is just to extract (to any location) and run.
  • Configure liclipse for debugging.
    • Right-click pydev icon (upper right corner) and choose customize.
      • Activate "PyDev Debug" (through checkbox, or it might be needed to go to tab "Action Set Availability" and activate there first).
      • In the pydev menu you can now choose "start debug server".
    • Use menu window/open perspective/other > debug.
      • Right-click debug icon (upper right corner) and choose customize.
      • Checking "Debug" brings the debugging navigation tools to the toolbar.
    • Open preferences through menu window/preferences.
      • In PyDev/Interpreters add "new Interpreter by browsing".
      • The added interpreter should be: your loc/squashfs-root/usr/bin/python.
      • If you are only using this for fc, you can add AddOn workbench folders as well, or do that in a pydev-project later on.
  • Find path to pydevd.py in your liclipse installation.
    • Something along the lines of: your location/liclipse/plugins/org.python.pydev.xx/pysrc.
  • Create a regular pydev-project in liclipse.
    • Import external sources, for example a macro that you want to debug, or an external workbench.
    • In that macro (or workbench .py file) add the code lines:
import sys; sys.path.append("path ending with /pysrc")
import pydevd; pydevd.settrace()
  • This is where the execution will halt when the macro is run.
  • Start the liclipse debug server (menu pydev).
  • Start FreeCAD.
squashfs-root> ./usr/bin/freecad
  • Run the macro (or any other file with a pydevd.settrace() trigger) from within freecad, as you would normally do.
  • Happy debugging.
  • The use of LiClipse for remote debugging, and the steps described here related to liclipse, should work on any platform. The parts related to AppImage is for linux only.

Pyzo

See the main article about Pyzo.

Debugging OpenCasCade

For developers needing to dig deeper in to the OpenCasCade kernel, user @abdullah has created a thread orientation discussing how to do so.



Icono del ambiente Prueba

Introducción

El Ambiente de trabajo del marco Pruebas no es realmente un ambiente de trabajo de modelado, pero contiene un conjunto de scripts de Python para realizar diferentes pruebas en los componentes principales de FreeCAD, con el fin de depurar problemas. Ver también depuración.

Puede ejecutar las pruebas desde la línea de comandos, utilizando las opciones -t o --run-test.

Ejecutar todas las pruebas:

freecad --run-test 0

Ejecutar sólo algunas de las pruebas unitarias especificadas, por ejemplo:

freecad -t TestDraft

If a test does not need the GUI, it can also be executed in console mode by setting the -c or --console option in addition. This usually results in much faster startup time as the GUI is not loaded. For example:

freecad -c -t TestPartDesignApp

Menú de prueba

Cada directorio de nivel superior en FreeCAD debe tener un archivo con las pruebas que se pueden ejecutar para ese ambiente de trabajo o módulo en particular. El archivo suele empezar con la palabra Test.

Para ejecutar una prueba desde FreeCAD, cambia al ambiente de trabajo Pruebas, luego Comandos de prueba → TestHierramientasGui → Autoprueba → Seleccionar nombre de la prueba, luego introduce el nombre del archivo Python con las pruebas; por ejemplo, para el Ambiente de trabajo Borrador, esto sería PruebaBorrador, luego presiona Inicio.

Funciones de prueba

Esta es la lista de aplicaciones de prueba a partir de la versión 0.15 git 4207:

TestAPP.All

Add test function

BaseTests

Add test function

UnitTests

Add test function

Documento

Add test function

UnicodeTests

Add test function

MeshTestsApp

Add test function

TestDraft

Add test function

TestSketcherApp

Add test function

TestPartApp

Add test function

TestPartDesignApp

Add test function

TestPathApp

Path workbench test cases:

  • depthTestCases:
  • PathTestUtils:
  • TestDressupDogbone: Test functionality of Dogbone dressup.
  • TestHoldingTags: Test functionality of Holding Tags dressup.
  • TestPathAdaptive: Test selection capability of Adaptive operation.
  • TestPathCore: Test core functionality of Path workbench.
  • TestPathDeburr: Test general functionality of Deburr operation.
  • TestPathGeom: Test various functions available in the PathGeom module.
  • TestPathHelix: Test general functionality of Helix operation.
  • TestPathLog: Test various functions available in the PathLog debugging and feedback module.
  • TestPathOpTools:
  • TestPathPreferences: Test various functions available in the PathPreferences module.
  • TestPathPropertyBag:
  • TestPathSetupSheet:
  • TestPathStock:
  • TestPathThreadMilling:
  • TestPathTool:
  • TestPathToolBit:
  • TestPathToolController:
  • TestPathTooltable:
  • TestPathUtil: Test various functions available in the PathUtil module.
  • TestPathVcarve: Test general functionality of Vcarve operation.
  • TestPathVoronoi:

Ambiente de trabajo

Add test function

Menú

Add test function

Menu.MenuDeleteCases

Add test function

Menu.MenuCreateCases

Add test function

Guionización

Ver también: Básicos de Guionización FreeCAD.

Get a list of all top-level test modules

FreeCAD.__unit_test__

Note that the test modules returned here depend on whether a GUI available or not. I.e. when executed in console mode, various tests ending in "Gui" are missing.

Run specific tests

There are various ways of running tests using Python's unittest library. FreeCAD's test framework removes some of the boiler plate for the most common cases.

Run all tests defined in a Python module:

import Test, TestFemApp
Test.runTestsFromModule(TestFemApp)

Run all tests defined in a Python class:

import Test, femtest.app.test_solver_calculix
Test.runTestsFromClass(femtest.app.test_solver_calculix.TestSolverCalculix)

Ejemplo 1

Within the Python Console of FreeCAD, the following code format may be used to run built-in tests. Replace the red "TestFem" text in the code below with the desired module test name.

  • For example, use "TestPathApp" to run all unit tests for the Path workbench unit test framework.
  • Submodules are available using dot notation, like "TestPathApp.TestPathAdaptive" to only run the Adaptive unit tests within the greater Path workbench test framework.
  • Multiple test modules or submodules may be combined by adding another `suite.addTest(...)` method call just like the one in the code below, but with a different module or submodule reference.
  • Output for the code below will be in the Report View panel within the FreeCAD GUI.
  • Code source is copied from post by FreeCAD forum user, sgrogan, in the unit tests per python topic, with credit there given to forum user, wmayer.
import unittest
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName("TestFem"))
r = unittest.TextTestRunner()
r.run(suite)

Recursos adicionales

Temas del foro



Overview

Este artículo describe el Marcado de FreeCAD. Marcado significa comenzar tu propia aplicación basada en FreeCAD. Esto puede ser sólo tu propio ejecutable o pantalla de bienvenida pantalla de bienvenida hasta un programa completo adaptado. En base a la arquitectura flexible de FreeCAD es sencillo de utilizar como base para tus propios programas de propósito especial.

Warning

Although FreeCAD is offered to you free of charge, and the FreeCAD community is happy to see other applications emerging, that are based on FreeCAD, we have on the other hand seen a lot of unfair use of the information contained on this page by people who simply rebranded FreeCAD into a closed-source application to make profit from it.

Although the LGPL license allows to use the FreeCAD source code in closed-source applications, it also gives strict rules to do so, and does not allow simply taking FreeCAD, renaming it and stripping it of its license.

Would you be interested in using FreeCAD in a closed-source application, be sure to check thoroughly the implications of the LGPL license, and, even better, contact any FreeCAD developer, administrator or moderator before doing so.

General

General

La mayoría del marcado se realiza en MainCmd.cpp o MainGui.cpp. Estos proyectos generan los archivos ejecutables de FreeCAD. Para crear tu propia Marca simplemente copia los proyectos Main o MainGui y dale al ejecutable un nombre diferente, e.g. FooApp.exe. La configuración más importante para una nueva apariencia puede realizarse en una lugar de la función main(). Aquí está la sección de código que controla el marcado:

int main( int argc, char ** argv )
{
    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FooApp";
    App::Application::Config()["ExeVersion"] = "0.7";

    // set the banner (for loging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "FooAppIcon";
    App::Application::Config()["SplashScreen"] = "FooAppSplasher";
    App::Application::Config()["StartWorkbench"] = "Part design";
    App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#000000"; // black

    // Inits the Application 
    App::Application::Config()["RunMode"] = "Gui";
    App::Application::init(argc,argv);

    Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);

    Gui::Application::initApplication();
    Gui::Application::runApplication();
    App::Application::destruct();

    return 0;
}

La primera entrada de Config define el nombre del programa. Este no es el nombre del ejecutable, el cual puede cambiarse renombrándolo o por la configuración del compilador, sino el nombre que es mostrado en la barra de tareas en Windows o en la lista de programas en los sistemas Unix.

Las siguientes líneas definen las entradas de Config de tu aplicación FooApp. Una descripción de Config y sus entradas se encuentra en Inicio y Configuración.

Images

Image resources are compiled into FreeCAD using Qt's resource system. Therefore you have to write a .qrc file, an XML-based file format that lists image files on the disk but also any other kind of resource files. To load the compiled resources inside the application you have to add a line

Q_INIT_RESOURCE(FooApp);

into the main() function. Alternatively, if you have an image in XPM format you can directly include it into your main.cpp and add the following line to register it:

Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);

Branding XML

In FreeCAD there is also a method supported without writing a customized main() function. For this method you must write a file name called branding.xml and put it into the installation directory of FreeCAD. Here is an example with all supported tags:

<?xml version="1.0" encoding="utf-8"?>
<Branding>
    <Application>FooApp</Application>
    <WindowTitle>Foo App in title bar</WindowTitle>
    <BuildVersionMajor>1</BuildVersionMajor>
    <BuildVersionMinor>0</BuildVersionMinor>
    <BuildRevision>1234</BuildRevision>
    <BuildRevisionDate>2014/1/1</BuildRevisionDate>
    <CopyrightInfo>(c) My copyright</CopyrightInfo>
    <MaintainerUrl>Foo App URL</MaintainerUrl>
    <ProgramLogo>Path to logo (appears in bottom right corner)</ProgramLogo>
    <WindowIcon>Path to icon file</WindowIcon>
    <ProgramIcons>Path to program icons</ProgramIcons>
    <SplashScreen>splashscreen.png</SplashScreen>
    <SplashAlignment>Bottom|Left</SplashAlignment>
    <SplashTextColor>#ffffff</SplashTextColor>
    <SplashInfoColor>#c8c8c8</SplashInfoColor>
    <StartWorkbench>PartDesignWorkbench</StartWorkbench>
</Branding>

All listed tags are optional.


Testing/es
Localisation/es


Vista general

"Localización" es en general el proceso de proveer un software con una interfaz de usuario con múltiples lenguajes. En FreeCAD puedes cambiar el lenguaje de la interfaz en Editar→Preferencias→General. FreeCAD usa Qt para facilitar el soporte de múltiples lenguajes. En Unix/Linux, FreeCAD utiliza la configuración local actual de tu sistema como predeterminado.

Ayudando a traducir FreeCAD

Una de las cosas más importantes que los usuarios pueden contribuir a FreeCAD (si por ejemplo no tienen conocimientos de programación) es ayudar a traducir sus diferentes aspectos (código fuente, wiki, sitio web, documentación, etc...) a otro idioma. Aquí están las formas de hacerlo

Traducir el código fuente de FreeCAD

FreeCAD utiliza un sistema de traducción colaborativa en línea de terceros llamado Crowdin.

Se trata de un software propietario, pero gratuito para los proyectos FOSS. A continuación encontrará instrucciones sobre cómo utilizarlo:

  • Ir a la FreeCAD página del proyecto de traducción en Crowdin
  • Iniciar sesión creando un nuevo perfil, o utilizando una cuenta de terceros (GitHub, GitLab, GMail, etc...)
  • Haga clic en el idioma que desea traducir
  • Comienza a traducir haciendo clic en el botón Traducir junto a uno de los archivos. Por ejemplo, FreeCAD.ts contiene las cadenas de texto para la interfaz gráfica principal de FreeCAD.
  • Puedes votar por las traducciones existentes, o puedes crear las tuyas propias.
Si estás participando activamente en la traducción de FreeCAD y quieres estar informado antes de que la próxima versión esté lista para ser lanzada, para que haya tiempo de revisar tu traducción, por favor suscríbete a uno de los equipos de traducción de Crowdin FreeCAD.


Nota: Los detalles sobre cómo utilizar crowdin se pueden encontrar en la página Administración de Crowdin.

Traduciendo ambientes de trabajo externos

Visite Traducir un ambiente de trabajo externos.

Preferencias de FreeCAD para traductores

A partir de la versión 0.20 de FreeCAD, las siguientes variables puede sert manualmente agregadas a la sección BaseApp/Preferences/General del archivo user.cfg para ayudar con el desarrollo de nuevas traducciones:

AddreDallanguageMainEnentries - para agregar idiomas completamente nuevos a FreeCAD que actualmente no son compatibles con el código fuente, puede usar esta preferencia del usuario para agregarlos a la lista de idiomas disponibles. El formato de los idiomas es "nombre del idioma" = "código"; por ejemplo:

<FCText Name="AdditionalLanguageDomainEntries">"Esperanto"="eo";"French"="fr";</FCText>

AdditionalTranslationsDirectory - agregue un directorio adicional para que FreeCAD busque archivos *.qm. Esta ubicación tendrá precedencia sobre $userAppDataDir/translations y $resourceDir/translations. Por ejemplo:

<FCText Name="AdditionalTranslationsDirectory">C:/Users/FreeCADUser/TestTranslations</FCText>

Traducir la wiki de FreeCAD

Este wiki alberga muchos contenidos, la mayoría de los cuales conforman el manual. Puedes navegar por la documentación a partir de la Página principal, o echar un vistazo al manual de usuario Ayuda en línea Índice de contenidos.

Para traducir el wiki, debes tener permisos de edición del wiki; consulta ¿Cómo puedo obtener permiso de edición en el wiki?.

También deberías tener suficientes conocimientos de marcado wiki y seguir las directrices generales de estilo descritas en PáginasWiki.

Extensión de traducción de Mediawiki

Cuando el wiki se alejó de SourceForge, Yorik instaló MediaWiki's Translation extension que facilita la traducción de las páginas. Las ventajas de la extensión de traducción son que el título de la página puede ser traducido, mantiene un registro de las traducciones, notifica si la página original ha sido actualizada, y mantiene las traducciones sincronizadas con la página original en inglés.

La herramienta está documentada en Help:Extension:Translate, y forma parte de MediaWiki Language Extension Bundle.

Para empezar rápidamente a preparar una página para su traducción, lea el Ejemplo de traducción de una página. Esencialmente, un par de

<translate> ... </translate>

tags rodear toda la página para activar el sistema de traducción, y la página debe estar marcada para ser traducida.

Para ver un ejemplo de cómo funciona la herramienta de traducción, visite la Página principal. Verá una barra de idiomas generada automáticamente en la parte superior. Haga clic en Hauptseite (alemán), le llevará a Main Page/de. Justo debajo del título, puedes leer Esta página es una versión traducida de la página Principal y la traducción está completada en un XX%, siendo XX el porcentaje actual de traducción. Haga clic en "Traducir" en la parte superior de la página para iniciar la utilidad de traducción para actualizar, corregir y revisar la traducción existente.

Si va a Main Page, notará que ya no puede editar la página directamente haciendo clic en las etiquetas [Edit], y el enlace superior "Editar" ha sido sustituido por el enlace "Traducir" que abre la utilidad de traducción.

Cuando se añade un nuevo contenido, la página en inglés debe crearse primero y luego traducirse a otro idioma. Si alguien quiere cambiar o añadir contenido en una página, la página en inglés debe ser modificada primero.

Si no estás seguro de cómo proceder con las traducciones, no dudes en pedir ayuda en el Desarrollo → subforo Wiki o en el subforo de idiomas específicos en el foro de FreeCAD.

Notas importantes

Todos los usuarios de la wiki que tengan permisos de "Editor" pueden lanzar la utilidad de traducción y escribir, guardar y revisar las traducciones.

Sin embargo, sólo los usuarios con permisos de "Administrador" pueden marcar las páginas para su traducción. Una página que no esté marcada para ser traducida no hará uso de la extensión de traducción y no se sincronizará correctamente con la información en inglés.

La barra lateral izquierda también es traducible, pero sólo los administradores pueden modificar este elemento del sitio. Por favor, siga las instrucciones dedicadas en Barra lateral de localización.

La primera vez que se cambia una página al nuevo sistema de traducción, se pierden todas sus antiguas traducciones "manuales". Para recuperar una traducción, debes guardar una copia offline del texto antiguo antes del cambio. Entonces podrás utilizar este texto antiguo traducido para rellenar las unidades de traducción en el nuevo sistema. También puedes abrir una versión anterior desde el historial, y obtener el texto antiguo de esta manera. Esto tiene que hacerse para cada idioma que tenía una página traducida.

Traducir la documentación de FreeCAD

Según el consenso general, la página de referencia en la wiki es la página en inglés, que debería crearse primero. Si quieres cambiar o añadir contenido a una página, debes hacerlo primero en la página en inglés, y sólo una vez completada la actualización, portar la modificación a la página traducida.

Instrucciones de traducción antiguas

Estas instrucciones son sólo para el fondo histórico. Las traducciones deben utilizar el nuevo sistema con la #Extensión de traducción de Mediawiki descrita anteriormente.

Así que el primer paso es comprobar si ya se ha iniciado la traducción manual para tu idioma (mira en la barra lateral izquierda, en "manual").
Si no es así, dirígete al [foro http://forum.freecadweb.org/] y di que quieres empezar una nueva traducción, crearemos la configuración básica para el idioma en el que quieres trabajar.
A continuación, debes obtener permiso de edición en la wiki.

Si tu idioma ya está en la lista, mira qué páginas aún no tienen traducción (aparecerán en rojo). La técnica es sencilla: entra en una página roja, y copia/pega el contenido de la página inglesa correspondiente, y empieza a traducir.
No olvides incluir todas las etiquetas y plantillas de la página original en inglés. Algunas de esas plantillas tendrán un equivalente en tu idioma (por ejemplo, hay una plantilla Docnav francesa llamada Docnav/fr). En casi todos los enlaces debes usar una barra y el código de tu idioma. Mira otras páginas ya traducidas para ver cómo lo hicieron.
Añade una barra y el código de tu idioma en las categorías, como [[Category:Developer Documentation/fr]]
Y si no estás seguro, dirígete a los foros y pide a la gente que compruebe lo que has hecho y te diga si está bien o no.
Hay cuatro plantillas que se utilizan habitualmente en las páginas de manual. Estas 4 plantillas tienen versiones localizadas (Template:Docnav/fr, Template:fr, etc...)

  • Template:GuiCommand : es el bloque de información del comando Gui en la parte superior derecha de la documentación del comando.
  • Template:Docnav : es la barra de navegación en la parte inferior de las páginas, mostrando las páginas anteriores y siguientes.
  • Template:Userdocnavi : da enlaces directos a las principales páginas base

Convención de nomenclatura de páginas
Por favor, ten en cuenta que, debido a las limitaciones en la implementación de Sourceforge del motor MediaWiki, requerimos que todas tus páginas mantengan el nombre de su contraparte original en inglés, añadiendo una barra y el código de tu idioma. Por ejemplo, la página traducida de About FreeCAD debe ser About Freecad/es para el español, About FreeCAD/pl para el polaco, etc. La razón es simple: para que si los traductores se van, los administradores del wiki, que no hablan todos los idiomas, sepan para qué son estas páginas. Esto facilitará el mantenimiento y evitará que se pierdan páginas.
Si quieres que la plantilla Docnav muestre páginas enlazadas en tu idioma, puedes usar páginas de redirección. Son básicamente enlaces de acceso directo a la página real. Aquí hay un ejemplo con la página francesa de Acerca de FreeCAD.

  • La página Acerca de FreeCAD/fr es la página con contenido
  • La página À propos de FreeCAD contiene este código:
#REDIRECT [[About_FreeCAD/fr]]
  • En la página À propos de FreeCAD/fr, el código Docnav tendrá el siguiente aspecto:
{{docnav/fr|[[Online_Help_Startpage/fr|Bienvenue dans l'aide en ligne de FreeCAD]]|[[Feature_list/fr|Fonctionnalités]]}}

La página "Bienvenue dans l'aide en ligne de FreeCAD" redirige a Online_Help_Startpage/fr, y la página "Fonctionnalités" redirige a Feature_list/fr.

Traducir el sitio web de FreeCAD

La traducción de la FreeCAD página web se realiza ahora a través de Crowdin. El archivo se llama homepage.po.

Desarrollo - Cómo añadir la localización

Esta sección es para los desarrolladores que quieren añadir localización a su código.

Preparando tus módulos de FreeCAD/master para la traducción

Estas son las partes del proceso de traducción de FreeCAD:

  • extraer las cadenas de texto del código fuente en archivos *.ts
  • cargar los archivos *.ts en FreeCAD Crowdin.
  • traducción de cadenas dentro de Crowdin
  • extraer archivos *.ts modificados/nuevos de Crowdin
  • convertir archivos *.ts en archivos *.qm y actualizar el archivo *.qrc de cada módulo
  • actualizar el maestro de FreeCAD

Todos los pasos anteriores son realizados por los "scripts de traducción" que son ejecutados por un administrador periódicamente.

Preparar su módulo para la traducción es bastante fácil. En primer lugar, debe asegurarse de que tiene un directorio "translations" en myModule/Gui/Resources. A continuación, abra una ventana de terminal (o su equivalente en Windows/OSX) en su directorio "translations" e introduzca el siguiente comando:

lupdate -ts myModule.ts

Esto crea un archivo de traducción vacío. Una vez hecho esto, hay que asegurarse de que los scripts de traducción se actualizan como en este pull request.

Todo lo que sigue es automático en lo que respecta a un desarrollador. El administrador extraerá las cadenas de texto, los traductores las traducirán, luego el administrador extraerá las traducciones y actualizará FreeCAD/master.

Preparar su módulo o macro de terceros para la traducción

Los módulos o macros de terceros se traducen prácticamente de la misma manera, con la diferencia de que debes hacer parte del trabajo tú mismo. Este discusión del foro describe los detalles.

Actualización: ver Traducir un banco de trabajo externo

Técnicas de traducción de módulos más antiguas

Localización Métodos antiguos describe el uso de herramientas de traducción como Qt Linguist, lupdate, lrelease, pylupdate4, etc en detalle. La mayor parte de esto ya no es necesario para los módulos de FreeCAD/master, pero puede ser útil para preparar y actualizar módulos de terceros.

Automatización de las actualizaciones de las traducciones de Crowdin

Actualmente los mantenedores de FreeCAD utilizan la API de Crowdin a través de Crowdin Guiones para extraer y enviar las traducciones a Crowdin y de vuelta al repositorio de Github. La API de Crowdin ofrece a los mantenedores de FreeCAD la posibilidad de automatizar aspectos del flujo de trabajo de traducción del proyecto, para más información consulta la Documentación de la API de Crowdin.

Páginas relacionadas

Programación

Ver también: Básicos de Guionización FreeCAD.

Para obtener un diccionario con los idiomas que admite la interfaz FreeCAD, use el método supportedLocales del módulo FreeCADGui.

locales = FreeCADGui.supportedLocales()

Después de la ejecución locales va a contener:

{'English': 'en', 'Afrikaans': 'af', 'Arabic': 'ar', 'Basque': 'eu', 'Catalan': 'ca', 'Chinese Simplified': 'zh-CN', 'Chinese Traditional': 'zh-TW', 'Croatian': 'hr', 'Czech': 'cs', 'Dutch': 'nl', 'Filipino': 'fil', 'Finnish': 'fi', 'French': 'fr', 'Galician': 'gl', 'German': 'de', 'Hungarian': 'hu', 'Indonesian': 'id', 'Italian': 'it', 'Japanese': 'ja', 'Kabyle': 'kab', 'Korean': 'ko', 'Lithuanian': 'lt', 'Norwegian': 'no', 'Polish': 'pl', 'Portuguese': 'pt-PT', 'Portuguese, Brazilian': 'pt-BR', 'Romanian': 'ro', 'Russian': 'ru', 'Slovak': 'sk', 'Slovenian': 'sl', 'Spanish': 'es-ES', 'Swedish': 'sv-SE', 'Turkish': 'tr', 'Ukrainian': 'uk', 'Valencian': 'val-ES', 'Vietnamese': 'vi'}

Para obtener el idioma que usa la interfaz actual use el método getLocale del mismo módulo:

locale = FreeCADGui.getLocale()

Si el idioma actual es inglés locale va a contener:

'English'

Para obtener el código de idioma correspondiente puede usar:

locale = FreeCADGui.supportedLocales()[Gui.getLocale()]

Si el idioma actual es inglés el resultado será:

'en'

Para establecer el lenguaje de interfaz actual, use el método setLocale del mismo módulo. Puede especificar el idioma o el código de idioma:

FreeCADGui.setLocale('Russian')
FreeCADGui.setLocale('ru')



Overview

Vista general

En esta página se enumeran varios módulos adicionales de python u otras piezas de software que pueden descargarse libremente de Internet, y que añaden funcionalidad a su instalación de FreeCAD.

PySide (previously PyQt)

PySide (anteriormente PyQt4)

  • página web (PySide): http://qt-project.org/wiki/PySide
  • licencia: LGPL
  • opcional, pero necesario para varios módulos: Borrador, Arco, Barco, Gráfica, OpenSCAD, Hoja de cálculo

PySide (antes PyQt) es requerido por varios módulos de FreeCAD para acceder a la interfaz Qt de FreeCAD. Ya está incluido en la versión de Windows de FreeCAD, y suele ser instalado automáticamente por FreeCAD en Linux, cuando se instala desde los repositorios oficiales. Si esos módulos (Draft, Arch, etc.) se activan después de que se instale FreeCAD, significa que PySide (antes PyQt) ya está ahí, y no es necesario hacer nada más.

Nota: FreeCAD se alejó progresivamente de PyQt después de la versión 0.13, a favor de PySide, que hace exactamente el mismo trabajo pero tiene una licencia (LGPL) más compatible con FreeCAD.

Instalación

Linux

Linux

La vía más simple para instalar PySide es a través del administrador de paquetes de su distribución. En los sistemas Debian/Ubuntu, el nombre del paquete es generalmente python-PySide, mientras que en los sistemas basados en RPM se llama pyside. Las dependencias necesarias (Qt y SIP) serán atendidas automáticamente.

Windows

Windows

El programa puede ser descargado de http://qt-project.org/wiki/Category:LanguageBindings::PySide::Downloads . Necesitarás instalar las librerías Qt y SIP antes de instalar PySide (para ser documentado).

MacOS

MacOSX

PyQt en Mac puede ser instalado vía homebrew o puerto. Ver Instalar dependencias para más información.

Usage

Uso

Una vez instalado, puede comprobar que todo funciona escribiendo en la consola python de FreeCAD:

import PySide

Para acceder a la interfaz de FreeCAD, escriba :

from PySide import QtCore,QtGui
FreeCADWindow = FreeCADGui.getMainWindow()

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)

Working with Unicode:

text = text.encode('utf-8')

Working with QFileDialog and OpenFileName:

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt")

Working with QFileDialog and SaveFileName:

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")

Example of transition from PyQt4 and PySide

PS: these examples of errors were found in the transition from PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above

try:
    import PyQt4                                        # PyQt4
    from PyQt4 import QtGui ,QtCore                     # PyQt4
    from PyQt4.QtGui import QComboBox                   # PyQt4
    from PyQt4.QtGui import QMessageBox                 # PyQt4
    from PyQt4.QtGui import QTableWidget, QApplication  # PyQt4
    from PyQt4.QtGui import *                           # PyQt4
    from PyQt4.QtCore import *                          # PyQt4
except Exception:
    import PySide                                       # PySide
    from PySide import QtGui ,QtCore                    # PySide
    from PySide.QtGui import QComboBox                  # PySide
    from PySide.QtGui import QMessageBox                # PySide
    from PySide.QtGui import QTableWidget, QApplication # PySide
    from PySide.QtGui import *                          # PySide
    from PySide.QtCore import *                         # PySide

To access the FreeCAD interface, type: You can add new elements, like a custom widget, with commands like:

myNewFreeCADWidget = QtGui.QDockWidget()          # create a new dockwidget
myNewFreeCADWidget.ui = Ui_MainWindow()           # myWidget_Ui()             # load the Ui script
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
try:
    app = QtGui.qApp                              # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw = app.activeWindow()                     # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
except Exception:
    FCmw = FreeCADGui.getMainWindow()             # PySide # the active qt window, = the freecad window since we are inside it
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Working with Unicode:

try:
    text = unicode(text, 'ISO-8859-1').encode('UTF-8')  # PyQt4
except Exception:
    text = text.encode('utf-8')                         # PySide

Working with QFileDialog and OpenFileName:

OpenName = ""
try:
    OpenName = QFileDialog.getOpenFileName(None,QString.fromLocal8Bit("Lire un fichier FCInfo ou txt"),path,"*.FCInfo *.txt") # PyQt4
except Exception:
    OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide

Working with QFileDialog and SaveFileName:

SaveName = ""
try:
    SaveName = QFileDialog.getSaveFileName(None,QString.fromLocal8Bit("Sauver un fichier FCInfo"),path,"*.FCInfo") # PyQt4
except Exception:
    SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide

The MessageBox:

def errorDialog(msg):
    diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical,u"Error Message",msg )
    try:
        diag.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint) # PyQt4 # this function sets the window before
    except Exception:
        diag.setWindowFlags(PySide.QtCore.Qt.WindowStaysOnTopHint)# PySide # this function sets the window before
#    diag.setWindowModality(QtCore.Qt.ApplicationModal)       # function has been disabled to promote "WindowStaysOnTopHint"
    diag.exec_()

Working with setProperty (PyQt4) and setValue (PySide)

self.doubleSpinBox.setProperty("value", 10.0) # PyQt4

replace with:

self.doubleSpinBox.setValue(10.0) # PySide

Working with setToolTip

self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None)) # PyQt4

replace with:

self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y")) # PySide

or:

self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide

Additional documentation

Pivy

Pivy is a needed by several modules to access the 3D view of FreeCAD. On windows, Pivy is already bundled inside the FreeCAD installer, and on Linux it is usually automatically installed when you install FreeCAD from an official repository. On macOS, unfortunately, you will need to compile pivy yourself.

Instalación

Prerequisites

Requisitos previos

Creo que antes de compilar Pivy querrás tener Coin y SoQt instalados.

Para construirlo en Mac es suficiente instalar el paquete binario de Coin3. Intentar instalar Coin desde MacPorts es problemático: añadir un montón de paquetes de X Windows y finalmente se cuelga con un error de script.

Para Fedora encontré un RPM con Coin3.

SoQt compilado desde código fuente funciona bien en Mac y Linux.

Debian & Ubuntu

Debian & Ubuntu

Empezando con Debian Squeeze y Ubuntu Lucid, pivy está disponible directamente desde los repositorios oficiales, ahorrándonos un montón de dificultades. Mientras tanto, puedes descargar uno de los paquetes que hemos creado (para Debian y Ubuntu karmic) disponibles en la página de Descargas, o compilarlo tu mismo.

El mejor modo de compilar pivy siomplemente es aprovechar el paquete de código fuente de Debian para pivy y crear un paquete con debuild. Es el mismo código fuente desde la web oficial de pivy, pero la gente de Debian han creado varios parches adicionales. También se compila bien en Ubuntu karmic: http://packages.debian.org/squeeze/python-pivy, descarga los archivos .orig.gz y .diff.gz, luego descomprimelos, y aplica .diff al código fuente: ve a las carpetas del código fuente descomprimido de pivy, y aplica el parche .diff:

patch -p1 < ../pivy_0.5.0~svn765-2.diff

luego

debuild

para tener pivy correctamente construido en un paquete oficial de instalación. A continuación, simplemente instala el paquete con gdebi.

Other linux distributions

Otras distribuciones Linux

Primero consigue la última versión del código fuente de los repositorios del proyecto:

hg clone http://hg.sim.no/Pivy/default Pivy

En marzo de 2012, la última versión es Pivy-0.5

Luego necesitas una herramienta llamada SWIG para generar el código C++ para la vinculación de Python. Pivy-0.5 informa que sólo ha sido comprobado con SWIG 1.3.31, 1.3.33, 1.3.35, y 1.3.40. Así que puedes descargar el código fuente en un tarball para una de dichas versiones anteriores desde http://www.swig.org. Luego descomprimelo y desde la línea de comandos haz lo siguiente (como root):

./configure
make
make install (or checkinstall if you use it)

Esto tardará unos segundos en construirse.

Como alternativa, puedes tratar de construir con un SWIG más reciente. En marzo de 2012, una versión típica del repositorio es la 2.0.4. Pivy tiene un problema menor de compilación con SWIG 2.0.4 en Mac OS (mira más abajo) pero parece construirse bien en Fedora Core 15.

Después de eso ve al archivo que va a los recursos de pivy y ejecuta

python setup.py build

lo que creará los archivos fuente. Ten en cuenta que la construcción puede producir miles de advertencias, pero afortunadamente no hay errores.

Es posible que esto esté obsoleto, pero puedes llegar a un error de compilación donde una constante de tipo caracter (char) no puede ser convertida en una 'char*'. Para solucionarlo sólo necesitas escribir una constante antes de las líneas apropiadas. Hay 6 líneas que corregir.

Después de eso, instalar por publicación (como root):

python setup.py install (or checkinstall python setup.py install)

Eso es todo, pivy está instalado.

MacOS

Mac OS

Estas instrucciones puede que no estén completas. Algo parecido funciona para OS 10.7 en marzo de 2012. He utilizado MacPorts para los repositorios, pero también deberían funcionar otras opciones.

Para Linux, consigue la última vcersión del código fuente:

hg clone http://hg.sim.no/Pivy/default Pivy

Si no tienes hg, puedes conseguirlo desde MacPorts:

port install mercurial

Luego, como se indica arriba, necesitas SWIG. Debería ser cuestión de hacer:

port install swig

He encontrado que también necesitaba:

port install swig-python

En marzo de 2012, la versión de SWIG en MacPorts es la 2.0.4. Como se ha indicado arriba para Linux, podría ser mejor que descargaras una versión más antigua. SWIG 2.0.4 parece tener un error que detiene la construcción de Pivy. Mira el primer mensaje en este enlace: https://sourceforge.net/mailarchive/message.php?msg_id=28114815

Esto se puede corregir editando las dos ubicaciones de código fuente para añadir: *arg4, *arg5 en lugar de arg4, arg5. Ahora Pivy debería construirse:

python setup.py build
sudo python setup.py install

Windows

Windows

Asumiendo que utilizas Visual Studio 2005 o superior deberías abrir una ventana de comandos con 'Visual Studio 2005 Command prompt' desde el menú Herramientas. Si el interprete aún no está en el sistema, haz

set PATH=path_to_python_2.5;%PATH%

Para tener pivy funcionando deberías conseguir las últimas fuentes desde los repositorios del proyect:

svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy

Luego necesitas una herramienta denominada SWIG para generar el ódigo C++ para la vinculación con Python. Es recomendable utilizar la versión 1.3.25 de SWIG, no la última versión, porque de momento pivy sólo funciona correctamente con con la versión with 1.3.25. Descarga los binarios para 1.3.25 desde http://www.swig.org. Luego descomprimelo y desde la línea de comandos añádelo al sistema path

set PATH=path_to_swig_1.3.25;%PATH%

y establece COINDIR a la ruta aproviada

set COINDIR=path_to_coin

En Windows el archivo de configuración de pivyespera SoWin en lugar de SoQt por defecto. No he encontrado una manera obvia para construirlo con SoQt, así que he modificado el arhivo setup.py directamente. En la línea 200 simplemente elimina la parte 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (no elimines los paréntesis de cierre).

Después de esto ve a las fuentes de pivy y ejecuta

python setup.py build

lo cual crea los archivos de fuente. Puedes llegar a un error de compilación de 'Varios archivos de cabecera no se han encontrado'. En este caso ajusta la variable INCLUDE

set INCLUDE=%INCLUDE%;path_to_coin_include_dir

y si las cabeceras de SoQt no están en el mismo sitio que las cabeceras de Coin también

set INCLUDE=%INCLUDE%;path_to_soqt_include_dir

y finalmente las cabeceras de Qt

set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

Si estas utilizando la versión Express Edition de Visual Studio puedes tener una excepción de error de clave de Python. En este caso tendrás que modificar unas cuantas cosas en msvccompiler.py situado en la instalación de Python.

Ve a la línea 122 y reemplaza la línea

vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version

con

vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version

Luego prueba de nuevo. Si te da un segundo error como

error: Python was built with Visual Studio 2003;...

debes reemplazar también la línea 128

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")

con

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")

Intenta de nuevo. Si tienes un nuevo error como

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.

entonces deberías comprobar las variables de entorno DISTUTILS_USE_SDK y MSSDK con

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

Ahora, debes encontrar un error de compilación donde una constante de tipo char no se puede convertir en char. Para solucionarlo necesitas escribir una constante antes de las líneas apropiadas. Hay 6 líneas que corregir. Después copia el directorio de pivy generado a un lugar donde el interprete de Python de FreeCAD lo pueda encontrar.

Usage

Utilización

To check if Pivy is correctly installed:

import pivy

Para tener Pivy acceso a la escena gráfica de FreeCAD haz lo siguiente:

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

Ahora puedes explorar FCSceneGraph con el comando dir().

Additonal Documentation

Documentación

Desafortunadamente la documentación sobre pivy es casi inexistente en la redt. Pero podrías encontrar la documentación de Coin útil, ya que pivy simplemente traduce las funciones de Coin, los nodos y métodos en Python, todo mantiene el mismo nombre y propiedades, teniendo en cuenta la diferencia de sintaxis entre C y Python:

También puedes echar un vistazo al archivo Draft.py en el directorio de FreeCAD Mod/Draft, ya que hace un uso importante de pivy.

pyCollada

pyCollada es una biblioteca de Python que permite a los programas leer y escribir archivos de Collada (*.DAE). Cuando pyCollada está instalado en tu sistema, FreeCAD (introducido en la versión 0.13) lo detectará y añadirá opciones de importación y exportación para manejar la apertura y guardado en el formato de archivos de Collada.

Installation

Linux

sudo apt-get install python3-collada

Puedes comprobar si pycollada fue instalada correctamente emitiendo en una consola de python:

import collada

Si no devuelve nada (no hay mensaje de error), entonces todo está bien.

Windows

En Windows desde 0.15 pycollada está incluida tanto en la versión de FreeCAD como en las construcciones de los desarrolladores, por lo que no son necesarios pasos adicionales.

Mac OS

Si estás usando la versión Homebrew de FreeCAD puedes instalar pycollada en tu sistema Python usando pip.

Si necesitas instalar pip:

$ sudo easy_install pip

Instalar pycollada:

$ sudo pip install pycollada

Si está usando una versión binaria de FreeCAD, puede decirle a pip que instale pycollada en los paquetes del sitio dentro de FreeCAD.app:

$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada

o después de descargar el código de la pycollada

$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
$ python setup.py install --prefix=/Applications/FreeCAD\ 0.16.6706.app/Contents

IfcOpenShell

  • página web: http://www.ifcopenshell.org
  • licencia: LGPL
  • opcional, necesario para ampliar las capacidades de importación de los archivos IFC

IFCOpenShell is a library currently in development, that allows to import (and soon export) Industry foundation Classes (*.IFC) files. IFC is an extension to the STEP format, and is becoming the standard in BIM workflows. When ifcopenshell is correctly installed on your system, the FreeCAD Arch Workbench will detect it and use it to import IFC files, instead of its built-in rudimentary importer. Since ifcopenshell is based on OpenCasCade, like FreeCAD, the quality of the import is very high, producing high-quality solid geometry.

Installation

Instalación

Ya que ifcopenshell es bastante nuevo, es probable que tengas que compilarlo tú mismo.

Linux

Linux

Necesitará un par de paquetes de desarrollo instalados en su sistema para compilar ifcopenshell:

liboce-*-dev
python-dev
swig

pero como FreeCAD requiere todos ellos también, si puedes compilar FreeCAD, no necesitarás ninguna dependencia extra para compilar IfcOpenShell.

Coge el último código fuente de aquí:

git clone https://github.com/IfcOpenShell/IfcOpenShell.git

El proceso de construcción es muy fácil:

mkdir ifcopenshell-build
cd ifcopenshell-build
cmake ../IfcOpenShell/cmake

o, si estás usando oce en lugar de opencascade:

cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake

Since ifcopenshell is made primarily for Blender, it uses Python3 by default. To use it inside FreeCAD, you need to compile it against the same version of Python that is used by FreeCAD. So you might need to force the Python version with additional cmake parameters (adjust the Python version to yours):

cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake

Then:

make
sudo make install

You can check that ifcopenshell was correctly installed by issuing in a Python console:

import ifcopenshell

If it returns nothing (no error message), then all is OK

Windows

Note: Official FreeCAD installers obtained from the FreeCAD website/github page now contain ifcopenshell already.

Copied from the IfcOpenShell README file

Users are advised to use the Visual Studio .sln file in the win/ folder. For Windows users a prebuilt Open CASCADE version is available from the opencascade website. Download and install this version and provide the paths to the Open CASCADE header and library files to MS Visual Studio C++.

For building the IfcPython wrapper, SWIG needs to be installed. Please download the latest swigwin version from swig website. After extracting the .zip file, please add the extracted folder to the PATH environment variable. Python needs to be installed, please provide the include and library paths to Visual Studio.

Links

LazyLoader

LazyLoader is a Python module that allows deferred loading, while still importing at the top of the script. This is useful if you are importing another module that is slow, and it is used several times throughout the script. Using LazyLoader can improve workbench startup times, but the module will still need to be loaded on first use.

Installation

Instalación

LazyLoader está incluido en FreeCAD v0.19

Usage

Uso

Necesitarás importar LazyLoader, y luego cambiar la importación de cualquier módulo que quieras que sea aplazado.

from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')

La variable Part es como se nombra el módulo en su guión. Puedes replicar "importar Part como P" cambiando la variable.

P = LazyLoader('Part', globals(), 'Part')

You can also import a module from a package.

utils = LazyLoader('PathScripts', globals(), 'PathScripts.PathUtils')

You can't import individual functions, just entire modules.

Links


Créditos


FreeCAD no sería lo que es sin las generosas contribuciones de muchas personas. Aquí hay un resumen de las personas y empresas que han contribuido a FreeCAD a lo largo del tiempo. Para ver los créditos de las librerías de terceros vea la página Librerías de terceros.

Desarrollo

Project managers

Gerentes de proyecto

Desarrolladores principales del proyecto FreeCAD:

Main developers

Principales desarrolladores

Personas que trabajan regularmente en el código de FreeCAD (recuperado de https://github.com/FreeCAD/FreeCAD/graphs/contributors):

Other coders

Otros codificadores

Otras personas que contribuyeron con código al proyecto FreeCAD:

  • Barleyman
  • Berthold Grupp
  • dbtayl
  • Dmitry Chigrin
  • ezzieyguywuf
  • fandaL
  • Georg Wiora
  • Graeme van der Vlugt
  • itain
  • j-dowsett
  • Jacques-Antoine Gaudin
  • jcc242
  • jmaustpc
  • Joachim Zettler
  • jobermayr
  • Johan3DV
  • jonnor
  • keithsloan52
  • Ken Cline
  • Mandeep Singh
  • marktaff
  • Martin Burbaum
  • maurerpe
  • ovginkel
  • peterl94
  • plaes
  • poutine70
  • TheMarkster
  • qingfengxia
  • Remigiusz Fiedler (DXF-parser)
  • SebKuzminsky
  • tomate44
  • triplus
  • usakhelo

Companies

Empresas

Empresas que han donado código, activos o tiempo de desarrollo:

Forum moderators

Moderadores del foro

Responsables del Foro de FreeCAD (recuperado de http://forum.freecadweb.org/memberlist.php?mode=team):

Community

Comunidad

La gente de la comunidad que se esfuerza en ayudar al proyecto FreeCAD, ya sea siendo activos en el foro, manteniendo un blog sobre FreeCAD, haciendo tutoriales en vídeo, empaquetando FreeCAD para Windows/Linux/MacOS X, escribiendo un libro de FreeCAD... (listado por orden alfabético) (recuperado de http://forum.freecadweb.org/memberlist.php?mode=&sk=d&sd=d#memberlist)

Documentation writers

Escritores de la documentación

Personas que escribieron la documentación de esta wiki:

Translators

Traductores

Personas que ayudaron a traducir la aplicación FreeCAD (recuperado de https://crowdin.com/project/freecad):

Addons developers

Desarrolladores de complementos

Desarrolladores de complementos de FreeCAD (recuperados de https://github.com/FreeCAD/FreeCAD-addons):