Manual/sv

From FreeCAD Documentation
Revision as of 21:44, 20 February 2015 by Renatorivo (talk | contribs)

Detta är FreeCAD manualen. Den innehåller de viktiga delarna ur FreeCADs dokumentationswiki. Den är avsedd att skrivas ut som ett enda stort dokument, så om du läser detta online, så kanske du föredrar att hoppa direkt tillOnline hjälp versionen, vilken är lättare att använda.



150
150

Välkommen till FreeCAD on-line hjälp

Detta dokument har skapats automatiskt av innehållet i den officiella FreeCAD wiki dokumentationen, vilken kan läsas online på http://www.freecadweb.org/wiki/index.php?title=Main_Page. Eftersom wikin underhålls och utvecklas kontinuerligt av FreeCAD communityn av utvecklare och användare, så kan du finna att online-versionen innehåller mer eller nyare information än detta dokument. Men vi hoppas i alla fall att du kommer hitta all den information du behöver här. Om du har frågor som du inte kan hitta svaren på i detta dokument, ta en titt på FreeCAD forumet, där din fråga kanske finns besvarad, eller du finner någon som kan hjälpa dig.

Hur man använder detta dokument

Detta dokument är uppdelat i flera avsnitt: introduktion, användande, skriptning och utveckling, de sista tre är specifikt tillägnade de tre breda FreeCAD användarkategorierna: slutanvändare, som helt enkelt vill använda programmet, experter, som är intresserade av FreeCAD's skriptmöjligheter och vill förändra några av dess egenskaper, och utvecklare, som vill använda FreeCAD som en bas för att utveckla sina egna applikationer. Om du aldrig har använt FreeCAD innan, så föreslår vi att du startar med introduktionen.

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.

Bidra

Som du kanske märkt tidigare, så är programmerare riktigt dåliga manualskrivare! För dem är allting självklart, eftersom de skrev programmet på det sättet. Därför är det viktigt att användare med god erfarenhet hjälper oss att skriva och revidera dokumentationen. Ja, vi menar dig! Hur, frågar du dig? Gå bara till wikin http://www.freecadweb.org/wiki/index.php i användarsektionen. Du kommer att behöva ett sourceforge konto för att logga in, sedan kan du börja att redigera!

Online Help Toc/sv
About FreeCAD/sv


Introduktion

FreeCAD är en allmän 3D CAD modellerare. Utvecklingen är helt baserad på öppen källkod (GPL & LGPL Licens). FreeCAD riktar sig direkt till mekanisk konstruktion och produkt design men passar även i ett bredare område inom konstruktion, som arkitektur eller andra konstruktions specialiteter.


FreeCAD erbjuder verktyg liknande Catia, SolidWorks eller Solid Edge, och hamnar därför i samma kategorier som MCAD, PLM, CAx och CAE. Det kommer att bli en parametrisk solidmodellerare med en modulär mjukvaruarkitektur vilket gör det lätt att erbjuda extre funktionalitet utan att behöva ändra kärnsystemet.


Som med många moderna 3D CAD modellerare så kommer den att ha en 2D komponent för att kunna skapa ritningar av 3D modellen, men direkt 2D ritare (som AutoCAD LT) är inte avsikten, inte heller animeringar eller organiska former (som Maya, 3ds Max eller Cinema 4D), fast tack vare sin stora anpassningsbarhet, så kan FreeCAD bli användbart inom ett mycket större område än vad som avses för tillfället.


En annan viktig sak för FreeCAD är ett flitigt användande av alla de fantastiska öppen-källkodsbibliotek som finns därute inom området Vetenskaplig databehandling. Bland dem är OpenCascade, en kraftfull CAD kärna, Coin3D, en inkarnation av OpenInventor, Qt, det världsberömda användargränssnittsverktyget, och Python, en av de bästa skriptspråken som finns. Själva FreeCAD kan även användas som ett bibliotek av andra program.


FreeCAD är också helt multiplattform, och fungerar för närvarande perfekt på Windows och Linux/Unix och Mac OSX systems, med exakt samma utseende och funktionalitet på alla plattformarna.


Blev du nyfiken? Ta en titt på Egenskaper eller Introduktion artiklarna, eller hoppa direkt till Användarhubben!

FreeCAD features tools similar to CATIA, SolidWorks, Solid Edge or Revit, and therefore also falls into the category of CAD, PLM, CAx, CAE and BIM. It is a feature based parametric modeler with a modular software architecture making it possible to provide additional functionality without modifying the core system.

As with other CAD modelers it has many 2D components in order to sketch planar shapes or create production drawings. However, direct 2D drawing (like Inkscape or AutoCAD LT) is not the focus, neither are animation or mesh editing (like Blender, Maya, 3ds Max, or Cinema 4D). Nevertheless, thanks to its wide adaptability, FreeCAD is useful in a much broader area around its base feature set.

FreeCAD makes heavy use of open-source libraries that exist in the field of scientific computing. Among them are Open Cascade Technology (OCCT), a powerful CAD kernel; Coin3D, a toolkit for 3D graphics development compatible with Open Inventor; Qt, the world-famous user interface framework; and Python, a modern scripting language. FreeCAD itself can also be used as a library by other programs.

FreeCAD is also multi-platform, and currently runs on Linux/Unix, Windows, and macOS systems with the same look and functionality on all platforms.

For more information about FreeCAD's capabilities, take a look at the feature list, the latest release notes, and the getting started articles, or see more screenshots.

About the FreeCAD project

The FreeCAD project was started as far back as 2001, as described on the history page.

FreeCAD is maintained and developed by a community of enthusiastic developers and users and is built through the patient work of hundreds of contributors, some regular, some occasional. Most work on FreeCAD as volunteers. The FreeCAD forum is where most of the ideas and decisions are discussed, and the GitHub repository is where the code is being kept, shared, discussed and worked on. Anybody is welcome to participate.

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.


Online Help Startpage/sv
Feature_list/sv


Detta är en extensiv, fast inte komplett, lista på de funktioner som FreeCAD har. Om du vill se in i framtiden, se utvecklingskartan för en snabb överblick så är Skärmdumpar en bra plats att gå till.

Release notes

Allmäna funktioner

  • En komplett OpenCasCade-baserad geometrikärna som tillåter komplexa 3D operationer på komplexa formtyper, och stöder nativt koncept som brep, nurbs, booleska operationer eller fasningar
  • En full parametrisk modell som tillåter valfri typ av parameter-drivna anpassade objekt, som även helt kan programmeras i python
  • Komplett åtkomst från den inbyggda python tolken, makron eller externa skript till nästan alla delar i FreeCAD, so till exempel skapande och omvandling av geometri, 2D eller 3D representationen av den geometrin (Scengrafen) eller även FreeCAD gränssnittet
  • Import/export till standard format som STEP, IGES, OBJ, DXF, SVG U3D eller STL
  • En Skissare med begränsningslösare, som låter dig skissa geometri-begränsade 2D former. Skissare tillåter dig för tillfället att bygga flera typer av begränsad geometri, och sedan använda dem som en bas att bygga andra objekt i FreeCAD.
  • En Robot simulerings modul som tillåter dig att studera robotrörelser. Robotmodulen har redan ett utökat grafiskt gränssnitt, vilket kan användas för ett smidigt arbetsflöde.
  • En Ritningsark modul som låter dig skapa 2D vyer på dina 3D modeler på ett ritningsark. Denna modul producerar sedan färdiga SVG eller PDF dokument. Modulen är ännu funktionsfattig, men har redan en kraftfull python-funktionalitet.
  • En Renderingsmodul som kan exportera 3D objekt för rendering med externa rendererare. Stödjer för närvarande endast povray, men förväntas stödja andra renderare i framtiden.
  • En Arkitektur modul som tillåter BIM-likt arbetsflöde, med IFC kompatibilitet. Skapandet av arkitekturmodulen diskuteras mycket av communityn här.
BIM-like workflow, with IFC compatibility. The making of the Arch Workbench is heavily discussed by the community here.

Allmänna funktioner

  • FreeCAD är multi-plattform. Det kan köras och beter sig på exakt samma sätt på Windows Linux och Mac OSX plattformarna.
  • FreeCAD är en helgrafisk applikation. FreeCAD har ett komplett grafiskt användargränssnitt baserat på det berömda Qt strukturen, med en 3D visare baserad på Open Inventor, vilket tillåter snabb rendering av 3D scener och en mycket lättåtkomlig scenrepresentation.
  • FreeCAD kan också köras som en kommandolinje applikation, med litet minnesbehov. I kommandolinje läge, så körs FreeCAD utan ett gränssnitt, men med alla geometriverktyg. Det kan till exempel användas som en server för att producera data för andra applikationer.
  • FreeCAD kan importeras som en Python modul, inuti andra applikationer som kan köra python skript, eller i en python konsol. Som i konsol läge, så är FreeCAD's gränssnitt otillgängligt, men alla geometriverktyg finns tillgängliga.
  • Arbetsbänk koncept: I FreeCAD gränssnittet, så är verktygen grupperade i arbetsbänkar. Detta innebär att endast de verktyg som behövs för att utföra en viss uppgift visas, vilket håller arbetsytan ren och responsiv, och snabb laddning av applikationen.
  • Plugin/Modul struktur för sen laddnig av funktioner/data-typer. FreeCAD är uppdelat i en kärnapplikation och moduler, som endast laddas när de behövs. Nästan alla verktyg och geometrityper är lagrade i moduler. Moduler beter sig som plugins, och kan adderas eller tas bort från en existerande installation av FreeCAD.
  • Parametriska associativa dokumentobjekt: Alla objekt i ett FreeCAD dokument kan definierass av parametrar. Dessa parametrar kan ändras direkt, och omberäknas när som helst. Förhållandet mellan objekt lagras också, så om ett objekt ändras, så ändras även de objekt som är beroende av det.
  • Parametriska primitiver som låda, sfär, cylinder, kon eller torus.
  • Grafiska ändringsoperationer som förflyttning, rotation, skalning, spegling, offset (trivial or after Jung/Shin/Choi) eller formförändring, i valfritt plan i 3D rymden
  • Grafiskt skapande avenkel plangeometri som linjer, trådar, rektanglar, cirkelbågar eller cirklar i valfritt plan i 3D rymden
  • Modellering med raka eller rotering extrusioner, sektioneringar och avrundningar.
  • Topologiska komponenter som hörn, kanter, trådar och plan (via pythonskript).
  • Testing and repairing tools for meshes: solid test, non-two-manifolds test, self-intersection test, hole filling and uniform orientation.
  • Anteckningar som texter eller dimensioner
  • Ångra/Gör om struktur: Allt kan ångras eller göras om, med åtkomst till ångra minnet, så multipla steg kan ångras åt gången.
  • Transaktionshantering: Ångra/Gör om minnet lagrar dokumenttransaktioner och inte enstaka aktioner, vilket tillåter varje verktyg att exakt definiera vad som ska ångras eller göras om.
  • Inbyggd skript struktur: FreeCAD tillhandahåller en inbyggd Python tolk, och ett API som täcker nästan alla delar av applikationen, gränssnittet, geometrin och representationen av denna geometri i 3D visaren. Tolken kan köra från enstaka kommandon upp till komplexa skript, faktum är att hela moduler kan programmeras helt och hållet i Python.
  • Inbyggd Python konsol med syntaxmarkering, autokomplettering och klassvisare: Python kommandon kan utföras direk i FreeCAD och ge resultat omedelbart, vilket tillåter skriptskrivare att testa funktionaliteten direkt, utforska modulernas innehåll och lätt lära sig FreeCAD's innanmäte.
  • Användarinteraktion speglas i konsolen: Allt som användaren gör i FreeCAD's gränssnitt, kör pythonkod, vilken kan skrivas ut i konsolen och spelas in i makron.
  • Full makro inspelning & redigering: De pythonkommandon som körs när användaren manipulerar gränssnittet kan spelas in, om nödvändigt redigeras, och sparas för att reproduceras senare.
  • Sammansatt (ZIP baserat) dokumentformat: FreeCAD dokument som är sparade med filtypen .fcstd kan innehålla många olika informationstyper, som geometri, skript eller tumnagelikoner.
  • Fullt anpassningsbart/skriptbart grafiskt användargränssnitt. Det Qt-baserade gränssnittet i FreeCAD är helt åtkomligt via python tolken. Förutom de enkla funktioner som FreeCAD själv ger till arbetsbänkarna, så är hela Qt strukturen också tillgänglig, vilket tillåter vilken operation som helst på gränssnittet, som till exempel skapa, lägga till, docka, ändra eller ta bort widgets och verktygslådor.
  • Tumnaglare (endast Linux system för närvarande): FreeCAD's dokumentikoner visar filens innehåll i de flesta filhanterarapplikationer som till exempel gnome's nautilus.
  • en modulär MSI installerare tillåter flexibel installation på Windowssystem. Paket för Ubuntusystem är också underhållna.

Extra Workbenches

Power users have created various custom external workbenches.


About_FreeCAD/sv
Install on Windows/sv


Installation

Installera på Windows


Standard Installation

The easiest way to install the latest stable version of FreeCAD is to use the installer, see the Download page.

If you would like to download either a 64 bit or unstable development version, see the Download page. Download/sv

After downloading the installer, double-click it to start the installation process.

Below is more information about some technical options. But most users don't need more than the installer. Head to Getting started once installation is complete.

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.

Avinstallering

Med

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.


Feature list/sv
Install on Unix/sv


Installera på Unix/Linux


Overview

The installation of FreeCAD on most well-known Linux systems is endorsed by the community, and FreeCAD is available via the package manager on those systems. The FreeCAD team also provides some:

Ubuntu and Ubuntu-based systems

Many Linux distributions are based on Ubuntu and share its repositories. Besides official variants (Kubuntu, Lubuntu and Xubuntu), there are non official derivatives like Linux Mint, Voyager and others. The installation options below (Expand) should be compatible with these systems.

Official version

FreeCAD is available from the Ubuntu Universe repository, and can be installed via the Software Center or from the terminal:

sudo apt install freecad

Note: the Ubuntu Universe package may be outdated as the packaging may lag behind the latest stable source code. In this case, it is suggested to install the package from the -stable PPA below. In addition, installing the -daily package can be done to test the development branch.

Stable PPA version

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

Personal Package Archive (PPA) for the stable FreeCAD release is maintained by the FreeCAD community on Launchpad. The Launchpad repository is called FreeCAD Stable Releases .

GUI

Install the stable PPA via the Graphical User Interface (GUI):

1. Navigate to Ubuntu Software → Software & Updates → Software Sources → Other Software
2. Click on Add, then copy and paste the following line
ppa:freecad-maintainers/freecad-stable
3. Add the source, close the dialog, and reload your software sources, if asked.

Now you can find and install the last stable FreeCAD version from the Ubuntu Software Center.

CLI

Install the stable PPA via the Command Line Interface (CLI):

1. Add the PPA to your software sources:
sudo add-apt-repository ppa:freecad-maintainers/freecad-stable
2. Retrieve the updated package lists:
sudo apt update
3. Then install FreeCAD along with its offline documentation:
sudo apt install freecad freecad-doc

Note: due to packaging problems, in certain versions of Ubuntu the freecad-doc package has collided with the installation of FreeCAD or one of its dependencies; if this is the case, remove the freecad-doc package, and only install the freecad package. If the freecad-doc package doesn't exist, then ignore it.

Checking Installation

4. Once you have the stable PPA added to your sources using one of the above methods, the freecad package will install this PPA version over the one provided by the Ubuntu Universe repository. You can see the available versions with the following apt-cache command:
apt-cache policy freecad
The output should look similar to the following (of course the version info will vary):
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. Invoke the stable (PPA) version of FreeCAD from the GUI or CLI. The latter method is as follows:
./freecad

Development PPA (Daily)

As FreeCAD is in constant development, you may wish to install the daily package to keep with the latest improvements and bug fixes. The repository is also hosted on Launchpad and is called freecad-daily.

This version is compiled daily from the official master repository. Please beware that although it will contain new features and bug fixes, it may also have newer bugs, and be unstable.

Add the daily PPA to your software sources, update the package lists, and install the daily package:

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

Every day you can update to the latest daily:

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

Note: in some cases new code or dependencies added to FreeCAD will cause packaging errors; if this happens, a daily package may not be generated until the maintainers manually fix the problems. If you wish to continue testing the latest code, you should get the source code and compile FreeCAD directly; for instructions see compiling.

Run the daily (PPA) version of FreeCAD:

freecad-daily

Note: it is possible to install both the -stable and -daily packages in the same system. This is useful if you wish to work with a stable version, and still be able to test the latest features in development. Notice that the executable for the daily version is freecad-daily, but for the stable version it is just freecad.

Debian and other Debian-based systems

Since Debian Lenny, FreeCAD is available directly from the Debian software repositories and can be installed via synaptic or simply with:

sudo apt-get install freecad

OpenSUSE

FreeCAD is typically installed with YAST (abbr. Yet another Setup Tool) the Linux operating system setup and configuration tool, or in any terminal/console (root rights required) with:

zypper install FreeCAD

Note: This procedure only covers the installation of officially released stable FreeCAD program versions, depending on the installed links to the program package repositories of your OS version. The openSUSE package may be outdated as the packaging may lag behind the latest stable source code. In this case, it is suggested to install the package manually from the below indicated (Expand) source repositories.

A vast release program for FreeCAD package builds are offered. Please visit for a survey:

Survey of repositories on openSUSE

Generally for selecting the correct openSUSE distribution needed it is necessary to click on the particular View button.

Stable

The stable package version: Stable repositories on openSUSE. The correct openSUSE distribution version must be selected in the lower part of the web page.

Note: openSUSE has several options to choose from when downloading FreeCAD. To view these options, visit Survey of stable repositories on openSUSE.

Development

Latest development releases AKA unstable: Unstable repositories listings on openSUSE

It is recommended to grab the binary packages directly. Then select the correct distribution for your installed openSUSE OS.

Gentoo

FreeCAD can be built/installed simply by issuing:

emerge freecad

Fedora

FreeCAD has been included in the official Fedora packages since Fedora 20. It can be installed from the command line with:

sudo dnf install freecad

On older Fedora releases, that was:

sudo yum install freecad

The gui packages managers can also be used. Search for "freecad". The official release package version tends to be well behind the FreeCAD releases. Package: freecad shows the versions included in the Fedora repositories over time and versions.

More current versions can be obtained by downloading one of the .AppImagereleases from the github repository. These work fine on Fedora.

If you want to keep up with the absolute latest daily builds, FreeCAD is also available on copr. To install the build from there, in a terminal session, enter:

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

That leaves the copr repository active, so

sudo dnf upgrade

or equivalent, will update to the latest FreeCAD build, along with updates from any of the other active repos. If you want something a bit more stable, you can disable @freecad/nightly again after the initial install. The copr repository only keeps builds from the past 2 weeks. This is not a solution if you want to pick a specific older version.

Instructions are also available on compile FreeCAD yourself, including a script specifically for Fedora. With a minor change, to checkout the specific commit from git, any version since about FreeCAD 0.15 can be built on any distribution since Fedora 21.

Arch

Installing FreeCAD on Arch Linux and derivatives (ex. Manjaro):

pacman -S freecad

Other

If you find out that your system features FreeCAD but is not documented in this page, please tell us on the forum!

Many alternative, non-official FreeCAD packages are available on the net, for example for systems like slackware or fedora. A search on the net can quickly give you some results.

Installing on other Linux/Unix systems

Many common Linux distros now include a precompiled FreeCAD as part of the standard packages. This is often out of date, but is a place to start. Check the standard package managers for your system. One of the following (partial) list of commands could install the official version of FreeCAD for your distro from the terminal. These probably need administrator privileges.

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

The package name is case sensitive, so try `FreeCAD` as well as `freecad`. If that does not work for you, either because your package manager does not have a precompiled FreeCAD version available, or because the available version is too old for your needs, you can try installing the Flatpak or Snap packages (these work on most x86_64 Linux distributions) or try downloading one of the .AppImage releases from the github repository. These also tend to work on most x86_64 Linux distributions, without any special installation. Just make sure the downloaded file is marked as executable, then run it.

If that still is not good enough, and you cannot locate another source of a precompiled package for your situation, you will need to compile FreeCAD yourself.

Next Step

Head to Getting started once installation is complete.



Installera på Mac


FreeCAD kan installeras på Mac OS X i ett steg genom att använda Installeraren. Denna sida beskriver användandet och funktionerna i FreeCAD installeraren. Den inkluderar också avinstallations instruktioner.

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

You can also use a package manager such as HomeBrew to keep your software updated. Instructions to install HomeBrew can be seen here. When HomeBrew installed you can simply install FreeCAD through your bash terminal with

brew install --cask freecad

and to use the latest version available on HomeBrew you may run

brew install freecad

If there are any issues with the HomeBrew Cask or Formula you may report them to here.

This page describes the usage and features of the FreeCAD installer. It also includes uninstallation instructions. Head to Getting started once installation is complete.

Enkel Installation

FreeCAD installeraren erbjuds som ett Installationspaket(.mpkg) bifogad i en diskavbildningsfil.

The FreeCAD installer is provided as a app package (.app) enclosed in a disk image file.

Du kan ladda ned den senaste installeraren från Nedladdningssidan. Efter att du laddat ned filen, montera diskavbildningen, kör sedan Install FreeCAD paketet.

Installeraren kommer att presentera en Customize Installation skärm som listar de paket som kommer att installeras. Om du vet att du redan har något av dessa paket, så kan du välja bort dem genom att använda kryssrutorna. Om du inte är säker, lämna alla rutor markerade.

Avinstallation

Det finns för närvarande ingen avinstallerare för FreeCAD. För att helt ta bort FreeCAD och alla installerade komponenter, dra följande filer och mappar till papperskorgen:

  • I /Applications:
    • FreeCAD

Det är allt. Eventuellt så kommer FreeCAD att finnas tillgängligt som ett applikationspaket så att allt detta trubbel kommer att försvinna.


Install on Unix/sv
Getting started/sv


Upptäcka FreeCAD


Förord

FreeCAD är en CAD/CAE parametrisk modelleringsapplikation. Den är fortfarande i ett tidigt utvecklingsstadium, så förvänta dig inte att du ska kunna använda den till professionellt arbete än.

Men, om du är nyfiken på hur FreeCAD ser ut och vilka funktioner som håller på att utvecklas, så är du välkommen att ladda ned den och testa den. För tillfället finns det redan många funktioner, men gränssnittet för många av dem har ännu inte skapats. detta innebär att om du kan lite om python, så kommer du redan att kunna producera och förändra komplex geometri relativt enkelt. Om inte, så kommer du förmodligen att upptäcka att FreeCAD fortfarande har en del att erbjuda dig. Men, ha tålamod, detta kommer att förändras snart.

Och om du efter att ha testat den har kommentarer, ideer eller åsikter, var vänlig att dela dem med oss på FreeCAD diskussionsforum!

See also:

Installation

Först av allt (om det inte redan är gjort), ladda ned och installera FreeCAD. Se Nedladdningssidan för information om nuvarande versioner och updateringar. Det finns färdiga installationspaket för Windows (.msi), Ubuntu & Debian (.deb) openSUSE (.rpm) och Mac OSX.

Utforska FreeCAD

FreeCAD gränssnittet när du startar den första gången. Se fler skärmdumpar här.

FreeCAD är en allmän, allt-i-allo 3D modelleringsapplikation, fokuserad på mekanisk konstruktion och relaterade områden, som andra konstruktionsspecialiteter eller arkitektur. Den är utformad som en plattform för utveckling av vilken 3D applikation som helst, men även för att göra väldigt specifika uppgifter. För det ändamålet så är dess gränssnitt uppdelat i en serie med Arbetsbänkar. Arbetsbänkar gör att du ändrar gränssnittsinnehållet till att endast visa de verktyg som är nödvändiga för en specifik uppgift, uppgiftsgrupper.

FreeCAD gränssnittet kan därför beskrivas som en mycket enkel behållare, med en menyrad, en 3D visningsområde, och några sidopaneler för att visa sceninnehållet eller objektegenskaper. Allt innehåll i dessa paneler kan förändras beroende på arbetsbänken.

När du startar FreeCAD för den första gången, så kommer en "generell" arbetsbänk att presenteras för dig, som vi kallar "komplett arbetsbänk". Denna arbetsbänk samlar de mognaste verktygen från andra arbetsbänkar. Eftersom FreeCAD är ganska ungt och inte har använts för något specialiserat arbete ännu, så är denna arbetsbänk väldigt smidig för att utforska FreeCAD lättare. Alla verktyg som är tillräckligt bra för att producera geometri finns här.

See a full explanation in Interface.

1. The main view area, which can contain different tabbed windows, principally the 3D view.
2. The 3D view, showing the geometrical objects in the document.
3. The tree view (part of the combo view), showing the hierarchy and construction history of objects in the document; it can also display the task panel for active commands.
4. The property editor (part of the combo view), which allows viewing and modifying properties of the selected objects.
5. The selection view, which indicates the objects or sub-elements of objects (vertices, edges, faces) that are selected.
6. The report view (or output window), where messages, warnings and errors are shown.
7. The Python console, where all the commands executed are printed, and where you can enter Python code.
8. The status bar, where some messages and tooltips appear.
9. The toolbar area, where the toolbars are docked.
10. The workbench selector, where you select the active workbench.
11. The standard menu, which holds basic operations of the program.

The main concept behind the FreeCAD interface is that it is separated into workbenches. A workbench is a collection of tools suited for a specific task, such as working with meshes, or drawing 2D objects, or constrained sketches. You can switch the current workbench with the workbench selector. You can customize the tools included in each workbench, add tools from other workbenches or even self-created tools, that we call macros. Widely used starting points are the PartDesign Workbench and Part Workbench.

When you start FreeCAD for the first time, you are presented with the Start page. Here is what it looks like for version 0.19:

The Start page allows you to quickly jump to one of the most common workbenches, open one of the recent files, or see the latest news from the FreeCAD world. You can change the default workbench in the preferences.

Navigera i 3D rymden

FreeCAD har två olika navigationslägen tillgängliga, som kan ställas in i inställningsdialogen. I standardläget, så utförs zoomning med Mushjulet, panorering med Mittre musknappen, och rotation med vänster musknapp och Mittre musknappen samtidigt. Val av ett objekt görs genom att klicka på det med vänster musknapp, med CTRL nedtryckt om du vill välja flera objekt.

Du har också flera förinställda vyer (Toppvy, Frontvy, etc) tillgängliga i Visa menyn och på verktygslådan Visa, och via numeriska genvägar (1, 2, etc...)

Skript

Och slutligen, en av de kraftfullaste funktionerna i FreeCAD är skript miljön. Från den integrerade pythonkonsolen (eller från något externt pythonskript), så får du åtkomst till nästan vilken del som helst av FreeCAD, skapa eller ändra geometri, ändra representationen av dessa objekt i 3D scenen eller förändra FreeCAD's gränssnitt. Python skript kan även användas i makron, vilket erbjuder en lätt metod att skapa anpassade kommandon.

FreeCAD has several navigation modes available, that change the way you use your mouse to interact with the objects in the 3D view and the view itself. One of them is specifically made for touchpads, where the middle mouse button is not used. The default navigation mode is CAD navigation. You can quickly change the current navigation mode by using the button in the Status bar or by right-clicking an empty area of the 3D view.

You also have several view presets (top view, front view, etc) available in the View menu, on the View toolbar, and by numeric shortcuts (1, 2, etc...). By right-clicking on an object or on an empty area of the 3D view, you have quick access to some common operations, such as setting a particular view, or locating an object in the Tree view.

First steps with FreeCAD

FreeCAD's focus is to allow you to make high-precision 3D models, to keep tight control over those models (being able to go back into modelling history and change parameters), and eventually to build those models (via 3D printing, CNC machining or even construction worksite). It is therefore very different from some other 3D applications made for other purposes, such as animation film or gaming. Its learning curve can be steep, especially if this is your first contact with 3D modeling. If you are stuck at some point, don't forget that the friendly community of users on the FreeCAD forum might be able to get you out in no time.

The workbench you will start using in FreeCAD depends on the type of job you need to do: If you are going to work on mechanical models, or more generally any small-scale objects, you'll probably want to try the PartDesign Workbench. If you will work in 2D, then switch to the Draft Workbench, or the Sketcher Workbench if you need constraints. If you want to do BIM, launch the Arch Workbench. And if you come from the OpenSCAD world, try the OpenSCAD Workbench. There are also many community-developed external workbenches available.

You can switch workbenches at any time, and also customize your favorite workbench to add tools from other workbenches.

Working with the PartDesign and Sketcher workbenches

The PartDesign Workbench is made to build complex objects, starting from simple shapes, and adding or removing pieces (called "features"), until you get to your final object. All the features you applied during the modelling process are stored in a separate view called the tree view, which also contains the other objects in your document. You can think of a PartDesign object as a succession of operations, each one applied to the result of the preceding one, forming one big chain. In the tree view, you see your final object, but you can expand it and retrieve all preceding states, and change any of their parameter, which automatically updates the final object.

The PartDesign workbench makes heavy use of another workbench, the Sketcher Workbench. The sketcher allows you to draw 2D shapes, which are defined by applying Constraints to the 2D shape. For example, you might draw a rectangle and set the size of a side by applying a length constraint to one of the sides. That side then cannot be resized anymore (unless the constraint is changed).

Those 2D shapes made with the sketcher are used a lot in the PartDesign workbench, for example to create 3D volumes, or to draw areas on the faces of your object that will then be hollowed from its main volume. This is a typical PartDesign workflow:

  1. Create a new sketch
  2. Draw a closed shape (make sure all points are joined)
  3. Close the sketch
  4. Expand the sketch into a 3D solid by using the pad tool
  5. Select one face of the solid
  6. Create a second sketch (this time it will be drawn on the selected face)
  7. Draw a closed shape
  8. Close the sketch
  9. Create a pocket from the second sketch, on the first object

Which gives you an object like this:

At any moment, you can select the original sketches and modify them, or change the extrusion parameters of the pad or pocket operations, which will update the final object.

Working with the Draft and Arch workbenches

The Draft Workbench and Arch Workbench behave a bit differently than the other workbenches above, although they follow the same rules, which are common to all of FreeCAD. In short, while the Sketcher and PartDesign are made primarily to design single pieces, Draft and Arch are made to ease your work when working with several, simpler objects.

The Draft Workbench offers you 2D tools somewhat similar to what you can find in traditional 2D CAD applications such as AutoCAD. However, 2D drafting being far away from the scope of FreeCAD, don't expect to find there the full array of tools that these dedicated applications offer. Most of the Draft tools work not only in a 2D plane but also in the full 3D space, and benefit from special helper systems such as Work planes and object snapping.

The Arch Workbench adds BIM tools to FreeCAD, allowing you to build architectural models with parametric objects. The Arch workbench relies extensively on other modules such as Draft and Sketcher. All the Draft tools are also present in the Arch workbench, and most Arch tools make use of the Draft helper systems.

A typical workflow with Arch and Draft workbenches might be:

  1. Draw a couple of lines with the Draft Line tool
  2. Select each line and press the Wall tool to build a wall on each of them
  3. Join the walls by selecting them and pressing the Arch Add tool
  4. Create a floor object, and in the Tree view drag your walls into the floor object
  5. Create a building object, and in the Tree view drag your floor (which now includes the walls) into the building object
  6. Create a window by clicking the Window tool, select a preset in its panel, then click on a face of a wall
  7. Add dimensions by first setting the working plane if necessary, then using the Draft Dimension tool

Which will give you this:

More on the Tutorials page.

Addons

Any user can develop their own new features for FreeCAD and make them available to the FreeCAD community as an addon.

There are three types of addons:

  • Macros: short snippet of Python code that provides a new tool or functionality in a single file ending with .FCMacro.
  • Workbenches: collections of Python files that provide related Gui Commands (tools) centered around a particular topic.
  • Preference Packs: distributable collections of user preferences.

Scripting

And finally, one of the most powerful features of FreeCAD is the scripting environment. From the integrated python console (or from any other external Python script), you can gain access to almost any part of FreeCAD, create or modify geometry, modify the representation of those objects in the 3D scene or access and modify the FreeCAD interface. Python scripting can also be used in macros, which provide an easy method to create custom commands.

What's new


Install on Mac/sv
Mouse Model/sv


Arbeta med FreeCAD

3D navigering


Overview

The FreeCAD mouse navigation consists of the commands used to visually navigate the 3D space and interact with the objects displayed. FreeCAD supports multiple mouse navigation styles. The default navigation style is referred to as "CAD Navigation," and is very simple and practical, but FreeCAD also provides alternative navigation styles which you can choose according to your preferences.

For more information about selecting objects see Selection methods.

For more information about manipulating objects see Std TransformManip.

Selecting a navigation style

  1. Do one of the following:
    • Press the button in the Status bar.
    • Right-click an empty area in the 3D view, and select Navigation styles from the context menu.
    • Use the Preferences Editor. In the menu select Edit → Preferences and then Display → Navigation → 3D Navigation.
  2. Select a style from the list.
  3. Optionally change the Orbit style: press the button in the Status bar and then choose Settings → Orbit style. See Preferences Editor.
  4. Optionally change the Rotation mode. See Preferences Editor.
  5. If the CAD navigation style is selected: optionally change the Enable animation setting. See Preferences Editor.

Available navigation styles

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

Blender Navigation

The Blender navigation style was modeled after Blender.

The Blender Navigation was modeled after Blender. Previously there was no mouse-only panning, and it required use of the SHIFT key to pan the view. This changed in 2016 with a feature-addition. In order to pan the view, you can now press both left and right mouse buttons and drag in the view.

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

CAD Navigation (default)

This is the default navigation style and allows the user a simple control of the view, and does not require the use of keyboard keys except to make multi-selections.

Select Pan Zoom Rotate view
First method
Rotate view
Alternate method
Press the left mouse button over an object you want to select.

Holding down Ctrl allows the selection of multiple objects.

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.

The cursor location when the middle mouse button is pressed determines the center of rotation. Rotation works like spinning a ball which rotates around its center. 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. introduced in version 0.17 Zoom mode: hold the Ctrl and Shift keys, press the right mouse button once, then move the pointer. introduced in version 0.17 Rotate mode: hold the Shift key, press the right mouse button once, then move the pointer. introduced in version 0.17
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.

Gesture Navigation (v0.16)

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

Maya-Gesture Navigation

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.

In Maya-Gesture Navigation, all view movements are activated pressing ALT and a mouse button, so that it will be needed to have a 3 button mouse in order to correctly use this navigation mode. Alternately it's possible to use gestures as this mode was been developed over the normal Gesture Navigation mode.

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

Alternatively, use the mouse wheel to zoom in and out.

Hold Alt and the left mouse button, then move the pointer.

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 navigation

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

OpenInventor Navigation

In OpenInventor (formerly Inventor) Navigation, modeled after Open Inventor (not to be confused with Autodesk Inventor), there is no mouse-only selection. In order to select objects, you must hold down the CTRL key.

Select Pan Zoom Rotate view
{{{Shift}}}+
Hold Ctrl, then 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 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.

This style is not based on 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.

Revit navigation

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.

Touchpad Navigation

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.

In Touchpad Navigation, neither panning, nor zooming, nor rotating the view, are mouse-only (or touchpad-only) operations.

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.

Hardware support

FreeCAD also supports some 3D input devices.

Recommended navigation for macOS

On MacBooks with a trackpad the Gesture navigation works very well, but the gestures have a special meaning:

  • Zoom: drag with two fingers.
  • Rotate: drag with three fingers.
  • Pan: Ctrl + three fingers.

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.


Getting started/sv
Document structure/sv


FreeCAD Dokumentet


Ett FreeCAD document inehåller alla objekten i din scen. Det kan innehålla grupper, och objekt gjorda med valfri arbetsbänk. Du kan därför växla mellan arbetsbänkar, och ändå arbeta med samma dokument. Dokumentet är det som sparas till disk när du sparar ditt arbete. Du kan också äppna flera dokument samtidigt i FreeCAD, och öppna flera vyer av samma dokument.

Inuti dokumentet, så kan objekten flyttas in i grupper, och ha unika namn. Hantering av grupper, objekt och objektnamn görs huvudsakligen från Trädvyn. Det kan förstås också göras, som allt annat i FreeCAD, från pythontolken. I trädvyn, så kan du skapa grupper, flytta objekt till grupper, radera objekt eller grupper, genom att högerklicka i trädvyn eller på ett objekt, döpa om objekt genom att dubbelklicka på dess namn, eller möjligtvis andra operationer, beroende på vilken arbetsbänk som används.

Objekten inuti ett FreeCAD dokument kan vara av olika typer. Varje arbetsbänk kan skapa sina egna objekttyper, till exempel Nät arbetsbänken skapar nätobjekt, Del arbetsbänken skapar Del objekt, Rit arbetsbänken skapar också Del objekt, etc.

Om det finns åtminstone ett dokument öppet i FreeCAD, så finns det alltid ett och endast ett aktivt dokument. Det är det dokument som syns i den nuvarande 3D vyn, dokumentet som du för närvarande jobbar med.

Applikations och Användargränssnitt

Liksom nästan allt annat i FreeCAD, så är användargränssnittsdelen separerad från basapplikationsdelen. Detta gäller även för dokument. Dokumenten utgörs också av två delar: Applikationsdokumentet, vilket innehåller våra objekt, och Vydokumentet, vilket innehåller skärmrepresentationen av våra objekt.

Tänk på det som två rymder, där objekten är definierade. Dess konstruktiva parametrar (är det en kub? en kon? vilken storlek?) lagras i Applikationsdokumentet, emedan dess grafiska representation (Är den ritad med svarta linjer? med blå ytor?) lagras i Vydokumentet. Varför är det så? därför att FreeCAD kan även användas UTAN grafiskt gränssnitt, till exempel inuti andra program, och vi måste fortfarande kunna manipulera våra objekt, även om inget ritas på skärmen.

En annan sak som lagras i Vydokumentet är 3D vyer. Ett dokument kan ha flera vyer öppnade, så du kan inspektera ditt dokument från flera håll samtidigt. Du kanske vill se en toppvy och en frontvy av ditt arbete samtidigt? Då kommer du att ha två vyer av samma dokument, båda lagrade i Vydokumentet. Skapande av nya vyer eller stänga vyer kan göras från Visa menyn eller genom att högerklicka på en vytabb.

Skript

Dokument kan lätt skapas, kommas åt och ändras från tolken. Till exempel:

FreeCAD.ActiveDocument

Kommer att returnera det nuvarande (aktiva) dokumentet

FreeCAD.ActiveDocument.Blob

Kommer åt ett objekt kallat "Blob" inuti ditt dokument

FreeCADGui.ActiveDocument

Kommer att returnera det vydokument som är associerat med det nuvarande dokumentet

FreeCADGui.ActiveDocument.Blob

Kommer åt den grafiska representationen (vy) delen av vårt Blob objekt

FreeCADGui.ActiveDocument.ActiveView

Kommer att returnera nuvarande vy


Mouse Model/sv
Preferences Editor/sv


Ställa in användarpreferenser


Introduction

FreeCAD inställningssystem finns i Redigera menyn → Alternativ.

FreeCAD's funktionalitet är uppdelat i olika moduler, där varje modul är ansvarig för att en specifik arbetsbänk ska fungera. FreeCAD använder sig också av ett koncept kallat sen laddning, vilket innebär att komponenter endast laddas när de behövs. du kanske har märkt att när du väljer en arbetsbänk i FreeCAD's verktygslåda, så laddas den arbetsbänken och alla dess komponenter just då. Detta inkluderar dess inställningar.

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.

Om inga moduler är laddade, så kommer du att ha två konfigurationssektioner, ansvariga för de allmäna applikationsinställningarna och för visningsinställningar.

Pressing the Reset button in the lower left corner of the Preferences dialog opens a menu (introduced in version 1.0) 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.

De allmäna inställningarna

När du startar FreeCAD utan någon arbetsbänk laddad, så kommer du ha ett minimalt inställningsfönster. Alltefter som du laddar fler moduler, så kommer nya avsnitt fram i inställningsfönstret, vilket tillåter dig att konfigurera detaljer för varje arbetsbänk.

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

Allmän

On the General tab you can specify the following:

Name Description
Ändra språk Selection of the language of the FreeCAD user interface
Storlek på listan för senast öppnade filer Specification how many files should be listed in the recent files list
Aktivera staplad bakgrund If checked, the background of FreeCAD's main window will by default consist of tiles of this image

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.

Formatmall Selection of a style sheet. Formatmalls define how the user interface of FreeCAD looks. For technical details about the style sheets, see themes.
Storlek på verktygsfältsikonerna Selection of the size for the toolbar icons
Trädvyläge Customization how the tree view is shown in the panel (restart required). The options are
  • Combo View combine tree view and property view into one panel.
  • TreeView and PropertyView split tree view and property view into separate panel.
  • Both keep all three panels, and you can have two sets of tree view and property view.
Autoladda modul efter uppstart Selection what workbench will be used directly after starting FreeCAD
Aktivera splashfönster vid uppstart 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 Aktivera staplad bakgrund.

Aktivera radbrytning Words will be wrapped when they exceed the available horizontal space in the Python console. This console is shown using the menu View → Panels → Python console.

Dokument

On the Document tab you can specify the following:

Name Description
Skapa nytt dokument vid uppstart If checked, FreeCAD will create a new document when started
Document save compression level Specification of 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.
Använder Ångra / Gör om på dokument If checked, all changes in documents are stored so that they can be undone/redone
Maximalt Ångra / Gör om steg Specification how many Undo/Redo steps should be recorded
Tillåt att omberäkning avbryts If checked, recomputations can be aborted by pressing Esc. This may slightly increase the recomputation time.
Kör automatisk återställning vid start 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.
Spara information för automatisk återställning varje Specification how often a recovery file is written.
Spara minibild i projektfilen när dokumentet sparas 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 the powers of two: 128, 256, 512.
Lägg till programlogon i den genererade miniatyrbilden If checked, the FreeCAD program logo will be added to the thumbnail.
Maximalt antal backup-filer att behålla när dokument återsparas 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.
Använd datum och FCBak tillägg 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 this site.

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

Tillåt duplicerade objektetiketter i ett dokument If checked, objects can have the same label.
Inaktivera partiell laddning av externa länkade objekt 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
Författare 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 Uppdatera vid sparning 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.
Företag All created documents will get the specified company name
Standardlicens Selection of the license for new documents. For predefined licenses the Licens-URL will automatically be set accordingly. Select Other for a custom license.
Licens-URL Specification of an URL describing the license selected in Standardlicens

Markering

On the Selection tab you can specify the following:

Name Description
Växla automatiskt till 3D-vyn som innehåller det valda objektet Enables the Tree view SyncView mode
Expandera trädobjektet automatiskt när motsvarande objekt väljs i 3D-vyn Enables the Tree view SyncSelection mode
Förvälj objektet i 3D-vyn när musen går över trädobjektet Enables the Tree view PreSelection mode
Spela in markering i trädvyn för att gå bakåt/framåt med navigeringsknappen Enables the Tree view RecordSelection mode
Lägg till kryssrutor för val i dokumentträd Each document tree 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
Spela in normala meddelanden If checked, normal messages will be recorded. They will be displayed in the Report view with the color set in Normala meddelanden.
spela in logg meddelanden If checked, log messages will be recorded. They will be displayed in the Report view with the color set in Loggmeddelanden.
Spela in varningar If checked, warnings will be recorded. They will be displayed in the Report view with the color set in Varningar.
Spela in felmeddelanden If checked, error messages will be recorded. They will be displayed in the Report view with the color set in Fel.
Visa rapportvy vid fel If checked, the Report view will be shown automatically when an error is recorded
Visa rapportvy vid varning If checked, the Report view will be shown automatically when a warning is recorded
Visa rapportvy på normalt meddelande If checked, the Report view will be shown automatically when a normal message is recorded
Visa rapportvy för loggmeddelande If checked, the Report view will be shown automatically when a log message is recorded
Inkludera en tidskod för varje post If checked, each message and warning will receive a timecode
Normala meddelanden Specification of the font color for normal messages
Loggmeddelanden Specification of the font color for log messages
Varningar Specification of the font color for warning messages
Fel Specification of the font color for error messages
Dirigera om intern Pythonutmatning till rapportvyn If checked, internal Python output will be redirected from the Python console to the Report view
Omdirigera interna Pythonfel till rapportvy 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.

Skärmens inställningar

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.

3D Vy

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:

Navigering

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 1.0

Färger

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.

Nätvy

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

Workbenches

This preferences section has a single tab: Available Workbenches.

Available Workbenches

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

Makro

On the Macro tab you can specify the following:

Name Description
Kör makron i lokala miljön If checked, variables defined by macros are created as local variables, otherwise as global Python variables
sökväg för makro Specification of the path for macro files
Spela in GUI-kommandon If checked, recorded macros will also contain user interface commands
Spela in som kommentar 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.
Visa skriptkommandon i python konsolen If checked, the commands executed by macro scripts are shown in the Python console. This console is shown using the View → Panels → Python console menu option.
Size of recent macros list Controls the number of recent macros to display in the menu
Antal genvägar Controls the number of recent macros that get dynamically assigned shortcuts
Tangentbords modifierare 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.

Redaktör

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
Aktivera radnummer If checked, the code lines will be numbered
Tabulatorstorlek Specification of 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 Behåll tabulatorer is selected.
Storlek på indrag Specification of how many spaces will be inserted when pressing Tab. This setting is only used if Sätt in mellanslag is selected.
Behåll tabulatorer If selected, pressing Tab will insert a tabulator with the raster defined by Tabulatorstorlek
Sätt in mellanslag If selected, pressing Tab will insert the amount of spaces defined by Storlek på indrag
Display Items Selection of the code type. The color and font settings will be applied to the selected type. The result can be checked in the Preview field.
Familj Specification of the font family that should be used for the selected code type
Storlek Specification of the font size that should be used for the selected code type
Färg Specification of 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

Import-Export

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

Workbench related preferences

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

Draft-modulen har sin Inställningar -skärm

Scripting

See also: FreeCAD Scripting Basics.

For a scripting example see Std DlgParameter.

Related



Anpassa gränssnittet


Introduction

Eftersom FreeCAD gränssnittet är baserat på det moderna Qt verktygssetet, så har det en högklassig organisation. Widgetar, menyer, verktygslådor och andra verktyg kan ändras, flyttas, delas mellan arbetsbänkar, tangentbordsgenvägar kan ställas in, ändras, och makron kan spelas in och spelas upp. Anpassningsfönstret hittas i Verktyg -> Anpassa menyn:

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.

Usage

  1. The commands available in the Customize dialog box depend on the workbenches that have been loaded in the current FreeCAD session. So you should first load all workbenches whose commands you want to have access to.
  2. There are several ways to invoke the Std DlgCustomize command:
    • Select the Tools → Customize... option from the menu.
    • Right-click a toolbar area and choose Customize... from the context menu.
  3. The Customize dialog box opens. For more information see Options.
  4. The Help button starts the Std WhatsThis command.
  5. Press the Close button to close the dialog box.

Options

In the Customize dialog box the following tabs are available:

Keyboard

The Keyboard tab

On this tab custom keyboard shortcuts can be defined. Shortcuts for macro commands can be defined on the Macros tab.

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.

Add a shortcut

  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. Press the Reset All button.

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.

Top

Toolbars

The Toolbars tab

On this tab custom toolbars can be created and modified.

Search

See Keyboard.

Select the workbench

  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.

Create a toolbar

  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.

Rename a toolbar

  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.

Delete a toolbar

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

Disable a toolbar

  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.

Add a command

  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.

Remove a command

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

Change a command position

  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.

Top

Macros

The Macros tab

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.

Add a macro command

  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.

Remove a macro command

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

Change a macro command

  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.

Top

Spaceball Motion

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

Top

Spaceball Buttons

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

Top

Themes

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

Top

Addons

Addons from the Addon Manager offer yet another way to customize the user interface. Several Preference Packs to change the theme are available.

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

Top

Preferences Editor/sv
Property/sv


Objekt egenskaper


Introduction

En egenskap är en informationsbit som till exempel ett nummer eller en textsträng som hör till ett FreeCAD dokument eller ett objekt i ett dokument. Egenskaper kan visas och - om det är tillåtet - ändras med egenskapsredigeraren.


Egenskaper spelar en mycket viktig roll i FreeCAD, eftersom det från början är gjort för att arbeta med parametriska objekt, vilket är objekt som endast definieras av deras egenskaper.


Anpassade skript objekt i FreeCAD kan ha egenskaper av följande typer:


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"



Arbeta med arbetsbänkar


FreeCAD, som många moderna design applikationer som Revit, är baserade på konceptet Arbetsbänk. En arbetsbänk kan anses vara ett set verktyg, grupperade för en viss uppgift. I en traditionell möbelverkstad, så skulle du ha ett arbetsbord för den person som arbetar med trä, ett annat bord för den som arbetar med metalldelar, och kanske ett tredje för den som monterar ihop allting.

FreeCAD, like many modern design applications such as Revit or CATIA, is based on the concept of Workbench. A workbench can be considered as a set of tools specially grouped for a certain task. In a traditional furniture workshop, you would have a work table for the person who works with wood, another one for the one who works with metal pieces, and maybe a third one for the guy who mounts all the pieces together.

I FreeCAD, så används samma koncept . Verktyg är grupperade i arbetsbänkar i enlighet med de uppgifter de är relaterade till.

När du byter från en arbetsbänk till en annan, så byts de tillgängliga verktygen i gränssnittet ut. Verktygslådor, kommandolådor och eventuellt andra delar av gränssnittet byts till den nya arbetsbänken, men innehållet i din scen förändras inte. Du kan till exempel börja att rita 2D former med Rit arbetsbänken, sedan fortsätta arbetet på dem med Del arbetsbänken.

Note that sometimes a Workbench is referred to as a Module. However, Workbenches and Modules are different entities. A Module is any extension of FreeCAD, while a Workbench is a special type of Module with a GUI configuration (toolbars and menus).

Built-in workbenches

Current

För närvarande har vi följande arbetsbänkar:

  • Std Base. This is not really a workbench, but rather a category of 'standard' commands and tools that can be used in all workbenches.
  • The CAM Workbench is used to produce G-Code instructions. This workbench was called "Path Workbench" in version 0.21 and below.
  • The FEM Workbench provides Finite Element Analysis (FEA) workflow.
  • The Inspection Workbench is made to give you specific tools for examination of shapes. Still in the early stages of development.
  • The Part Workbench for working with geometric primitives and boolean operations.
  • The Reverse Engineering Workbench is intended to provide specific tools to convert shapes/solids/meshes into parametric FreeCAD-compatible features.
  • The Start Workbench allows you to quickly jump to one of the most common workbenches.

Obsolete

The following workbenches are no longer included after version 0.20:

External workbenches

FreeCAD workbenches are easy to program in Python, there are therefore many people developing additional workbenches outside of the FreeCAD main development area.

The external workbenches page lists all that are known to this community. Most are easily installable from within FreeCAD, using the Addon Manager, found under menu Tools → Addon manager.


Property/sv
Mesh Workbench/sv


Nät arbetsbänken


Mesh workbench icon

Introduction

Nät arbetsbänken hanterar triangelnät. Nät är en speciell typ av 3D objekt, sammansatt av trianglar som är ihopkopplade via deras kanter och hörn.

Många 3D applikationer använder nät som deras primära 3D objektstyp, som sketchup, blender, maya eller 3d studio max. Eftersom nät är mycket simpla objekt, som endast innehåller hörn (punkter), kanter och (triangulära) ytor, så är de mycket lätta att skapa, förändra, dela upp, sträcka ut, och kan lätt flyttas från en applikation till en annan utan några förluster. Eftersom de dessutom innehåller mycket simpel data, så kan 3D applikationer vanligtvis hantera mycket stora kvantiteter av dem utan några problem. Av dessa anledningar, så är nät ofta den valda 3D objekttypen i applikationer för filmer, animeringar, och bildbehandling.

Emellertid har nät en stor begränsning inom konstruktionsfältet: De är mycket 'dumma' objekt, som endast består av punkter, linjer och ytor. De består endast av ytor, och har ingen informationom dess massa, så de beter sig inte som solider. I ett nät så finns det inget automatiskt sätt att avgöra om en punkt är inuti eller utanför objektet. Detta innebär att alla solidbaserade operationer, som addition eller subtraktion, alltid är svåra att utföra på nät, och ofta orsakar fel.

Använda nätmodulen

Nätmodulen har för närvarande ett mycket enkelt gränssnitt, alla dess funktioner är grupperade i Nät menyn. De viktigaste operationerna som du för närvarande kan göra med nät är:

  • Importera nät i flera filformat
  • Exportera nät i flera filformat
  • Konvertera Del objekt till nät
  • Analysera kurvatur, ytor, och kontrollera om ett nät kan konverteras till en solid på ett säkert sätt
  • Vända nät normaler
  • Stänga hål i nät
  • Ta bort ytor i nät
  • Förena, subtrahera och skära nät
  • Skapa nätprimitiver, som kuber, sfärer, Koner eller cylindrar
  • Klippa nät längs en linje
  • Close hole: Fills selected holes in mesh objects.
  • Add triangle: Adds faces along a boundary of an open mesh object.
  • Boolean
    • Union: Creates a mesh object that is the union of two mesh objects.
    • Intersection: Creates a mesh object that is the intersection of two mesh objects.
    • Difference: Creates a mesh object that is the difference of two mesh objects.
  • 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.

Preferences

There are some export preferences related to Mesh Formats but these are not used by commands belonging to this workbench. They are used by the Std Export command.

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

Notes


Workbenches/sv
Part Workbench/sv


Del arbetsbänken


Part workbench icon

Introduction

FreeCAD's CAD kapabilitet är baserad på OpenCasCade kärnan. Del modulen tillåter FreeCAD att komma åt och använda OpenCasCade objekt och funktioner. OpenCascade är en professionell CAD kärna, som erbjuder avancerad 3D geometrimanipulation och objekt. Del objekten, till skillnad från Nätmodul objekten, är mycket komplexare, och tillåter därför mycket mer avancerade operationer, som koherenta booleska operationer, ändringshistorik och parametriskt beteende.

A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design.

The objects created with the Part Workbench are relatively simple; they are intended to be used with boolean operations (unions and cuts) in order to build more complex shapes. This modeling paradigm is known as the constructive solid geometry (CSG) workflow, and it was the traditional methodology used in early CAD systems. On the other hand, the PartDesign Workbench provides a more modern workflow to constructing shapes: it uses a parametrically defined sketch, that is extruded to form a basic solid body, which is then modified by parametric transformations (feature editing), until the final object is obtained.

Part objects are more complex than mesh objects created with the Mesh Workbench, as they permit more advanced operations like coherent boolean operations, modifications history, and parametric behaviour.

The Part Workbench is the basic layer that exposes the OCCT drawing functions to all workbenches in FreeCAD.

Verktygen

Alla Del modul verktygen finns i Del menyn som kommer fram när du laddar Del modulen.

Primitiver

Detta är verktyg för att skapa primitivobjekt.

  • Låda: Ritar en låda genom att ge dess dimensioner
  • Cylinder: Ritar en cylinder genom att ge dess dimensioner
  • Sfär: Ritar en sfär genom att ge dess dimensioner
  • Kon: Ritar en kon genom att ge dess dimensioner
  • Torus: Ritar en torus (ring) genom att ge dess dimensioner
  • CreatePrimitives: Ett verktyg för att skapa olika parametriska geometriska primitiver
  • Shapebuilder: Ett verktyg för att skapa mer komplexa former från olika parametriska geometriska primitiver
  • Cone: Creates a cone.
  • 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.

Förändra objekt

Detta är verktyg för att förändra existerande objekt. De kommer att låta dig välja vilka objekt som du vill förändra.

  • Extrudera: Extruderar plana ytor på ett objekt
  • Rotera: Skapar ett objekt genom att rotera ett annat objekt runt en axel
  • Spegling: Speglar de valda objekten runt en given axel
  • Fasning: Fasar (rundar) kanterna på ett objekt
  • Fasning: Fasar (klipper) kanter på ett objekt
  • Ruled Surface:
  • Loft: Lofts från en profil till en annan
  • Sweep: Sopa en eller flera profiler längs en bana
  • 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.
  • Section: Creates a section by intersecting an object with a section plane.
  • Offset tools:
    • 3D Offset: Constructs a parallel shape at a certain distance from an original.
    • 2D Offset: Constructs a parallel wire at certain distance from an original, or enlarges/shrinks a planar face.
  • Attachment: Attaches an object to another object.

Boolean

These tools perform boolean operations.

  • Boolean: Utför booleska operationer på objekt.
  • Cut: Cuts (subtracts) one object from another.
  • Fuse: Fuses (unions) two or more objects.
  • Common: Extracts the common (intersection) part of two objects.
  • Join features:
    • Connect: Connects interiors of walled objects.
    • Embed: Embeds a walled object into another walled object.
    • Cutout: Creates a cutout in a wall of an object for another walled object.
  • Splitting tools:
    • Boolean fragments: Creates all pieces obtained from Boolean operations.
    • Slice apart: Slices and splits an object by intersecting it with other objects.
    • Slice: Slices an object by intersecting it with other objects.
    • XOR: Removes space shared by an even number of objects.

Measure

Other tools

  • Import: Imports from *.IGES, *.STEP, or *.BREP files.
  • Export: Exports to *.IGES, *.STEP, or *.BREP files.

Context menu items

  • Appearance: Determines the appearance of a whole object (color, transparency etc.).

Preferences

  • Preferences: Preferences available for Part Tools (the Part workbench also uses the PartDesign Preferences).
  • Import Export Preferences: Preferences available for importing from and exporting to different file formats.
  • Fine-tuning: Some extra parameters to fine-tune Part behavior.

Skript

See Part scripting.

Tutorials


Mesh Workbench/sv
Drawing Workbench/sv


Ritnings arbetsbänken


The Drawing Workbench is no longer included after version 0.20.
The TechDraw Workbench is its more advanced replacement.
Drawing workbench icon

Introduction

Ritnings modulen tillåter dig att lägga ut ditt 3D arbete på papper. Det är, att lägga vyer av dina modeller i ett 2D fönster osh att sätta in det fönstret i en ritning, till exempel ett ark med en ram, en titel och din logotyp och slutligen skriva ut det arket. Ritningsmodulen är för närvarande under konstruktion och är mer eller mindre en teknologisk förhandstitt!

Gränssnittsverktyg

Detta är verktyg för att skapa, konfigurera och exportera 2D ritningsark

  • Insert a view: Inserts a view of the selected object in the active drawing sheet
  • Annotation: Adds an annotation to the current drawing sheet
  • 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
  • Save sheet: Saves the current sheet as a SVG file
  • Project Shape: Creates a projection of the selected object (Source) in the 3D view.

Note The Draft Workbench has its own Draft_Drawing too to place Draft objects on paper. It has a couple of extra capabilities over the standard Drawing tools, and supports specific objects like Draft dimensions.

I bilden så ser du huvudkoncepten av Ritningsmodulen. Dokumentet innehåller ett formobjekt (Schenkel) som vi vill göra en ritning av. Därför så är en "Sida" skapad. Sidan fås genom en mall, i detta fall "A3_Landskap" mallen. Mallen är ett SVG dokument som kan innehålla din vanliga sidram, din logotyp eller så den överensstämmer med dina presentationsstandarder.

I denna sida så kan vi sätta in en eller fler vyer. Varje vy har en position på sidan (Egenskaper X,Y), en skalfaktor (Egenskap skala) och ytterligare egenskaper. Varje gång som sidan ,eller vyn, eller det refererade objektet ändras så regenereras sidan och visningen uppdateras.

Skript

För tillfället så är arbetsflödet för slutanvändaren väldigt begränsat, så skript API't är intressantare. Här följer exempel på hur man använder skript API't för ritningsmodulen.

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

Exempel

FreeCAD kommer med ett standardset med mallar, men du kan hitta fler på Ritningsmallar sidan.

Extending the Drawing Module

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.

Tutorials

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


Part Workbench/sv
Raytracing Workbench/sv


Raytracing arbetsbänken


The Raytracing Workbench is no longer included after version 0.20.
The external Render Workbench should be used instead.
Raytracing workbench icon

Denna modul är tänkt att skicka innehållet i din scen till en extern rendererare, för att generera fotorealistiska bilder på ditt arbete. Renderingsmodulen är fortfarande i ett mycket tidigt skede, så du har inte så många tillgängliga alternativ för tillfället. För närvarande finns endast ett grundläggande verktygsset för att exportera Del objekt som POV-ray filer. Dessa filer kan sedan laddas i POV-ray och renderas.

The Raytracing Workbench is used to generate photorealistic images of your models by processing them with an external renderer.

The Raytracing Workbench works with templates, which are project files that define a scene for your 3D model. You can place lights and geometry such as ground planes, and it also contains placeholders for the position of the camera, and for the material information of the objects in the scene. The project can then be exported to a ready-to-render file, or be rendered directly within FreeCAD.

Currently, two renderers are supported: POV-Ray and LuxRender. To be able to render from within FreeCAD, at least one of these programs must be installed and configured in your system. However, if no renderer is installed, you will still be able to export a project file to be rendered at another time.

The Raytracing workbench is obsolete, the external Render Workbench is its replacement. Nevertheless, the information on this page is generally useful for the new workbench, as both basically work in the same way.

Typical workflow

  1. Create or open a FreeCAD project, add some solid objects (Part-based or PartDesign-based); meshes are currently not supported.
  2. Create a Raytracing project (povray or luxrender).
  3. Select the objects that you wish to add to the Raytracing project and add them.
  4. Export the project file or render it directly.



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.

Gränssnittsverktyg

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

Creating a povray file manually

The utility tools described above allow you to export the current 3D view and all of its content to a Povray file. First, you must load or create your CAD data and position the 3D View orientation as you wish. Then choose "Utilities → Export View..." from the raytracing menu.

You will be asked for a location to save the resulting *.pov file. After that you can open it in Povray and render:

As usual in a renderer you can make big and nice pictures:

Skript

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

Länkar

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.


Drawing Workbench/sv
Draft Workbench/sv


Bild arbetsbänken


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

Introduction

Bildmodulen hanterar olika typer av bitmapp bilder, och låter dig öppna dem i FreeCAD. För närvarande, så kan modulen öppna .bmp, .jpg, .png och .xpm filformat i ett separat visningsfönster. Det finns också ett verktyg som tillåter dig att fånga bilder från en webcam.

Tools

Features

  • Like a Sketch, an imported image can be attached to one of the main planes XY, XZ, or YZ, and given a positive or negative offset.
  • The image is imported with relation of 1 pixel to 1 millimeter.
  • The recommendation is to have the imported image at a reasonable resolution.

Workflow

A major use of this workbench is tracing over the image, with the Draft or Sketcher tools, in order to generate a solid body based on the contours of the image.

Tracing over an image works best if the image has a small negative offset, for example, -0.1 mm, from the working plane. This means that the image will be slightly behind the plane where you draw your 2D geometry, so you won't draw on the image itself.

The offset of the image can be set during import, or changed later through its properties.


Draft Workbench/sv
Macros/sv


Skiss arbetsbänken


Draft workbench icon

Introduction

Rit modulen är ett pågående arbete och är en ganska experimentell modul som har gjorts för att lägga till grundläggande 2d ritfunktionalitet till FreeCAD. Den är helt och hållet skriven i python, och är även tänkt att fungera som en presentation om hur mycket du kan utöka FreeCAD endast med hjälp av python, utan att ens röra källkoden.

Draft objects can be used for general drafting, similar to what can be done with Inkscape or AutoCAD. But they can also form the base for the creation of 3D objects in other workbenches. A Draft Wire may define the path of an Arch Wall, a Draft Polygon can be extruded with Part Extrude, etc. Many of the Draft modifier tools can be applied to 2D and 3D objects created with other workbenches as well. You can, for example, move a Sketch or create a Draft OrthoArray from a Part object.

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

If your primary goal is the production of complex 2D drawings and DXF files, and you don't need 3D modelling, FreeCAD may not be the right choice for you. You may wish to consider a dedicated software program for technical drafting instead, such as LibreCAD or 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.

Modification

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

Draft Tray

The Draft Tray allows selecting the working plane, defining style settings, toggling construction mode, and specifying the active layer or group.

  • Select plane: defines the current Draft working plane. Also available in the menu: Draft → Utilities → Select Plane.
  • 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.

Draft annotation scale widget

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

Draft snap widget

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

Draft snap toolbar

The Draft snap toolbar allows selecting the active snap options. The buttons belonging to active options stay depressed. For general information about snapping see: Draft Snap.

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

Draft utility tools toolbar

Additional tools

The Draft → Utilities menu contains several tools. Most of them can also be accessed from toolbars or the Draft Tray and have already been mentioned above. For the following tools this is not the case:

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

Gemensamt beteende

  • Snäpp: tillåter dig att placera nya punkter på speciella platser på existerande objekt
  • Begränsning: Tillåter att nya punkter placeras horisontellt eller vertikalt i relation till tidigare punkter
  • Konstruktionsläge: Tillåter dig att skilja viss geometri åt från resten, för att lätt kunna stänga på/av
  • Arbetsplan: Alla skisskommandon kan användas på valfritt plani i 3D rymden. Det gällande arbetsplanet kan konfigureras på ett lätt sätt

Tree view context menu

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.

Layer container options

For a Draft LayerContainer these additional options are available:

Layer options

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 1.0

Wire options

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.

Working plane proxy options

For a Draft WorkingPlaneProxy these additional options are available:

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

3D view context menu

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.

Obsolete tools

  • Array: creates an orthogonal array from a selected object. The created array can be turned into a polar array or a circular array by changing its DataArray Type property. Not available in version 0.21 and above.
  • Drawing: inserts views of selected objects into a drawing page. Not available in version 0.21 and above.

Preferences

  • Preferences: general preferences for the Draft Workbench.

Import & export

Detta är funktioner för att öppna, importera eller exportera andra filformat. Öppna kommet att öppna ett nytt dokument med filens innehåll, medan importera kommer att lägga till filinnehållet till det nuvarande dokumentet. Exportera kommer att spara de valda objekten till en fil. Om inget är valt, så kommer alla objekt att exporteras. Var uppmärksam på att eftersom tanken med Ritmodulen är att arbeta med 2d objekt, så fokuserar dessa importerare endast på 2d objekt, och, fastän DXF och OCA formaten stödjer objektdefinitioner i 3D rymden (objekt är inte nödvändigtvis platta), så kommer de inte att importera volymetriska objekt som nät, 3D ytor, etc, utan snarare linjer, cirklar, text eller flata former. För närvarande så stöds följande filformat:

  • Autodesk .DXF: Importerar och exporterar DXF filer som har skapats med andra CAD applikationer
  • SVG (som geometri): Importerar och exporterar SVG filer som har skapats med vektorbaserade ritapplikationer

Unit tests

See also: Test Workbench.

To run the unit tests of the workbench execute the following from the operating system terminal:

freecad -t TestDraft

API

Se Skiss API sidan för en komplett beskrivning av Skissfunktionerna som du kan använda i skript och makron

The workbench includes a module to create samples of all objects in a new document.

Use this to test that all objects are produced correctly:

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

Inspecting the code of this module can help to understand the programming interface.

Tutorials


Raytracing_Workbench/sv
Robot_Workbench/sv


Skript och Makron

Macros


Introduction

Makron är ett smidigt sätt att skapa komplexa aktioner i FreeCAD. Du behöver bara spela in aktioner samtidigt som du gör dem, och sedan spara det under ett namn, och senare spela upp det när du vill. Eftersom makron i realiteten är en lista av python kommandon, så kan du även redigera det, och skapa mycket komplexa skript.

While Python scripts normally have the .py extension, FreeCAD macros should have the .FCMacro extension. A collection of macros written by experienced users is found in the macros recipes page.

See the Power users hub to learn more about the Python programming language, and about writing macros. In particular, you should start with these pages:

Hur det fungerar

Om du aktiverar konsolutmatning(Meny Redigera -> Alternativ -> Allmänt -> Makro -> Visa skriptkommandon i python konsolen), så kommer du se att varje aktion du gör i FreeCAD, , som att klicka på en knapp, genererar ett python kommando. Dessa kommandon är vad som kan spelas in i ett makro. Huvudverktyget för att göra makron är makroverktygslådan: . På den finns det 4 knappar: Spela in, stoppa inspelning, redigera och spela upp det nuvarande makrot.

Enable the console output in the menu Edit → Preferences → Python → Macro → Show scripts commands in python console. You will see that in FreeCAD, every action you do, such as pressing a button, outputs a Python command. Those commands are what can be recorded in a macro. The main tool for making macros is the macros toolbar: . On it you have 4 buttons: Record, stop recording, edit and play the current macro.

Det är mycket enkelt att använda: Klicka på inspelningsknappen, du kommer att efterfrågas om ett namn till ditt makro, utför sedan några aktioner. När du är klar, Klick på stoppa inspelning knappen, och dina aktioner kommer att spaaras. Du kan nu komma åt makrodialogen med redigeraknappen:

Där kan du hantera dina makron, radera, redigera eller skapa nya från scratch. Om du redigerar ett makro, så kommer det att öppnas i ett redigeringsfönster där du kan förändra dess kod.

Exempel

Klicka på inspelningsknappen, ge den ett namn, låt oss säga "cylinder 10x10", skapa skapa sedan med Del arbetsbänken en cylinder med radien= 10 och höjden = 10. Klicka sedan på "stoppa inspelning" knappen. I redigera makro dialogen, så kan du se den python kod som har spelats in, och om du vill, göra ändringar på den. För att köra ditt makro, klicka på uppspelningsknappen i verktygslåden medan ditt makro är i redigeraren. Ditt makro sparas alltid till disk, så alla ändringar du gör, eller alla nya makron du skapar, kommer alltid att finnas tillgängliga nästa gång som du startar FreeCAD.

Press the record button, give a name, let's say "cylinder 10x10", then, in the Part Workbench, create a cylinder with radius = 10 and height = 10. Then, press the "stop recording" button. In the edit macros dialog, you can see the python code that has been recorded, and, if you want, make alterations to it. To execute your macro, simply press the execute button on the toolbar while your macro is in the editor. You macro is always saved to disk, so any change you make, or any new macro you create, will always be available next time you start FreeCAD.

Anpassning

Det är förstås inte så praktiskt att behöva ladda ett makro i redigeraren för att kunna använda det. FreeCAD erbjuder många bättre sätt att använda ditt makro, som att tilldela en tangentbordsgenväg till den eller lägga till en punkt i menyn. När ditt makro är sparat, så kan allt detta göras via Verktyg -> Anpassa menyn:

Of course it is not practical to load a macro in the editor in order to use it. FreeCAD provides much better ways to use your macro, such as assigning a keyboard shortcut to it or putting an entry in the menu. Once your macro is created, all this can be done via the Tools → Customize menu.

Pä detta sätt så kan du göra ditt makro till ett riktigt verktyg, precis som ett standardverktyg i FreeCAD . Detta, i tilläg till kraften hos pythonskripten i FreeCAD, gör det möjligt att lätt lägga till dina egna verktyg till gränssnittet. Läs vidare på Skript sidan om du vill veta mer om python skript...

See Customize Toolbars for a more detailed description.

Skapa makron utan inspelning

Du kan också direkt kopiera/klistra in python kod till ett makro, utan att behöva spela in aktioner i gränssnittet. Skapa bara ett nytt makro, redigera det, och klistra in din kod. Ditt makro sparas automatiskt när du stänger makroredigerings fönstret.

You can also directly copy/paste python code into a macro, without recording GUI action. Simply create a new macro, edit it, and paste your code. You can then save your macro the same way as you save a FreeCAD document. Next time you start FreeCAD, the macro will appear under the "Installed Macros" item of the Macro menu.

See How to install macros for a more detailed description.

Makroförråd

Besök Makrorecept sidan för att hämta några användbara makron att lägga till din FreeCAD installation.

There are two main places for macros. The first one is the official peer-reviewed macro repository on GitHub. The second one is the Macros recipes page from which you can pick some useful macros to add to your FreeCAD installation. Macros from both repositories can be installed via the Addon Manager directly from FreeCAD.

Additional information

Tutorials

You can manually install extensions, however, it is much simpler to just use the Addon Manager.


Standard Menu/sv
Introduction to Python/sv


Introduktion till Python


Introduction

This is a short tutorial for those new to Python. Python is an open-source, multiplatform programming language. It has several features that make it different from other programming languages, and very accessible to new users:

  • It has been designed to be to readable by human beings, making it relatively easy to learn and understand.
  • It is interpreted, this means that programs do not need to be compiled before they can be executed. Python code can be executed immediately, even line by line if you wish.
  • It can be embedded in other programs as a scripting language. FreeCAD has an embedded Python interpreter. You can write Python code to manipulate parts of FreeCAD. This is very powerful, it means you can build your very own tools.
  • It is extensible, you can easily plug new modules into your Python installation and extend its functionality. For example, there are modules that allow Python to read and write images, to communicate with Twitter, to schedule tasks to be performed by your operating system, etc.

The following is a very basic introduction, and by no means a complete tutorial. But hopefully it will provide a good starting point for further exploration into FreeCAD and its mechanisms. We strongly encourage you to enter the code snippets below into a Python interpreter.

The interpreter

Usually when writing computer programs, you open a text editor or your special programming environment (which is basically a text editor with some additional tools), write your program, then compile and execute. Often one or more errors were made during entry, so your program won't work. You may even get an error message telling you what went wrong. Then you go back to your text editor, correct the mistakes, run again, repeating until your program works as intended.

In Python that whole process can be done transparently inside the Python interpreter. The interpreter is a Python window with a command prompt, where you can simply type Python code. If you have installed Python on your computer (download it from the Python website if you are on Windows or Mac, install it from your package repository if you are on GNU/Linux), you will have a Python interpreter in your start menu. But, as already mentioned, FreeCAD also has a built-in Python interpreter: the Python console.

The FreeCAD Python console

If you don't see it, click on View → Panels → Python console. The Python console can be resized and also undocked.

The interpreter shows the Python version, then a >>> symbol which is the command prompt. Writing code in the interpreter is simple: one line is one instruction. When you press Enter, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this:

print("hello")

print() is a Python command that, obviously, prints something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write:

print(hello)

Python will immediately tell you so. In this case Python doesn't know what hello is. The " " characters specify that the content is a string, programming jargon for a piece of text. Without these the print() command doesn't recognize hello. By pressing the up arrow you can go back to the last line of code and correct it.

The Python interpreter also has a built-in help system. Let's say we don't understand what went wrong with print(hello) and we want specific information about the command:

help("print")

You'll get a long and complete description of everything the print() command can do.

Now that you understand the Python interpreter, we can continue with the more serious stuff.

Top

Variables

Very often in programming you need to store a value under a name. That's where variables come in. For example, type this:

a = "hello"
print(a)

You probably understand what happened here, we saved the string "hello" under the name a. Now that a is known we can use it anywhere, for example in the print() command. We can use any name we want, we just need to follow some simple rules, such as not using spaces or punctuation and not using Python keywords. For example, we can write:

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

Now hello is not an undefined any more. Variables can be modified at any time, that's why they are called variables, their content can vary. For example:

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

We changed the value of myVariable. We can also copy variables:

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

It is advisable to give meaningful names to your variables. After a while you won't remember what your variable named a represents. But if you named it, for example, myWelcomeMessage you'll easily remember its purpose. Plus your code is a step closer to being self-documenting.

Case is very important, myVariable is not the same as myvariable. If you were to enter print(myvariable) it would come back with an error as not defined.

Top

Numbers

Of course Python programs can deal with all kinds of data, not just text strings. One thing is important, Python must know what kind of data it is dealing with. We saw in our print hello example, that the print() command recognized our "hello" string. By using " " characters, we specified that what follows is a text string.

We can always check the data type of a variable with the type() command:

myVar = "hello"
type(myVar)

It will tell us the content of myVar is a 'str', which is short for string. We also have other basic data types such as integer and float numbers:

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

Python knows that 10 and 20 are integer numbers, so they are stored as 'int', and Python can do with them everything it can do with integers. Look at the results of this:

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

Here we forced Python to consider that our two variables are not numbers but pieces of text. Python can add two pieces of text together, although in that case, of course, it won't perform any arithmetic. But we were talking about integer numbers. There are also float numbers. The difference is float numbers can have a decimal part and integer numbers do not:

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

Integers and floats can be mixed together without problems:

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

Because var2 is a float Python automatically decides that the result must also be a float. But there are cases where Python does not knows what type to use. For example:

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

This results in an error, varA is a string and varB is an integer, and Python doesn't know what to do. However, we can force Python to convert between types:

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

Now that both variables are strings the operation works. Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:

varB = str(varB)

We can also use int() and float() to convert to integer and float if we want:

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

You must have noticed that we have used the print() command in several ways. We printed variables, sums, several things separated by commas, and even the result of another Python command. Maybe you also saw that these two commands:

type(varA)
print(type(varA))

have the same result. This is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print() command. With that in mind let's stop using it here. From now on we will simply write:

myVar = "hello friends"
myVar

Top

Lists

Another useful data type is a list. A list is a collection of other data. To define a list we use [ ]:

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

As you can see a list can contain any type of data. You can do many things with a list. For example, count its items:

len(myOtherList)

Or retrieve one item:

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

While the len() command returns the total number of items in a list, the first item in a list is always at position 0, so in our myOtherList "Bob" will be at position 2. We can do much more with lists such as sorting items and removing or adding items.

Interestingly a text string is very similar to a list of characters in Python. Try doing this:

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

Usually what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Apart from strings, integers, floats and lists, there are more built-in data types, such as dictionaries, and you can even create your own data types with classes.

Top

Indentation

One important use of lists is the ability to "browse" through them and do something with each item. For example look at this:

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

We iterated (programming jargon) through our list with the for in command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that there is more to come.

How will Python know how many of the next lines will need to be executed inside the for in operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the for in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you have finished, just write another line without indentation, or press Enter to come back from the for in block

Indentation also aids in program readability. If you use large indentations (for example use tabs instead of spaces) when you write a big program, you'll have a clear view of what is executed inside what. We'll see that other commands use indented blocks of code as well.

The for in command can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

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

If you have been running the code examples in an interpreter by copy-pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste in the interpreter. In the interpreter press Enter until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another Enter. The final answer should appear.

If you type into the interpreter help(range) you will see:

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

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using int():

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

Another range() example:

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

The range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

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

Another interesting use of indented blocks is with the if command. This command executes a code block only if a certain condition is met, for example:

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

Of course this will always print the sentence, but try replacing the second line with:

if "Lucky" in alldaltons:

Then nothing is printed. We can also specify an else statement:

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

Top

Functions

There are very few standard Python commands and we already know several of them. But you can create your own commands. In fact, most of the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

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

printsqm(45)

The def() command defines a new function, you give it a name, and inside the parenthesis you define the arguments that the function will use. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len(), Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write len(myList) then myList is the argument that you pass to the len() function. And the len() function is defined in such a way that it knows what to do with this argument. We have done the same thing with our printsqm function.

The myValue name can be anything, and it will only be used inside the function. It is just a name you give to the argument so you can do something with it. By defining arguments you also to tell the function how many to expect. For example, if you do this:

printsqm(45, 34)

there will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. Let's try another example:

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

myTotal = sum(45, 34)

Here we made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable.

Top

Modules

Now that you have a good idea of how Python works, you will need to know one more thing: How to work with files and modules.

Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the .py extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them.

There are several of ways to execute a Python program. In Windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's user Mod folder:

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

Let's add a subfolder there called scripts and then write a file like this:

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

print("myTest.py succesfully loaded")

Save the file as myTest.py in the scripts folder, and in the interpreter window write:

import myTest

without the .py extension. This will execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. Files containing functions, like ours, are called modules.

When we write a sum() function in the interpreter, we execute it like this:

sum(14, 45)

But when we import a module containing a sum() function the syntax is a bit different:

myTest.sum(14, 45)

That is, the module is imported as a "container", and all its functions are inside that container. This is very useful, because we can import a lot of modules, and keep everything well organized. Basically when you see something.somethingElse, with a dot in between, then this means somethingElse is inside something.

We can also import our sum() function directly into the main interpreter space:

from myTest import *
sum(12, 54)

Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We have already seen that Python has a help() function. Doing:

help("modules")

will give us a list of all available modules. We can import any of them and browse their content with the dir() command:

import math
dir(math)

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. Every function in a well made module has a __doc__ that explains how to use it. For example, we see that there is a sin() function inside the math module. Want to know how to use it?

print(math.sin.__doc__)

It may not be evident, but on either side of doc are two underscore characters.

And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension, .FCMacro, but instead use the standard .py extension. This is because Python doesn't recognize the .FCMacro extension. If you use .py your code can be easily loaded with import, as we have already seen, and also reloaded with importlib.reload():

import importlib
importlib.reload(myTest)

There is however an alternative:

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

Top

Starting with FreeCAD

Hopefully you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. Just try:

dir()

Top

Notes

  • FreeCAD was originally designed to work with Python 2. Since Python 2 reached the end of its life in 2020, future development of FreeCAD will be done exclusively with Python 3, and backwards compatibility will not be supported.
  • Much more information about Python can be found in the official Python tutorial and the official Python reference.

Top


Python skript i FreeCAD

FreeCAD är byggt från grunden att helt och hållet kunna kontrolleras av python skript. Nästan alla delar av FreeCAD som gränssnittet, sceninnehållet, och även representationen av detta innehåll i 3d vyerna kan kommas åt från den inbyggda pythontolken eller från dina egna skript. Resultatet av detta är att FreeCAD troligen är en av de mest anpassningsbara konstruktionsapplikationerna som finns idag.

FreeCAD is built from scratch to be totally controlled by Python scripts. Almost all parts of FreeCAD, such as the interface, the scene contents, and even the representation of this content in the 3D views, are accessible from the built-in Python interpreter or from your own scripts. As a result, FreeCAD is probably one of the most deeply customizable engineering applications available today.

Om du inte kan något om python, så rekommenderar vi att du letar efter övningar på internet, och tar en snabbtitt på dess struktur. Python är ett mycket lättlärt språk, speciellt eftersom det kan köras inuti en tolk, där allt från enkla kommandon till kompletta program kan köras direkt, utan något bahov för kompilering. FreeCAD har en inbyggd tolk. Om du inte ser fönstret "Rapportvy", som visas nedan, så kan du få fram den genom att klicka på Vy -> Vyer -> Rapportvy.

Tolken

Från tolken så har du åtkomst till alla dina systeminstallerade pythonmoduler, såväl som FreeCAD's inbyggda moduler, och alla extra FreeCAD moduler som du installerat senare. Skärmdumpen nedan visar python tolken:

From the interpreter, you can access all your system-installed Python modules, as well as the built-in FreeCAD modules, and all additional FreeCAD modules you installed later. The screenshot below shows the Python interpreter:

FreeCAD python tolken

Från tolken kan du köra pythonkod, lista igenom tillgängliga klasser och funktioner. FreeCAD erbjuder en väldigt smidig klasslistare för utforskning av din nya FreeCAD värld: När du skriver namnet på en känd klass följt av en punkt (vilket innebär att du vill addera något från den klassen), så öppnas en klasslistare, där du kan navigera mellan tillgängliga underklasser och metoder. När du väljer något, så visas en associerad hjälptext (om den finns):

FreeCAD klasslistare

Så, starta här genom att skriva App. eller Gui. och se vad som händer. Ett annat mer allmänt python-sätt att utforska modul- och klassinnehåll är att använda print dir() kommandot. Till exempel, genom att skriva print dir() så kommer alla moduler som för närvarande är laddade i FreeCAD att listas. print dir(App) kommer att visa dig allt inuti App modulen, etc.

En annan användbar egenskap hos tolken är möjligheten att backa i kommandohistorian och hämta en kod-rad som du skrivit tidigare. För att navigera i kommandohistorian, använd CTRL+UPP-PIL eller CTRL+NED-PIL.

Genom att högerklicka i tolkfönstret, så har du flera andra alternativ, som att kopiera hela historian (användbart för att göra en experimentskript, och sedan kunna spara det), eller att sätta in ett filnamn med full sökväg.

Top

Python Hjälp

I FreeCAD Hjälpmenyn, så hittar du en menypunkt som heter "Python hjälp", vilken kommer att öppna ett webbfönster som innehåller en komplett, realtidsgenererad dokumentation över alla python moduler som finns tillgänglig för FreeCAD tolken, inklusive python inbyggda FreeCAD moduler, system-installerade moduler, och extra FreeCAD moduler. Den dokumentation som fills tillgänglig där beror på hur mycket arbete varje modulutvecklare lägger på att dokumentera sin kod, men vanligtvis her pythonmoduler ett rykte om sig att vara ganska väldokumenterade. Ditt FreeCAD fönster måste vara öppet för att detta dokumentationssystem ska fungera.

In the FreeCAD Help menu, you'll find an entry labeled Automatic python modules documentation, which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work. The entry Python scripting documentation will give you a quick link to the Power users hub wiki section.

Top

Inbyggda moduler

Eftersom FreeCAD är designat för att kunna köras utan ett grafiskt användargränssnitt, så är nästan all dess funktionalitet uppdelat i två grupper: Kärnfunktioner, benämnda App, och gränssnittsfunktioner, benämnda Gui. Så våra två inbyggda FreeCAD huvudmoduler kallas för App och Gui. Dessa två moduler kan även kommas åt av skript utanför tolken, genom de respektive namnen FreeCAD och FreeCADGui.

Since FreeCAD is designed so that it can also be run without a Graphical User Interface (GUI), almost all its functionality is separated into two groups: Core functionality, named App, and GUI functionality, named Gui. These two modules can also be accessed from scripts outside of the interpreter, by the names FreeCAD and FreeCADGui respectively.

  • I App modulen, så hittar du allt som är relaterat till själva applikationen, som metoder för att öppna eller stänga filer, och till dokumenten, som att ställa in det aktiva dokumentet eller lista dess innehåll.
  • I Gui modulen, så hittar du verktyg för åtkomst och hantering av gränssnittselement, som arbetsbänkarna och dears verktygslådor, och mer intressant, den grafiska representationen av allt FreeCAD innehåll.

Att lista allt innehåll av dessa moduler är en lite improduktiv uppgift, eftersom de växer ganska snabbt tillsammans med FreeCAD's utveckling. Men de två erbjudna listverktygen (klasslistaren och python hjälpen) ska alltid ge dig en komplett och uppdaterad dokumentation av dessa moduler.

Top

App och Gui objekten

Som vi sade, så är allt i FreeCAD uppdelat mellan kärna och representation. Detta inkluderar även 3D objekten. Du kan komma åt objektens definierande egenskaper (kallade features i FreeCAD) via App modulen, och ändra det sätt som de representeras på skärmen via Gui modulen. Till exempel, en kub har egenskaper som definierar den, som bredd, längd, höjd som sparas i ett App objekt, och representationsegenskaper, som ytfärg, ritläge, som lagras i ett motsvarande Gui objekt.

As already mentioned, in FreeCAD everything is separated into core and representation. This includes the 3D objects. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it (like width, length, height) that are stored in an App object, and representation properties (like faces color, drawing mode) that are stored in a corresponding Gui object.

Detta sätt att göra det på tillåter ett mycket brett användningsområde, som att låta algoritmer endast arbeta på den definierande delen av objekten, utan att behöva bry sig om någon visuell del, eller även att skicka dokumentets innehåll till icke-grafiska applikationer, som listor, räkneark eller elementanalyser.

För varje App objekt i ditt dokument, så existerar det ett motsvarande Gui objekt. Själva dokumentet har faktiskt också ett App och ett Gui objekt. Detta är förstås endast giltigt när du kör FreeCAD med dess fulla gränssnitt. I kommando-linje versionen, så existerar inget gränssnitt, så endast App objekt är tillgängliga. Notera att Gui delen av objekt genereras igen varje gång som ett App objekt är markerat som "att omberäknas" (till exempel när en av dess parametrar har ändrats), så ändringar som du har gjort direkt på Gui objektet kan förloras.

För att komma åt App delen av något, så skriver du:

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

där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:

myObject = App.ActiveDocument.ObjectName

För att komma åt Gui delen av samma objekt, skriv:

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

där "ObjektNamn är namnet på ditt objekt. Du kan också skriva:

myViewObject = App.ActiveDocument.ObjectName.ViewObject

Om vi inte har något gränssnitt (vi är till exempel i kommandoradsläge), så kommer den sista raden att returnera None.

Top

Dokument objekten

I FreeCAD så finns allt ditt arbete i Dokument. Ett dokument innehåller din geometri och kan sparas till en fil. Flera dokument kan öppnas samtidigt. Dokumentet, som geometrin som finns i den, har App och Gui objekt. App objekt innehåller dina geometridefinitioner, medan Gui objekt innehåller ditt dokuments olika vyer Du kan öppna flera fönster, där varje fönster visar ditt arbete med en annan zoomfaktor eller synvinkel. Dessa vyer är en del av Gui objektet i ditt dokument.

In FreeCAD all your work resides inside documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. The App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or from a different direction. These views are all part of your document's Gui object.

För att komma åt App delen i det aktiva dokumentet, skriv:

myDocument = App.ActiveDocument

För att skapa ett nytt dokument, skriv:

myDocument = App.newDocument("Document Name")

För att komma åt Gui delen i det aktiva dokumentet, skriv:

myGuiDocument = Gui.ActiveDocument

För att komma åt nuvarande vy, skriv:

myView = Gui.ActiveDocument.ActiveView

Top

Using additional modules

The FreeCAD and FreeCADGui modules are only responsible for creating and managing objects in the FreeCAD document. They don't actually do anything more such as creating or modifying geometry. This is because that geometry can be of several types, and therefore requires additional modules, each responsible for managing a certain geometry type. For example, the Part Workbench, using the OpenCascade kernel, is able to create and manipulate BRep type geometry. Whereas the Mesh Workbench is able to build and modify mesh objects. In this manner FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types can easily be added in the future.

Top

Creating objects

Each module has its own way of dealing with geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:

FreeCAD.ActiveDocument.supportedTypes()

will list all possible objects you can create. For example, let's create a mesh (handled by the Mesh module) and a part (handled by the Part module):

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

The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one thing, myMesh has a Mesh property and myPart has a Shape property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:

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

You could try storing the cube inside the Mesh property of the myMesh object, but it will return an error. That is because each properties is made to store only a certain type. In a Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:

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

Top

Modifying objects

Modifying an object is done in the same way:

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

Now let's change the shape by a bigger one:

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

Top

Querying objects

You can always look at the type of an object like this:

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

or check if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):

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

Now you can really start playing with FreeCAD! For a complete list of available modules and their tools, visit the Category:API section.

Top

Introduction to Python/sv
Mesh Scripting/sv


Introduktion

Först av allt så måste du importera Nätmodulen:

To get access to the Mesh module you have to import it first:

import Mesh

Skapande och laddning

För att skapa ett tomt nätobjekt använd standardkonstruktören:

To create an empty mesh object just use the standard constructor:

mesh = Mesh.Mesh()

Du kan också skapa ett objekt från en fil

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

Eller skapa det från ett set av trianglar, beskrivna av dess hörnpunkter:

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)

Mesh-Kernel tar hand om skapandet av en topologiskt korrekt datastruktur genom att sortera sammanfallande punkter och kanter tillsammans.

Top

Modellering

För att skapa reguljärageometrier så kan du används Python skriptet BuildRegularGeoms.py.

To create regular geometries you can use one of the create*() methods. A torus, for instance, can be created as follows:

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

De första två parametrarna definierar toroidens radier och den tredje parametern är en sub-sampling faktor för hur många trianglar som skapas. Ju högre värde på denna faktorn, desto jämnare blir kroppen.

Nät klassen har ett set med booleska funktioner som kan användas för modelleringsändamål. Den erbjuder förening, skärning och skillnad mellan två nätobjekt.

The Mesh module also provides three Boolean methods: union(), intersection() and 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

Slutligen, ett komplett exempel som beräknar skärningen mellan en sfär och en cylinder som skär sfären.

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()

Top

Special

En extensiv, fast svåranvänd, källa för Nätrelaterade skript är Nätmodulens enhetstestskript. I detta enhetstest så kallas samtliga metoder och samtliga egenskaper/attribut ändras. Så om du är tillräckligt modig, ta en titt på Unit Test module.

An extensive, though hard to use, source of mesh related scripting are the unit test scripts of the Mesh module. In these unit tests literally all methods are called and all properties/attributes are tweaked. So if you are bold enough, take a look at the Unit Test module.

See also: Mesh API.

Top


Introduktion

Här kommer vi att förklara hur du kontrollerar Del Modulen direkt från FreeCADs python tolk, eller från ett externt skript. Titta igenom Skript avsnittet och FreeCAD Skript grunder sidorna om du behöver mer information om hur python skript fungerar i FreeCAD.


För att kunna använda Delmodulens funktioner så måste du ladda Del modulen i tolken:

import Part

Here we will explain to you how to control the Part module directly from the FreeCAD Python interpreter, or from any external script. Be sure to browse the Scripting section and the FreeCAD Scripting Basics pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the Introduction to Python.

See also

Klass Diagram

Detta är en UML översikt över de viktigaste klasserna i Del modulen:

Python klasser i Del modulen
Python klasser i Del modulen

This is a Unified Modeling Language (UML) overview of the most important classes of the Part module: Python classes of the Part module

Top

Geometri

De geomtriska objekten är byggblocken för alla topologiska objekt:

  • GEOM Basklass för geometriska objekt
  • LINE En rak linje i 3D, definierad av en start- och en slutpunkt
  • CIRCLE Cirkel eller cirkelsegment som definieras av en centrumpunkt, start- och en slutpunkt
  • ...... Och snart lite mer

The geometric objects are the building blocks of all topological objects:

  • Geom Base class of the geometric objects.
  • Line A straight line in 3D, defined by starting point and end point.
  • Circle Circle or circle segment defined by a center point and start and end point.
  • Etc.

Top

Topologi

Följande topologiska datatyper finns tillgängliga:

  • COMPOUND En grupp av valfri typ av topologiska objekt.
  • COMPSOLID En kompositsolid är ett set av solider ihopkopplade genom dess ytor. Det expanderar begreppen WIRE och SHELL till solider.
  • SOLID En rymd som är begränsad av skal. Den är tredimensionell.
  • SHELL Ett set av ytor ihopkopplade genom dess kanter. Ett skal kan vara öppet eller slutet.
  • FACE I 2D så är det en del av ett plan; i 3D är det en del av en yta. Dess geometri är begränsad (trimmad) av konturer. Den är tvådimensionell.
  • WIRE Ett set av kanter som är ihopkopplade genom dess hörn. Det kan vara en öppen eller sluten kontur beroende på om kanterna är ihoplänkade eller inte.
  • EDGE Ett topologiskt element som motsvarar en begränsad kurva. En kant är vanligtvis begränsad av hörn. Det har en dimension.
  • VERTEX Ett topologiskt element som motsvarar en punkt. Dess dimension är noll.
  • SHAPE En allmän term som täcker allt ovan.

The following topological data types are available:

  • Compound A group of any type of topological objects.
  • Compsolid A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids.
  • Solid A part of space limited by shells. It is three dimensional.
  • Shell A set of faces connected by their edges. A shell can be open or closed.
  • Face In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional.
  • Wire A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not.
  • Edge A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension.
  • Vertex A topological element corresponding to a point. It has zero dimension.
  • Shape A generic term covering all of the above.

Top

Exempel

Skapa simpel topologi

Wire
Wire

Vi ska nu skapa en topologi genom att konstruera den utifrån enklare geometri. Som ett studiefall så använder vi en del som syns i bilden vilken består av fyra hörn, två cirklar och två linjer.

Top

Skapa Geometri

Först så måste vi skapa de distinkt geometriska delarna av denna tråd. Och vi måste ta hänsyn till att hörnen på de geometriska delarna är på samma position. Annars kanske vi inte kan koppla ihop de geometriska delarna till en topologi!

First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices.

Så vi skapar punkterna först:

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)

Top

Cirkelbåge

Circle
Circle


För att skapa en cirkelbåge så skapar vi en hjälppunkt och skapar cirkelbågen genom tre punkter:

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

Top

Linje

Line
Line


Linjen kan skapas mycket lätt ur punkterna:

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

Top

Sätta ihop allt

Det sista steget är att sätta ihop den geometriska grundelementen och baka en topologisk form:

The last step is to put the geometric base elements together and bake a topological shape:

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

Top

Skapa ett prisma

Extrudera nu tråden i en riktning och skapa en äkta 3D form:

Now extrude the wire in a direction and make an actual 3D shape:

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

Top

Show it all

Part.show(P)

Top

Skapa grundtyper

Kort beskrivning

Du kan lätt skapa enkla topologiska objekt med "make...()" metoden från Del Modulen:

You can easily create basic topological objects with the make...() methods from the Part module:

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

Några andra make...() metoder fom finns:

  • makeBox(l,w,h,[p,d]) -- Skapa en låda placerad i p och pekar i riktningen d med dimensionerna (l,w,h). Som standard är p Vektor(0,0,0) och d är Vektor(0,0,1)
  • makeCircle(radius,[p,d,angle1,angle2]) -- Skapa en cirkel med en given radie. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) angle1=0 och angle2=360
  • makeCompound(list) -- Skapar en compound från en lista med former (shapes)
  • makeCone(radius1,radius2,height,[p,d,angle]) -- Skapa en kon med given radie och höjd. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) och angle=360
  • makeCylinder(radius,height,[p,d,angle]) -- Skapa en cylinder med given radie och höjd. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) och angle=360
  • makeLine((x1,y1,z1),(x2,y2,z2)) -- Skapa en linje mellan två punkter
  • makePlane(length,width,[p,d]) -- Skapa ett plan med längd och bredd. med given radie och höjd. Som standard är p Vektor(0,0,0), och d är Vektor(0,0,1)
  • makePolygon(list) -- Skapa en polygon från en lista med punkter
  • makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Skapa en sfär med given radie. Som standard är p Vektor(0,0,0), d Vektor(0,0,1), angle1=0, angle2=90 och angle3=360
  • makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Skapa en torus med given radie. Som standard är p Vektor(0,0,0), d Vektor(0,0,1), angle1=0, angle2=360 och angle3=360

See the Part API page for a complete list of available methods of the Part module.

Top

Detaljerade förklaringar

Importera först följande:

First we need to import the FreeCAD and Part modules so we can use their contents in Python:

import FreeCAD as App
import Part

Top

Create a vector

Vectors are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this:

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

We just created a vector at coordinates X = 3, Y = 2, Z = 0. In the Part module, vectors are used everywhere. Part shapes also use another kind of point representation called Vertex which is simply a container for a vector. You access the vector of a vertex like this:

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

Top

Hur skapar man en kant?

En kant är inget annat än en linje med två hörn:

An edge is nothing but a line with two vertices:

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

Notera: Du kan inte skapa en kant som passerar två hörn.

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

Du kan hitta en kants längd och centrum så här:

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

Top

Put the shape on screen

So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:

Part.show(edge)

The show function creates an object in our FreeCAD document and assigns our "edge" shape to it. Use this whenever it is time to display your creation on screen.

Top

Hur skapar man en tråd?

en tråd kan skapas från en lista med kanter eller en lista med trådar:

A wire is a multi-edge line and can be created from a list of edges or even a list of wires:

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) kommer att visa fyra linjer som bildar en kvadrat:

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

Top

Hur skapar man en yta?

Endast ytor som skapats av stängda trådar är giltiga.

I detta exempel, så är wire3 en stängd tråd men wire2 är inte det (se ovan)

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

Endast ytor har en area, inte trådar eller kanter.

Top

Hur skapar man en cirkel?

circle = Part.makeCircle(radius,[center,dir_normal,angle1,angle2]) -- Skapa en cirkel med en given radie

Som standard är, center=Vektor(0,0,0), dir_normal=Vektor(0,0,1), angle1=0 och angle2=360.

En cirkel kan skapas så här:

A circle can be created like this:

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

Om du vill skapa den vid en viss position och med en viss riktning

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

cirkeln kommer att skapas med en distans 10 från nollpunkten i x och kommer att vara vänd mot x axeln.

Notera: makeCircle accepterar endast Base.Vector() men inte tupler.

Du kan också skapa en cirkelbåge genom att ge start- och slutvinkel:

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)

Både arc1 och arc2 kommer tillsammans skapa en cirkel.

Vinklar ska anges i grader, om du har radianer, konvertera det genom att använda formeln:

Grader = radianer * 180/PI

eller genom att använda python's math modul (efter att du importerat math, förstås):

grader = math.degrees(radianer)

import math
degrees = math.degrees(radians)

Top

Hur skapar man en cirkelbåge längs punkter?

Olyckligtvis så finns det ingen makeArc funktion men vi har Part.Arc funktionen för att skapa en cirkelbåge längs tre punkter.

Det kan antas vara en cirkelbåge som förenar start- och slutpunkt genom mittenpunkten.

Part.Arc skapar ett arc objekt på vilken .toShape() måste kallas för att få kant objektet,

vilket i allmänhet skapas av makeLine eller makeCircle

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)

Notera: Arc accepterar endast Base.Vector() för punkter men inte tupler.

arc_edge är vad vi vill ha, vilken vi kan visa med Part.show(arc_edge).

Om du vill ha en liten del av en cirkel som en cirkelbåge, så är det också möjligt:

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

Arcs are valid edges like lines, so they can be used in wires also.

Top

Hur skapar man en polygon eller linje längs punkter?

En linje längs multipla punkter är inget annat än att skapa en tråd med multipla kanter.

makePolygon funktionen tar en lista med punkter och skapar en tråd längs dessa punkter:

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)])

Top

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)

Top

Hur skapar man ett plan?

Ett plan är en platt yta, alltså en yta i 2D

makePlane(length,width,[start_pnt,dir_normal]) -- Skapa ett plan

Som standard start_pnt=Vector(0,0,0) och dir_normal=Vector(0,0,1).

dir_normal=Vector(0,0,1) kommer att skapa ett plan vinkelrätt mot z axeln.

dir_normal=Vector(1,0,0) kommer att skapa ett plan vinkelrätt mot x axeln:

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 är en kub som omsluter planet med en diagonal som startar vid (3,0,0) och slutar vid (5,0,2).

Här ar BoundBox tjockleken i y axeln noll.

Notera: makePlane accepterar endast Base.Vector() för start_pnt och dir_normal men inte tupler

Top

Hur skapar man en ellips?

För att skapa en ellips så finns det flera sätt:

There are several ways to create an ellipse:

Part.Ellipse()

Skapar en ellips med majorradie 2 och minorradie 1 med

centrum i (0,0,0)

Part.Ellipse(Ellipse)

skapa en kopia på den givna ellipsen

Part.Ellipse(S1, S2, Center)

Skapar en ellips centrerad på punkten Center, där ellipsens plan är definierad av Center, S1 och S2, dess majoraxel är definierad av Center och S1, dess majorradie är avståndet mellan Center och S1, och dess minorradie är avståndet mellan S2 och majoraxeln.

Part.Ellipse(Center, MajorRadius, MinorRadius)

Skapar en ellips med major och minor radierna MajorRadius och MinorRadius, och är placerad i det plan som definieras av Center och normalen (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())

I koden ovan så har vi gett S1, S2 och centrum. I likhet med Arc, så skapar Ellipse också ett ellipsobjekt men inte kant, så vi behöver konvertera den till en kant genom att använda toShape() för att visa den

Note: Arc accepterar endast Base.Vector() för punkter men inte tupler

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

För Ellipse konstruktören ovan så har vi gett center, MajorRadius och MinorRadius

Top

Hur skapar man en Torus?

makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Skapa en torus med given radie och vinklar.

Som standard är pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle1=360 och angle=360

anse torus som en liten cirkel som sveper längs en stor cirkel:

radius1 den stora cirkelns radie, radius2 är den lilla cirkelns radie, pnt torusens centrum och dir är normalriktningen. angle1 och angle2 är vinklar i radianer för den lilla cirkeln, för att skapa en cirkelbåge den sista parametervinkeln är för att sektionera torusen:

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)

Ovanstående kod kommer att skapa en torus med diametern 20(radie 10) och tjocklek 4(lilla cirkelradien 2)

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

Ovanstående kod kommer att skapa en bit av en torus

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

Ovanstående kod kommer att skapa en semi torus, endast den sista parametern är ändrad d.v.s. vinkeln och de kvarvarande vinklarna är standardvärden.


Genom att ge vinkeln 180 så kommer en halvtorus att skapas

Top

Hur skapar man en låda eller en kub?

makeBox(length,width,height,[pnt,dir]) -- Skapar en låda placerad i pnt med dimensionerna (längd,bredd,höjd)

Som standard är pnt=Vektor(0,0,0) och dir=Vektor(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

Top

Hur skapar man en sfär?

makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Skapa en sför med given radie.

Som standard är pnt=Vektor(0,0,0), dir=Vektor(0,0,1), angle1=-90, angle2=90 och angle3=360.

angle1 och angle2 är sfärens vertikala minimum och maximum ,

angle3 sfärdiametern

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)

Top

Hur skapar men en Cylinder?

makeCylinder(radius,height,[pnt,dir,angle]) -- skapa en cylinder med given radie och höjd

Som standard är pnt=Vektor(0,0,0),dir=Vektor(0,0,1) och 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)

Top

Hur skapar man en Kon?

makeCone(radius1,radius2,height,[pnt,dir,angle]) -- skapa en kon med given radie och höjd

Som standard är pnt=Vector(0,0,0), dir=Vector(0,0,1) och 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)

Top

Modify shapes

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.

Top

Transform operations

Translate a shape

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

This will move our shape "myShape" 2 units in the X direction.

Top

Rotate a shape

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)

The above code will rotate the shape 180 degrees around the Z Axis.

Top

Matrix transformations

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)

Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three numbers, so these two lines do the same thing:

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

Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no deformations will occur (see Scaling a shape below). We can apply our transformation like this:

myShape.transformShape(myMat)

or

myShape.transformGeometry(myMat)

Top

Scale a shape

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)

Top

Booleska Operationer

Hur klipper man ut en form från en annan?

cut(...)

Skillnaden mellan denna och en given topografisk form.

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)

Top

Hur får man det gemensamma mellan två former?

common(...)

Skärning mellan denna och en given topografisk form.

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)

Top

Hur förenar man två former?

fuse(...)

Förening av denna och en given topografisk form.

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)

Top

Hur man sektionerar en solid med given form?

section(...)

Sektionering av denna med en given topografisk form.


Kommer att returnera en skärningskurva, en compound med kanter

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

Top

Extrusion

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

If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc with a filled face, you will obtain a solid cylinder:

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

Top

Utforska former

du kan lätt utforska den topologiska datastrukturen:

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

Genom att skriva in ovanstående rader i python tolken, kommer du att få en god förståelse av Del objektens struktur . Här skapade vårt makeBox() kommando en solid form. Denna solid, liksom alla Del solider, innehåller ytor. Ytor innehåller alltid trådar, vilka är listor på kanter som gränsar till ytan. Varje yta har exakt en stängd tråd. I tråden, så kan vi titta på varje kant separat, och inuti varje kant, så kan vi se hörnen. Raka kanter har förstås endast två hörn. Del Hörn är OCC former, men de har ett punktattribut vilket returnerar en snygg FreeCAD Vektor.

Top

Utforska Kanter

I fallet Kanter, vilken är en godtycklig kurva, så är det mycket troligt att du vill göra en diskretisering. I FreeCAD så är kanterna parametriserade av dess längder. Det innebär att du kan gå en kant/kurva genom dess längd:

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)

Nu kan du komma åt många av kantens egenskaper genom att använda längden som en position. Det betyder att om

kanten är 100mm lång så är startpositionen 0 och slutpositionen 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)

Top

Använda valet

Här ser vi nu hur vi kan använda det val som användaren gjorde i visaren.

Först av allt så skapar vi en låda och visar den i visaren

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")

Välj nu några ytor eller kanter. Med detta skript kan du

iterera alla valda objekt och deras delelement:

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)

Välj några kanter och detta skript kommer att beräkna längden:

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

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

Top

OCC flaskan

Ett typiskt exempel som finns på OpenCasCade Startsida är hur man bygger en flaska.

Detta är en god övning även för FreeCAD. Du kan faktiskt följa vårt exempel nedan och OCC sidan samtidigt , du kommer att få en god förståelse om hur OCC strukturer är implementerade i FreeCAD.


Hela skriptet nedan är även inkluderat i FreeCAD installationen (i Mod/Part mappen) och kan anropas från python tolken genom att skriva:

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)

Top

Det kompletta skriptet

Här är det kompletta MakeBottle skriptet:

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)

Top

Detaljerad förklaring

import FreeCAD as App
import Part, math

Vi kommer förstås behöva Del modulen, men också FreeCAD.Base modulen, vilken innehåller grundläggande FreeCAD strukturer som vektorer och matriser.

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)

Här definierar vi vår makeBottle funktion. Denna funktion kan anropas utan argument, som vi gjorde ovan, i vilket fall standardvärden för bredd, höjd, och tjocklek kommer att användas. Sedan så definierar vi ett par punkter som kommer att användas för att bygga vår grundprofil.

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

Här definierar vi själva geometrin: en cirkelbåge, gjord av 3 punkter, och två linjesegment, gjorda av 2 punkter.

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

Kommer du ihåg skillnaden mellan geometri och former? Här bygger vi former utifrån vår konstruktionsgeometri. 3 kanter (kanter kan vara raka eller krökta), sedan en tråd av dessa tre kanter.

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

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

Tills nu så har vi bara byggt en halv profil. Lättare än att bygga hela profilen på samma sätt, så behöver vi bara spegla det vi har gjort, och limma ihop båda halvorna. Så vi skapar först en matris. En matris är ett mycket vanligt sätt att tillämpa omvandlingar på objekt i 3D världen, eftersom den i en struktur kan innehålla alla grundläggande omvandlingar som 3D objekt kan påtvingas (flytta, rotera och skala). Här, efter att vi skapat matrisen, så speglar vi den, och vi skapar en kopia av vår tråd med tillämpning av vår omvandlingsmatris. Vi har nu två trådar, och vi kan göra en tredje tråd från dem, eftersom trådar egentligen är listor med kanter.

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

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

Nu när vi har en stängd tråd, så kan den omvandlas till en yta. När vi väl har en yta, så kan vi extrudera den. Genom att göra så, så skapar vi en solid. Sedan tillämpar vi en snygg liten fasning på vårt objekt för vi vill ha en bra design, eller hur?

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

När vår flaskas kropp är skapad, så behöver vi fortfarande skapa en hals. Så vi gör en ny solid, med en cylinder.

...
    myBody = myBody.fuse(myNeck)

Ihopsmältningsoperationen, vilket i andra applikationer ibland kallas för förening, är mycket kraftfull. Den kommer att limma ihop det som behövs, och ta bort de delar som inte behövs.

...
    return myBody

Sedan så får vi tillbaka vår Del solid som ett resultat av vår funktion. Denna Del solid, liksom andra Del former, kan tillskrivas ett objekt i ett FreeCAD dokument, med:

el = makeBottleTut()
Part.show(el)

eller, mer enkelt:

Top

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)

Top

Ladda och spara

Det finns flera sätt att spara ditt arbetet i Del modulen. Du kan förstås spara ditt FreeCAD dokument, men du kan också spara Del objekt direkt till vanliga CAD format, som BREP, IGS, STEP och 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.

Att spara en form till en fil är lätt. det finns exportBrep(), exportIges(), exportStl() och exportStep() metoder tillgängliga för alla form objekt. Så genom att göra:

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

detta kommer att spara vår låda i en STEP fil. För att ladda en BREP, IGES eller STEP fil, gör bara motsatsen:

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

Top

Mesh Scripting/sv
Mesh to Part/sv


Konvertera Del objekt till Nät

Att konvertera högnivåobjekt som Del former till enklare objekt som nät är en ganska enkel operation, där alla ytor på ett Del objekt blir triangulerade. Resultatet av denna triangulering (tessellering) används sedan till att konstruera ett nät: (Låt oss anta att vårt dokument innehåller ett Del objekt)

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)

Konvertera Nät till Del objekt

Konvertering av Nät till Del objekt är en mycket viktig operation i CAD arbete, eftersom du mycket ofta tar emot 3D data i nätformat från andra människor eller utmatade från andra applikationer. Nät är mycket praktiskt för att representera friformsgeometri och stora visuella scener, eftersom den är mycket kompakt, men för CAD föredrar vi i allmänhet mer högnivåobjekt som bär mycket mer information, som solider, eller ytor som är skapade av kurvor istället för trianglar.

Konvertering av nät till dessa högnivåobjekt (hanterat av Del Modulen i FreeCAD) är inte en lätt operation. Nät kan vara gjord av tusentals trianglar (till exempel när de är genererade av en 3D skanner), och att ha solider gjorda med samma antal ytor skulle bli väldigt tungrott att manipulera. Så generellt sett så vill du optimera objektet när du konverterar.

FreeCAD erbjuder för närvarande två metoder för att konvertera Nät till Del objekt. Den första metoden är en enkel, direkt konvertering, utan någon optimering:

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)

Den andra metoden erbjuder möjligheten att anse nätfasetter koplanära när vinkeln mellan dem är under ett visst värde. Detta tillåter uppbyggnad av mycket enklare former: (Låt oss anta att vårt dokument innehåller ett Nät objekt)

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

Den geometri som syns i FreeCAD's #D vyer är renderade av Coin3D biblioteket. Coin3D är en implementering av OpenInventor standarden. openCascade mjukvaran erbjuder också samma funktionalitet, men det beslöts när FreeCAD påbörjades att inte använda openCascade's inbyggda visare utan istället använda sig av den snabbare coin3D mjukvaran.

Description

OpenInventor är egentligen ett 3D scen beskrivningsspråk. Den scen som beskrivs i renderas sedan av OpenGL på din skärm. Coin3D gör arbetet med detta, så programmeraren inte behöver bry sig om komplexa openGL anrop, programmeraren behöver bara förse den med giltig OpenInventor kod. Den stora fördelen är att openInventor är en mycket välkänd och väldokumenterad standard.

Ett av de stora jobben som FreeCAD gör för dig är att översätta openCascade geometriinformation till openInventor språket.

OpenInventor beskriver en 3D scen i formen av en scenegraph, som den nedan:

image from Inventor mentor

En openInventor scengraf beskriver allt som utgör en 3D scen, som geometri, färger, material, ljus, etc, och organiserar all den data i smidig och klar struktur. Allting kan grupperas till sub-strukturer, vilket tillåter dig att organisera ditt sceninnehåll så som du vill. Här är ett exempel på en openInventor fil:

#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 {
       }
    }
}

Som du kan se, så är strukturen mycket simpel. Du använder separatorer för att organisera din data till block, lite som du skulle organisera dina filer i mappar. Varje uttryck påverkar vad som kommer härnäst, till exempel de första två punkterna i vår rot separator är en rotation och en förflyttning, båda kommer att påverka nästa punkt, vilken är en separator. I den separatorn, så är ett material definierat, och en annan förflyttning. Vår cylinder kommer därför att påverkas av båda förändringarna, den som vi lade direkt på den och den som vi lade på dess förälderseparator.

Vi har också många andra elementtyper för att organisera vår scen, som grupper, växlar eller annoteringar. Vi kan definiera mycket komplexa material för våra objekt, med färg, texturer, skugglägen och transparens. Vi kan också definiera ljus, kameror, och även rörelser. Det är även möjligt att bädda in skriptbitar i openInventor filer, för att definiera mer komplext beteende.

Om du är intresserad av att lära dig mer om openInventor, hoppa direkt till dess berömdaste referens, Inventor mentor.

I FreeCAD behöver vi normalt inte interagera direkt med scengrafen openInventor. Varje objekt i ett FreeCAD dokument, ett nät, en delform eller något annat, blir automatiskt konverterat till openInventor kod och insatt i huvudscengrafen som du ser i en 3D vy. Den scengrafen uppdateras kontinuerligt när du gör förändringar, lägger till eller tar bort objekt i dokumentet. Alla objekt (i App rymden) har en visare(ett motsvarande objekt i Gui rymden), som anvarar för att ge openInventor kod.

Men det finns många fördelar med att kunna komma åt scengrafen direkt. Vi kan till exempel temporärt ändra utseendet på ett objekt, eller vi kan lägga till objekt som inte har en reell existens i FreeCAD dokumentet, som till exempel konstruktionsgeometri, hjälpare, grafiska tips eller verktyg som manipulatorer eller information på skärmen.

Själva FreeCAD har flera verktyg för att se eller ändra openInventor kod. Till exempel, följande pythonkod kommer att visa openInventor representationen av ett valt objekt:

obj = FreeCAD.ActiveDocument.ActiveObject
viewprovider = obj.ViewObject
print viewprovider.toString()

Men vi har också en python modul som tillåter komplett åtkomst till allt som hanterar av Coin3D, som vår FreeCAD scengraf. Så, läs vidare på 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.

Top

Mesh to Part/sv
Pivy/sv


Introduction

Pivy är ett python bindnings bibliotek för Coin3d, det 3D-renderingsbibliotek som används av FreeCAD. när det importeras i en körande python tolk, så kan du föra en direkt dialog med alla körande scengrafer, som FreeCAD's 3D vyer, eller att även skapa nya. Pivy följer med i en standard FreeCAD installation.

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.

Coin biblioteket är uppdelat i flera delar, själva coin, för manipulation av scengrafer och bindningar för flera GUI system, som windows, eller som i vårt fall, qt. Dessa moduler är även tillgängliga för pivy, beroende på om de finns i systemet. Coin modulen finns alltid, och det är vad vi kommer att använda i alla fall, eftersom vi inte behöver bry oss om att förankra vårt 3D fönster i något gränssnitt, det görs redan av FreeCAD själv. Allt vi behöver göra är detta:

from pivy import coin

Komma åt och ändra scengrafen

Vi såg i Scengraf sidan hur en typisk Coin scen är organiserad. Allt som syns i en FreeCAD 3D vy är en coin scengraf, organiserad på samma sätt. Vi har en rotnod, och alla objekt på skärmen är dess barn.

FreeCAD har ett lätt sätt att komma åt 3D vy scengrafens rotnod:

sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
print(sg)

Detta kommer att returnera rotnoden:

<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >

Vi kan inspektera vår scen's närmaste barn:

for node in sg.getChildren():
    print(node)

En del av dessa noder, som SoSeparators eller SoGroups, kan själva ha barn. Den kompletta listan på de tillgängliga coin objekten kan återfinnas på official coin documentation.

Låt oss försöka lägga till något till vår scengraf nu. Vi lägger till en snygg röd kub:

col = coin.SoBaseColor()
col.rgb = (1, 0, 0)
cub = coin.SoCube()
myCustomNode = coin.SoSeparator()
myCustomNode.addChild(col)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)

och här är vår (snygga) röda kub. Låt os nu försöka detta:

col.rgb = (1, 1, 0)

Se? Allt är fortfarande åtkomligt och förändringsbart direkt. Inget behov av omberäkningar eller omritningar, coin tar hand om allt. Du kan lägga till saker till din scengraf, ändra egenskaper, gömma saker, visa temporära objekt, allting. Detta gäller förstås endast visningen i 3D vyn. Den visningen beräknas om av FreeCAD när filen öppnas, och när ett objekt behöver omberäknas. Så om du ändrar en aspekt på ett existerande FreeCAD objekt, så kommer dessa ändringar att förloras om objektet beräknas om eller när du öppnar filen igen.

En nyckel till arbete med scengrafer i dina skript är att kunna komma åt vissa egenskaper på de noder som du vid behov lägger till. Till exempel, om vi skulle vilja flytta vår kub, så skulle vil ha lagt till en SoTranslation nod till vår anpassade nod, och det skulle ha sett ut så här:

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)

Kom ihåg att i en openInventor scengraf, så är ordningen viktig. en nod påverkar efterkommande saker, så du kan säga något som : färg röd, kub, färg gul, sfär, och du kommer att få en röd kub och en gul sfär. Om vi lade till förflyttning till vår existerande anpassade nod, så skulle den komma efter kuben, och inte påverka den. Om vi hade satt in den när vi skapade den, som här ovan, så skulle vi nu kunna göra:

trans.translation.setValue([2, 0, 0])

Och vår kub skulle hoppa 2 enheter åt höger. Slutligen, att ta bort något görs med:

sg.removeChild(myCustomNode)

Top

Använda återanropsmekanismer

En återanropsmekanism är ett system som tillåter ett bibliotek som du använder, som vårt coin bibliotek, att anropa tillbaka, vilket innebär att anropa en viss funktion från ditt för närvarande körande python objekt. Detta är väldigt användbart, därför att på det sättet så kan coin meddela python objektet om någon specifik händelse uppstår i scenen. Coin kan övervaka väldigt olika saker, som musposition, musklick, tangentbordsnedtryckningar, och många andra saker.

FreeCAD erbjuder ett lätt sätt att använda sådana återanrop:

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()

Återanropet måste initieras från ett objekt, därför så måste det objektet fortfarande köras när återanropet uppstår.

Se även den kompletta listan för möjliga händelser och dess parametrar, eller i den officiella coin dokumentationen.

Top

Dokumentation

Olyckligtvis har pivy själv ingen ordentlig dokumentation, men eftersom det är en riktig översättning av coin, så kan du med säkerhet använda coin dokumentationen som referens, och använda python stil istället för c++ stil (till exempel SoFile::getClassTypeId() skulle i pivy bli 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.

Top

Scenegraph/sv
PySide/sv


Introduction

The PySide library gives access to the cross-platform graphical user interface (GUI) toolkit Qt from Python. Qt is a collection of C++ libraries, but with the help of PySide, the same components can be used from Python. Every graphical interface that can be created in C++, can also be created and modified in Python. An advantage of using Python is that Qt interfaces can be developed and tested live, as we don't need to compile the source files.

When you install FreeCAD, you should get both Qt and PySide as part of the package. If you are compiling yourself then you must verify that these two libraries are installed in order for FreeCAD to run correctly. Of course, PySide will only work if Qt is present.

In the past, FreeCAD used PyQt, another Qt binding for Python, but in 2013 (commit 1dc122dc9a) the project migrated to PySide because it has a more permissible License.

For more information see:

Examples created with PySide. Left: a simple dialog. Right: a more complex dialog with graphs.

PySide in FreeCAD with Qt5

FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility.

Normally, the PySide module provides support for Qt4, while PySide2 provides support for Qt5. However, in FreeCAD there is no need to use PySide2 directly, as a special PySide module is included to handle Qt5.

This PySide module is located in the Ext/ directory of an installation of FreeCAD compiled for Qt5.

/usr/share/freecad/Ext/PySide

This module just imports the necessary classes from PySide2, and places them in the PySide namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as we use the single PySide module.

PySide2.QtCore -> PySide.QtCore
PySide2.QtGui -> PySide.QtGui
PySide2.QtSvg -> PySide.QtSvg
PySide2.QtUiTools -> PySide.QtUiTools

The only unusual aspect is that the PySide2.QtWidgets classes are placed in the PySide.QtGui namespace.

PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox

Top

Examples of PySide use

The examples of PySide are divided into 3 parts, differentiated by level of exposure to PySide, Python and the FreeCAD internals. The first page has an overview on PySide; the second and third pages are mostly code examples at different levels.

It is expected that these examples are useful to get started, and afterwards the user can consult other resources online, or the official documentation.

Top

Documentation

There are some differences in handling of widgets in Qt4 (PySide) and Qt5 (PySide2). The programmer should be aware of these incompatibilities, and should consult the official documentation if something doesn't seem to work as expected on a given platform. Nevertheless, Qt4 is considered obsolete, so most development should target Qt5 and Python 3.

The PySide documentation refers to the Python-style classes; however, since Qt is originally a C++ library, the same information should be available in the corresponding C++ reference.

Top


Introduction

Förutom standard objekttyper som annoteringar, nät och delobjekt, så erbjuder FreeCAD också den fantastiska möjligheten att bygga 100% python-skriptade objekt, som kallas för Python Funktioner. dessa objekt kommer att bete sig exakt som alla andra FreeCAD objekt, de kan sparas i ett dokument och öppnas av en annan FreeCAD installation, eftersom den python kod som definierar objektet även sparas i dokumentet.

One particularity must be understood: For security reasons, FreeCAD files never carry any embedded code. The Python code that you write to create parametric objects is never saved inside a file. This means that if you open a file containing such an object on another machine, if that python code is not available on that machine, the object won't be fully recreated. If you distribute such objects to others, you will need to distribute your Python script too, for example as a Macro.

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.

Python Funktioner följer samma regler som alla FreeCAD funktioner: de är separerade i App och GUI delar. App delen, Dokumentobjektet, definierar vårt objekts geometri , medan dess gränssnittsdel, Visaobjektet, definierar hur objektet kommer att ritas på skärmen. VisaObjektet, är som alla andra FreeCAD funktioner, endast tillgängligt när du kör FreeCAD i dess eget gränssnitt. Det finns flera egenskaper och metoder tillgängliga för att bygga ditt objekt. Egenskaperna måste vara en av de fördefinierade egenskapstyperna som FreeCAD erbjuder, och kommer att visas i egenskapsfönstret, så de kan redigeras av användaren. på detta sätt så är Python Funktionsobjekt totalt parametrisk. Du kan definiera egenskaper för objektet och dess Visaobjekt separat.

Basic example

Enkelt exempel

Följande exempel kan hittas i src/Mod/TemplatePyMod/FeaturePython.py filen, tillsammans med flera andra exempel:

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

Andra mer komplexa exempel

Detta exempel använder sig av Del Modulen för att skapa en oktahedron, sedan skapas dess coin representation med pivy.

Det första är själva Dokument objektet:

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

Sedan så har vi visarobjektet, ansvarigt för att visa objektet i 3D scenen:

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

Slutligen, när vårt objekt och dess visningsobjekt är definierade, så behöver vi bara anropa dem:

FreeCAD.newDocument()
a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron")
Octahedron(a)
ViewProviderOctahedron(a.ViewObject)

Making objects selectable

Göra objekt valbara

Om du vill göra ditt objekt valbart, eller åtminstone en del av den, genom att klicka på den i vyn, så måste du inkludera dess geometri inuti en SoFCSelection nod. Om ditt objekt har en komplex representation, med widgetar, annoteringar, etc, så kanske du bara vill inkludera en del av den i en SoFCSelection. Allt som är en SoFCSelection skannas konstant av FreeCAD för att detektera val/förval, så det är vettigt att inte försöka överbelasta den med onödig skanning. Detta är vad du skulle göra för att inkludera en self.face från det ovan visade exemplet:

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

Arbeta med enkla former

Om ditt parametriska objektbara resulterar i en form, så behöver du inte använda ett visarobjekt. Formen kommer att visas med hjälp av FreeCAD's standard form representation:

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

Tillgängliga egenskaper

Egenskaper är PythonFunktion objektens sanna byggstenar. Genom dem, så kan användaren interagera och ändra objektet. Efter att ett nytt PythonFunktion objekt har skapats i ditt dokument ( a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), så kan du få en lista på de tillgängliga egenskaperna genom att skriva:

obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Box")
obj.supportedProperties()

Du kommer att få en lista på tillgängliga egenskaper:

När du adderar egenskaper till dina anpassade objekt, var uppmärksam på detta:

  • Använd inte tecknen "<" eller ">" i egenskapsbeskrivningen (det förstör xml delarna i .fcstd filen)
  • Egenskaper lagras i alfabetisk ordning i en .fcstd fil. Om du har en form i dina egenskaper, så kommer alla egenskaper vars namn kommer efter "Form" i alfabetisk ordning att laddas EFTER formen, vilket kan orsaka ett märkligt beteende.

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/sv
Embedding FreeCAD/sv

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 har den fantastiska förmågan att kunna importeras som en python modul i andra program eller i en python konsol, tilsammans med alla dess moduler och komponenter. Det är även möjligt att importera FreeCAD's gränssnitt som en python modul -- emellertid med några begränsningar.

Använda FreeCAD utan gränssnitt

En första, direkt, lätt och användbar sak du kan göra med detta är att importera FreeCAD dokument in till ditt program. I det följande exemplet, så kommer vi att importera Del geometrin i ett FreeCAD dokument till blender. Här är det kompletta skriptet. Jag hoppas att du kommer att bli imponerad av dess enkelhet:

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()

Den första, viktiga delen är att försäkra sig om att python kan hitta vårt FreeCAD bibliotek. När den väl har hittats, så kommer alla FreeCAD moduler som Del, som vi kommer använda, automatiskat att vara tillgängliga. Så vi tar bara sys.path variabeln, vilket är var python söker efter moduler, och lägger till sökvägen till FreeCAD's bibliotek. Denna ändring är endast temporär, och kommer att förloras när vi stänger vår python tolk. Ett annat sätt kan vara att göra en länk till ditt FreeCAD bibliotek i en av python's sökvägar. Jag behöll sökvägen i en konstant (FREECADPATH) så att det blir lättare för en annan användare av skriptet att konfigurera den till sitt eget system.

FREECADPATH = 'C:\\FreeCAD\\bin' # path to your FreeCAD.so or FreeCAD.pyd file
import sys
sys.path.append(FREECADPATH)

När vi är säkra på att biblioteket är laddat(try/except sekvensen), så kan vi nu arbeta med FreeCAD, på samma sätt som vi skulle inuti FreeCAD's egen python tolk. Vi öppnar FreeCAD dokumentet som skickats till oss genom main() funktionen, och vi gör en lista på dess objekt. Sedan då vi valde att endast bry oss om Del geometri, så kontrollerar vi om varje objekts Typegenskap innehåller "Part", sedan tesselerar vi den.

import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':

Tesseleringen producerar en lista på hörn och en lista på ytor som definierats av hörnindexen. Detta är perfekt, eftersom det är på exakt samma sätt som blender definierar nät. Så vår uppgift är löjligt enkel, vi adderar bara båda listinnehållen till verts och faces av ett blender nät. När allting är gjort, så ritar vi bara om skärmen, och det är klart!

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()

Detta skript är förstås mycket enkelt (det finns ett mer avancerat här), du kanske vill bygga ut det, för att till exempel importera nätobjekt också, eller importera Del geometri som inte har några ytor, eller importera andra filformat som FreeCAD kan läsa. Du kanske också vill exportera geometri till ett FreeCAD dokument, vilket kan göras på samma sätt. Du kanske också vill bygga en dialog, så att användaren kan välja vad som ska importeras, etc... Skönheten i allt detta ligger i det faktum att du låter FreeCAD göra grundarbetet medan du presenterar dess resultat i ett program som du väljer.

Note: checkout Headless FreeCAD for running FreeCAD without the GUI.

Använda FreeCAD med gränssnitt

Från och med version 4.2 så har Qt den fängslande förmågan att inbädda Qt-gränssnitt-beroende plugins till icke-Qt värdapplikationer och dela värdens händelseslinga.

Speciellt för FreeCAD så betyder detta att den kan importeras från en annan applikation med hela gränssnittet där värdapplikationen har full kontroll över FreeCAD.

Hela python koden för att uppnå detta har bara två rader

import FreeCADGui 
FreeCADGui.showMainWindow()

Om värdapplikationen är baserad på Qt så ska denna lösningen fungera på alla plattformar som Qt stöder. emellertid så ska värden länka samma Qt version som FreeCAD, annars såkan du få oväntade fel.

Men för icke-Qt applikationer så finns det en del begränsningar som du måste vara uppmärksam på. Denna lösning fungerar troligen inte tillsammans med alla andra verktygskiten.

I Windows så fungerar det så länge som värdapplikationen är direkt baserad på Win32 eller något annat verktygskit som internt använder Win32 API som wxWidgets, MFC eller WinForms. för att få det att fungera under X11 så måste värdapplikationen länka till "glib" biblioteket.

Notera att för konsolapplikationer fungerar inte denna lösning eftersom det inte finns någon händelseslinga som körs.

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



Introduction

Denna sida innehåller exempel, delar, bitar av FreeCAD pythonkod som samlats ihop från användare och diskussioner på forumen. Läs och använd dem som en början för dina egna skript...

Snippets

En typisk InitGui.py fil

Varje modul måste innehålla, förutom din huvudmodul fil, en InitGui.py fil, som ansvarar för insättningen av modulen i huvudgränssnittet. Detta är ett exempel på en enkel sådan.

Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

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())

Top

En typisk modulfil

Detta är ett exempel på en huvudmodulfil, som innehåller allt som din modul gör. Det är Scripts.py filen startad i föregående exempel. Du kan ha alla dina anpassade kommandon här.

This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

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())

Top

Importera en ny filtyp

Att skapa en importerare för en ny filtyp i FreeCAD är lätt. FreeCAD anser inte att du importerar data i ett öppnat dokument, utan snarare att du direkt kan öppna den nya filtypen. Så vad du behöver göra är att lägga till den nya filtypen till FreeCAD's lista på kända filtyper, och skriva koden som kommer att läsa filen och skapa de FreeCAD objekt som du vill:

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

Denna rad måste läggas till i InitGui.py filen för att lägga till den nya filtypen till listan:

# 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")

Sedan i filen 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()

För att exportera ditt dokument till någon ny filtyp fungerar på samma sätt, förutom att du använder:

FreeCAD.addExportType("Din nya FilTyp (*.ext)","Export_Ext")

Top

Lägga till en linje

En linje har 2 punkter.

A line simply has 2 points.

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()

Top

Lägga till en polygon

En polygon ett set av ihopkopplade linjesegment (en polyline i AutoCAD). Den behöver inte vara stängd.

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

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()

Top

Lägga till och ta bort ett objekt till/från en grupp

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

Notera: Du kan även lägga till andra grupper till en grupp...

Top

Lägga till ett nät

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

Top

Lägga till en cirkelbåge eller en cirkel

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()

Top

Komma åt och ändra representationen av ett objekt

Varje objekt i ett FreeCAD dokument har ett associerat vy representationsobjekt som sparar alla parametrar som definierar hur objekten syns, som färg, linjebredd, etc...

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how that object appears: i.e. color, linewidth, etc... See also List the components of an object snippet below

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

Top

Replace the form of mouse with one image

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

Top

Replace the form of mouse with one image (cross) include

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

Top

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)

Top

Observation av mushändelser i 3D visaren via Python

Inventor ramverket tillåter att du lägger till en eller flera återanropsnoder vill visarens scengraf. som standard i FreeCAD är en återanropsnod installerad per visare vilket tillåter att du kan lägga till globala eller statiska C++ funktioner. I en lämplig Python bindning så erbjuds några metoder för att använda denna teknik inuti Python kod.

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

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)


Klicka nu någonstans i 3D visaren och observera meddelandena i utmatningsfönstret. För att avsluta observationen, anropa bara

v.removeEventCallback("SoMouseButtonEvent",c)

Följande händelsetyper stöds

  • SoEvent -- alla sorts händelser
  • SoButtonEvent -- alla musknapps och tangentbordshändelser
  • SoLocation2Event -- 2D rörelsehändelser (normalt musförflyttningar)
  • SoMotion3Event -- 3D rörelsehändelser (normalt spaceball)
  • SoKeyboardEvent -- tangentbordsknapp ned och upphändelser
  • SoMouseButtonEvent -- musknapp ned och upphändelser
  • SoSpaceballButtonEvent -- spaceballknapp ned och upphändelser

Python funktionen som kan registreras med addEventCallback() förväntar sig ett lexikon. Beroende på den övervakade händelsen så kan lexikonet innehålla olika nycklar.

För alla händelser så har den nycklarna:

  • Type -- händelsetypens namn d.v.s. SoMouseEvent, SoLocation2Event, ...
  • Time -- nuvarande tid som en sträng
  • Position -- en tupel med två heltal, musposition
  • ShiftDown -- en boolesk, sann om Skift var nedtryckt, annars falsk
  • CtrlDown -- en boolesk, sann om CTRL var nedtryckt, annars falsk
  • AltDown -- en boolesk, sann om Alt var nedtryckt, annars falsk


För alla knapphändelser, d.v.s. tangentbord, mus eller spaceball händelser

  • State -- En sträng 'UP' om knappen var uppe, 'DOWN' om den var nera eller 'UNKNOWN' för alla andra fall


För tangentbordshändelser:

  • Key -- tecknet för den nedtryckta tangenten


För musknappshändelser

  • Button -- den nedtryckta knappen, kan vara BUTTON1, ..., BUTTON5 eller ANY


För spaceballhändelser:

  • Button -- den nedtryckta knappen, kan vara BUTTON1, ..., BUTTON7 eller ANY


Och slutligen rörelsehändelser:

  • Förflyttning -- en tupel med tre flyttal
  • Rotation -- en kvaternion för rotationen, d.v.s. en tupel med fyra flyttal

Top

Display keys pressed and Events command

This macro displays in the report view the keys pressed and all events command

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

Top

Manipulera scengrafen i Python

Det är också möjligt att hämta och ändra scengrafen i Python, med 'pivy' modulen -- en Python bindning för Coin.

It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for 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()

Pivy's Python API skapas med hjälp av verktyget SWIG. Då vi i FreeCAD använder några självskrivna noder så kan du inte skapa dem direkt i Python. Emellertid så är det möjligt att skapa en nod med dess interna namn. En instans av typen 'SoFCSelection' kan skapas med

type = SoType.fromName("SoFCSelection")
node = type.createInstance()

Top

Lägga till och ta bort objekt till/från scengrafen

Addering av nya noder till scengrafen kan görass på detta sätt. Var noga med att alltid lägga till en SoSeparator för att innehålla geometrin, koordinaterna och materialinformationen på samma objekt. Följande exempel lägger till en röd linje från (0,0,0) till (10,0,0):

Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (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)

För att ta bort den, skriv bara:

sg.removeChild(no)

Top

Save the sceneGraph in 3 series of 36 files

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)

Top

Lägga till anpassade widgetar till gränssnittet

Du kan skapa anpassade widgetar med Qt designer, omvandla dem till ett python skript, och sedan ladda dem till FreeCAD gränssnittet med PyQt4.

You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PySide.

Den pythonkod som producerats av Ui pythonkompilatorn (det verktyg som konverterar qt-designer .ui file till pythonkod) ser i allmänhet ut så här (det är enkelt, du kan även skriva det direkt i 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))

Allt du sedan behöver göra är att skapa en referens till FreeCAD's Qt fönster, sätta in en anpassad widget i det, och "omvandla" denna widget till din med den Ui kod vi just gjorde:

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

Top

Add a Tab to the Combo View

The following code allows you to add a tab to the Combo view, separate from the preexisting "Model" and "Tasks" tabs. It also uses the uic module to load an UI file directly in that tab.

# 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)

Top

Enable or disable a window

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

Top

Open a custom webpage

import WebGui
WebGui.openBrowser("http://www.example.com")

Top

Get the HTML contents of an opened webpage

from PySide import QtGui,QtWebKit
a = QtGui.qApp
mw = a.activeWindow()
v = mw.findChild(QtWebKit.QWebFrame)
html = unicode(v.toHtml())
print( html)

Top

Retrieve the coordinates of 3 selected points or objects

# -*- 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")

Top

List all objects

# -*- 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

Top

List the dimensions of an object, given its name

for edge in FreeCAD.ActiveDocument.MyObjectName.Shape.Edges: # replace "MyObjectName" for list
    print( edge.Length)

Top

Function resident with the mouse click action

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)

Top

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

Top

Find/select all elements below the 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)

Top

List the components of an object

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()

Top

List the PropertiesList

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")

Top

Add a single Property Comment

import Draft
obj = FreeCADGui.Selection.getSelection()[0]
obj.addProperty("App::PropertyString","GComment","Draft","Font name").GComment = "Comment here"
App.activeDocument().recompute()

Top

Search and data extraction

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)
##################################################################################

Top

Manual search of an element with label

# 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)

Top

Cartesian coordinates

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"

Top

Select all objects in the document

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

Top

Select a face of an object by Name object and Face number

# 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)                       #

Top

Get the normal vector of a face of an object by Name object and number Face (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)

Top

Get the normal vector of a face of an object by Name object and number of Face

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)

Top

Get the normal vector of an object selected and number of Face

## 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))

Top

Get the normal vector on the surface

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)

Top

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

Top

Get the normal vector of a surface from a STL file

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)

Top

Create one object to the position of the Camera

# 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)

Top

Read And write one Expression

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])

Top

Create a Sketch on a Surface in PartDesign

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()

Top

How to Simulate a Mouse Click at a given Coordinate

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)

Top

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)

Top

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
        )

Top

Coin3D

See Coin3d snippets

Top

Related

Top


Introduction

Denna sida visar hur lätt avancerad funktionalitet kan byggas i Python. I denna övning, så kommer vi att bygga ett nytt verktyg som ritar en linje. Detta verktyg kan sedan länkas till ett FreeCAD kommando, och det kommandot kan anropas av ett element i gränssnittet, som en menypunkt eller en knapp i en verktygslåda.

Huvudskriptet

Först kommer vi att skriva ett skript som innehåller all vår funktionalitet. Sedan kommer vi att spara detta i en fil, och importera den i FreeCAD, så att alla klasser och funktioner som vi skriver kommer att vara tillgängliga för FreeCAD. Så, starta din favorit textredigerare, , och skriv följande rader:

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)

Top

Detaljerad förklaring

import Part, FreeCADGui
from pivy.coin import *

När du vill använda funktioner från en annan modul I Python, så behöver du importera den. I vårt fall, så behöver vi funktioner från Del Modulen, för att skapa linjen, och från gränssnittsmodulen (FreeCADGui), för att komma åt 3D vyn. Vi behöver även innehållet i coin biblioteket, så vi kan använda alla coin objekt som SoMouseButtonEvent, etc...

class line:

Här definierar vi vår huvudklass. Varför använder vi en klass och inte en funktion? Skälet är att vårt verktyg behöver "stanna vid liv" medan vi väntar på att användaren ska klicka på skärmen. En funktion avslutas när dess uppgift är klar, men ett objekt (en klass definierar ett objekt) stannar vid liv ända tills den förstörs.

"""This class will create a line after the user clicked 2 points on the screen"""

I Python, så kan varje klass eller funktion ha en beskrivningssträng. Detta är speciellt användbart i FreeCAD, därför att när du anropar den klassen i tolken, så visas beskrivningssträngen som ett verktygstips.

def __init__(self):

Python klasser kan alltid innehålla en __init__ funktion, vilken utförs när klassen anropas för att skapa ett objekt. Så här lägger vi allt som vi vill ska hända när vårt linjeverktyg börjar.

self.view = FreeCADGui.ActiveDocument.ActiveView

I en klass, så vill du vanligtvis lägga till self. innan ett variabelnamn, så att den kan kommas åt lätt för alla funktioner inuti och utanför den klassen. Här kommer vi att använda self.view för att komma åt och manipulera den aktiva 3D vyn.

self.stack = []

Här skapar vi en tom lista som kommer att innehålla 3D punkterna som sänds av getpoint funktionen.

self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

Detta är den viktiga delen: Eftersom det egentligen är en coin3D scen, så använder FreeCAD coin's återanropsmekanism, som tillåter en funktion att anropas varje gång en viss scenhändelse inträffar. I vårt fall, så skapar vi ett återanrop för SoMouseButtonEvent händelser, och vi binder den till getpoint funktionen. Nu, varje gång som en musknapp trycks ned eller släpps, så kommer getpoint funktionen att utföras.

Notera att det finns ett alternativ till addEventCallbackPivy() kallat addEventCallback() vilket dispenserar bruket av pivy. Men eftersom pivy är en mycket effektiv och naturlig väg att komma åt en del av coin scenen, så är det mycket bättre att använda den så mycket du kan!

Top

def getpoint(self, event_cb):

Nu definierar vi getpoint funktionen, som kommer utföras när en musknapp trycks ned i en 3D vy. Denna funktion kommer att ta emot ett argument, som vi kommer kalla event_cb. Från denna händelses återanrop kan vi komma åt händelseobjektet, vilket innehåller flera informationsbitar (läge info här).

if event.getState() == SoMouseButtonEvent.DOWN:

Getpoint funktionen kommer att anropas när en musknapp trycks ned eller släpps. Men vi vill bara välja en 3D punkt när den trycks ned (annars skulle vi få två 3D punkter mycket nära varann). Så vi måste kontrollera det här.

pos = event.getPosition()

Här får vi musmarkörens skärmkoordinater

point = self.view.getPoint(pos[0], pos[1])

Denna funktion ger oss en FreeCAD vektor (x,y,z) som innehåller den 3D punkt som ligger på fokalplanet, precis under vår musmarkör. om du är i kameravy, tänk dig en stråle som kommer från kameran, och passerar genom musmarkören, och träffar fokalplanet. Där är vår 3D punkt. On vi är i ortogonal vy, så är strålen parallell med vyriktningen.

self.stack.append(point)

Vi lägger till vår nya punkt till stacken

if len(self.stack) == 2:

Har vi tillräckligt med punkter? Om ja, låt oss då rita linjen!

l = Part.LineSegment(self.stack[0], self.stack[1])

Här använder vi funktionen Line() från Del Modulen som skapar en linje från två FreeCAD vektorer. Allt som vi skapar och ändrar inuti Del modulen, stannar i Del modulen. Så, tills nu, så har vi skapat en Linje Del. Den är inte bunden till något objekt i vårt aktiva dokument, så inget syns på skärmen.

shape = l.toShape()

FreeCAD dokumentet kan bara acceptera former från Del modulen. Former är Del modulens mest allmäna typ. Så vi behöver konvertera vår linje till en form innan vi lägger till den till dokumentet.

Part.show(shape)

Del modulen har en mycket smidig show() funktion som skapar ett nytt objekt i dokumentet och binder en form till den. Vi skulle också kunna ha skapat ett nytt objekt i dokumentet först, och sedan ha bundit formen till den manuellt.

self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Eftersom vi är klara med vår linje, låt oss ta bort vår återanropsmekanism, som använder värdefulla CPU cykler.

Top

Testa & använda skriptet

Låt oss nu spara vårt skript på någon plats där FreeCAD's python tolk kommer att hitta den. När moduler importerass, så kommer tolken att leta på följande platser: python's installationssökväg, FreeCAD bin katalogen, och alla FreeCAD modulkataloger. Så, den bästa lösningen är att skapa en ny katalog i en av FreeCAD's Mod kataloger, och spara vårt skript i den. Låt oss till exempel skapa en "MinaSkript" katalog, och spara vårt skript som "ovning.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.

Nu är allt klart, låt oss starta FreeCAD, skapa ett nytt dokument, och i pythontolken skriva:

import exercise

Om inga felmeddelanden kommer fram, så innebär det att vårt övningsskript har laddats. Vi kan nu kontrollera dess innehåll med :

dir(exercise)

Kommandot dir() är ett inbyggt python kommando som listar modulens innehåll. Vi kan se att vår line() klass är där, som väntar på oss. Låt oss nu testa den:

'line' in dir(exercise)

Now let's test it:

exercise.line()

Klicka sedan på två olika ställen i 3D vyn, och bingo, där är vår linje! För att göra det igen, skriv bara ovning.line() igen, och igen, och igen... Känns det bra?

Top

Registrera skriptet i FreeCAD's gränssnitt

För att vårt nya linjeverktyg ska bli ännu häftigare, så borde det ha en knapp i gränssnittet, så vi inte behöver skriva allt det varje gång. Den lättaste vägen är att omvandla vår nya MinaSkript katalog till en full FreeCAD arbetsbänk. Det är lätt, allt som behövs är att lägga in en fil som kallas InitGui.py inuti din MinaSkript katalog. InitGui.py kommer att innehålla instruktioner för att skapa en ny arbetsbänk, och addera vårt nya verktyg till den. Förutom det så behöver vi ändra vår övningskod lite, så att line() verktyget igenkänns som ett officiellt FreeCAD kommando. Låt oss starta genom att göra en InitGui.py fil, och skriva följande kod i den:

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())

Jag tror att du redan nu förstår det ovanstående skriptet: Vi skapar en ny klass som vi kallar MinArbetsbänk, vi ger den en titel (MenuText), och vi definierar en Initialize() funktion som kommer att utföras när arbetsbänken laddas till FreeCAD. I den funktionen så laddar vi innehållet i vår övningsfil, och lägger till de FreeCAD kommandon som hittas i det i en kommandolista. Sedan gör vi en verktygslåda som kallas "Mina Skript" och vi tilldelar vår kommandolista till den. För närvarande har vi förstås endast ett verktyg, så vår kommandolista innehåller endast ett element. Sedan, när vår arbetsbänk är klar, så lägger vi till den till huvudgränssnittet.

Men det kommer fortfarande inte att fungera, därför att ett FreeCAD kommando måste formatteras på ett visst sätt för att fungera. så vi behöver ändra vårt line() verktyg lite. Vår nya ovning.py skript kommer nu att se ut så här:

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())

Vad vi gjorde här var att omvandla vår __init__() funktion till en Activated() funktion, därför att när FreeCAD kommandon körs, så utför de automatiskt Activated() funktionen. Vi lade också till en GetResources() funktion, som informerar FreeCAD var den kan hitta en ikon för verktyget, och namnet och verktygstipset för vårt verktyg. en jpg, png eller svg bild kommer att fungera som en ikon, den kan vara av valfri storlek, men det är bäst att använda en storlek osm är nära den slutliga, som 16x16, 24x24 eller 32x32.

Sedan lägger vi till line() klassen som ett officiellt FreeCAD kommando med addCommand() metoden.

Klart, nu behöver vi bara starta om FreeCAD och vi kommer att ha en ny snygg arbetsbänk med vårt splitternya verktyg!

Top

Så du vill ha mer?

Om du gillade denna övningen, varför inte försöka förbättra detta lilla verktyg? Det finns många saker som kan göras, som till exempel:

  • Lägga till feedback för användaren: nu är det ett mycket 'naket' verktyg, så användaren kan bli lite osäker när det används. Så vi skulle kunna lägga till lite feedback, tala om vad som ska göras. Du skulle till exempel kunna mata ur meddelanden till FreeCAD konsolen. Ta en titt i FreeCAD.Console modulen
  • Lägga till en möjlighet att skriva in 3D punkterna manuellt. Titta på python input() funktionen, till exempel
  • Lägga till möjligheten att lägga till mer än 2 punkter
  • Lägga till händelser för andra saker: Nu kontrollerar vi endast musknappshändelser, men om vi också kunde göra något när musen förflyttas, som att visa koordinater?
  • Ge ett namn till det skapade objektet

Tveka inte att skriva dina frågor eller ideer på forum!

Don't hesitate to ask questions or share ideas on the forum!

Top


Introduction

På denna sida kommer vi att visa hur man bygger en simpel Qt Dialog med Qt Designer, Qt's officiella verktyg för att designa gränssnitt, och sedan konvertera den till pythonkod, och sedan använda den inuti FreeCAD. Jag antar i exemplet att du redan vet hur du ska redigera och köra python skript, och att du kan göra enkla saker i ett terminalfönster som att navigera, etc. Du måste förstås också ha pyqt installerat.

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.

Designa dialogen

Att i CAD applikationer designa ett bra användargränssnitt är mycket viktigt. Nästan allt som användaren kommer att göra kommer att vara genom någon typ av gränssnitt: läsa dialogrutor, klicka på knappar, välja mellan ikoner, etc. Så det är mycket viktigt att noga tänka igenom vad du vill göra, hur du vill att användaren ska bete sig, och hur arbetsflödet i din aktion kommer att se ut.

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.

Det finns några koncept man bör känna till när man designar ett gränssnitt:

  • Modal/non-modal dialogs: En modal dialog kommer fram längst fram på skärmen, stoppar aktionen i huvudfönstret, och tvingar användare att svara på dialogen, emedan en icke-modal dialog inte stoppar dig från att arbeta med huvudfönstret. I en del fall så är det första bättre, i andra fall inte.
  • Identifiera vad som krävs och vad som är valbart: Försäkra dig om att användaren vet vad den måste göra. Etikettera allting med en riktig beskrivning, använd verktygstips, etc.
  • Separera kommandon från parametrar: Detta görs vanligtvis med knappar och textinmatningsfält. Användaren vet att om en knapp klickas så produceras en aktion emedan ändring av ett värde inuti ett textfält kommer att ändra en parameter någonstans. Nuförtidan så vet de flesta användarna vad en kanpp är, vad ett inmatningsfält är, etc. Det gränssnitts verktygskit vi använder, Qt, är en av de bästa verktygskiten, och vi behöver inte bry oss om så mycket om hur man klargör saker, eftersom de redan är mycket tydliga.

Så, nu när vi har definierat vad vi ska göra, så är det dags att öppna qt designer. Låt oss designa en mycket enkel dialog, som den här:

Vi kommer sedan använda denna dialog i FreeCAD till att producera ett fint rektangulärt plan. Du kanske tycker att det inte är så användbart att producera fina rektangulära plan, men det kommer vara lätt att senare ändra den till att göra mer komplexa saker. När du öppnar det, så ser Qt Designer ut så här:

Det är mycket enkelt att använda. I den vänstra lådan har du element som kan dras till din widget. på den högra sidan har du egenskapspanelerna som visar alla möjliga redigerbara egenskaper på de valda elementen. Så, börja med att skapa en ny widget. Välj "Dialog without buttons", eftersom vi inte vill ha standard Ok/Cancel knappar. Dra sedan3 labels, på din widget, en för titeln, en för att skriva "Höjd" och en för att skriva "Bredd". Labels är enkla texter som syns på din widget, bara för att informera användaren. Om du väljer en label, så kommer det fram flera egenskaper på den högra sidan som du kan ändra om du vill, som teckensnitt, höjd, etc.

Notera att jag här valde mycket enkla kontroller, men Qt har många fler alternativ, du kan till exempel använda Spinboxes istället för LineEdits, etc... Ta en titt på vad som finns tillgängligt, du kommer säkert att få andra ideer.

Det är ungefär allt vi behöver göra i Qt Designer. En sista sak bara, låt oss döpa om alla våra element till lättare namn, så blir det lättare att identifiera dem i våra skript:

Konvertera vår dialog till python

Låt oss nu spara vår widget någonstans. Den kommar att sparas som en .ui fil, som vi smidigt kan omvandla till python skript med pyuic. på windows, så är pyuic programmet hoppackat med pyqt (ska verifieras), på linux behöver du troligen installera den separat från din pakethanterare (på debian-baserade system, så är det en del av pyqt4-dev-tools paketet). För att göra konverteringen, så behöver du öppna ett terminalfönster (eller ett kommandoprompt fönster på windows), navigera till där du sparade din .ui file, och skriva:

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

På en del system så kallas programmet pyuic4 istället för pyuic. Detta kommer att konvertera .ui filen till ett python skript. Om vi öppnar mywidget.py filen, så är dess innehåll mycket lätt att förstå:

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

Som du ser så har det en mycket enkel struktur: En klass benämnd Ui_Dialog skapas, som sparar din widgets gränssnittselement. Den klassen har två metoder, en fär att ställa in widgeten, och en för att översätta dess innehåll, som är en del av de allmäna Qt mekanismerna för översättning av gränssnittselement. Inställningsmetoden skapar, en och en, widgetarna som vi har definierat dem i Qt Designer, och sätter deras alternativ som vi bestämt tidigare. Sedan blir hela gränssnittet översatt, och slutligen, blir sloten anslutna (vi pratar om det senare).

Vi kan nu skapa en ny widget, och använda denna klass till att skapa dess gränssnitt. Vi kan redan se vår widget i aktion, genom att sätta vår mywidget.py fil på en plats där FreeCAD kommer att hitta den (i FreeCAD's bin katalog, eller i någon av underkatalogerna till Mod ), och i FreeCAD pythontolken skriva:

from PySide import QtGui
import mywidget
d = QtGui.QWidget()
d.ui = mywidget.Ui_Dialog()
d.ui.setupUi(d)
d.show()

Och vår dialog kommer fram! Notera att din pythontolk fortfarande fungerar, vi har en icke-modal dialog. Så, för att stänga den, så kan vi (förutom att klicka på dess stängningsikon, förstås) skriva:

d.hide()

Ordna så att vår dialog gör något

Nu när vi kan visa och gömma vår dialog, så behöver vi bara lägga till en sista bit: Att låta den göra något! Om du leker lite med Qt designer, så kommer du snabbt upptäcka ett helt avsnitt som kallas "signals and slots". I grunden så fungerar det så här: element på dina widgetar (i Qt terminologi, så är dessa element widgetar själva) kan sända signaler. Dessa signaler skiljer sig beroende på widget typ. Till exempel, en knapp kan sända en signal när den är nedtryckt och när den släpps. Dessa signaler kan anslutas till slots, vilka kan vara en speciell funktionalitet i andra widgetar (till exempel en dialog har en "stäng" slot till vilken du kan ansluta signalen från en stäng knapp), eller kan vara anpassade funktioner. PyQt Referensdokumentation listar alla qt widgetar, vad de kan göra, vilka signaler de kan sända , etc...

Vad vi kommer att göra här, är att skapa en ny funktion som kommer att skapa ett plan, baserat på höjd och bredd, och ansluta denna funktion till nedtryckt signalen som sänds av vår "Skapa!" button. Så, låt os börja med att importera våra FreeCAD moduler, genom att sätta följande rader i toppen på skriptet, där vi redan har importerat QtCore och QtGui:

import FreeCAD, Part

Låt oss sedan lägga till en ny funktion till vår Ui_Dialog klass:

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()

Sedan behöver vi informera Qt att ansluta knappen till funktionen, genom att placera följande rad precis innan QtCore.QMetaObject.connectSlotsByName(Dialog):

QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)

Detta ansluter, som du ser, pressed() signalen från vårt skapade objekt ("Skapa!" knappen), till en slot benämnd createPlane, som vi just definierade. Klart! Nu, som en slutlig justering, så kan vi lägga till lite funktion för att skapa dialogen, så kommer den bli lättare att anropa. Utanför Ui_Dialog klassan, så lägger vi till denna kod:

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!)

Det enda vi sedan behöver göra från FreeCAD är:

import mywidget
myDialog = mywidget.plane()

Det var allt. Nu kan du försöka andra saker, som till exempel sätta in din widget i FreeCAD's gränssnitt (se kodbitar sidan), eller göra mycket mer avancerade verktyg, genom att använda andra element på din widget.

Det kompletta skriptet

För referens, så är det kompletta skriptet här:

# 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/sv
Licence/sv


Utveckla applikationer för FreeCAD


Använda licenser

Här är de tre licenserna under vilka FreeCAD är publicerad:

FreeCAD uses two different licenses, one for the application itself, and one for the documentation:

GPL
För Python sripten för att bygga binärfilerna som uttalat i .py filerna i src/Tools
LGPL
För kärnbiblioteken som uttalat i .h och .cpp filerna i src/App src/Gui src/Base och de flesta modulerna i src/Mod och för de körbara som uttalat i .h och .cpp filerna i src/main
Open Publication Licence
För dokumentationen på http://free-cad.sourceforge.net/ om inget annat markerats av författaren

Creative Commons Attribution 3.0 License (CC-BY-3.0) For the documentation and the website.

Se FreeCAD's debian copyright file för mer detaljer om de licenser som används i FreeCAD

Licensernas inverkan

Below is a friendlier explanation of what the LGPL license means for you:

All users

Privata användare

Privata användare kan använda FreeCAD utan avgift och kan göra ungefär vad de vill med den....

Professional users

Professionella användare

Kan använda FreeCAD fritt, för alla sorters privata eller professionella arbeten. De kan anpassa applikationen som de önskar. De kan skriva öppen eller sluten källkodsextensioner till FreeCAD. De är alltid herrar över deras data, de är inte tvingade att uppdatera FreeCAD, ändra deras bruk av FreeCAD. Att använda FreeCAD binder dem inte till några kontrakt eller krav.

Open-source software developers

Öppen källkodsutvecklare

Kan använda FreeCAD som grundplattform för egna extensionsmoduler för speciella ändamål. De kan välja antingen GPL eller LGPL för att tillåta bruk av deras arbete i proprietär mjukvara, eller inte.

Closed-source software developers

Professionella utvecklare

Professionella utvecklare Kan använda FreeCAD som grundplattform för egna extensionsmoduler för speciella ändamål och är inte tvingade att göra sina moduler till öppen källkod. De kan använda alla moduler som använder LGPL. De är tillåtna att distribuera FreeCAD tillsammans med deras proprietära mjukvara. De kommer få support av författarna så länge som den inte är enkelriktad. Om du vill sälja din modul så behöver du en Coin3D licens, annars är du tvingad av detta bibliotek att göra den till öppen källkod.

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

Uttalande från underhållaren

Jag vet att diskussionen om "rätt" licens för öppen källkod tar upp en signifikant del av internetbandbredden, så här är skälen till varför, enligt min åsikt, FreeCAD ska ha denna.

Jag valde LGPL och GPL för projektet och jag vet för- och nackdelarna med LGPL och vill ge dig några skäl till det beslutet.

FreeCAD är en blandning av bibliotek och en applikation, så GPL skulle vara lite för starkt för det. Det skulle förhindra skapande av kommersiella moduler för FreeCAD därför att det skulle förhindra länkning med FreeCAD's basbibliotek. Du kanske frågar dig: varför kommersiella moduler överhuvudtaget? Därför är Linux ett bra exempel. Skulle Linux vara så framgångsrikt om GNU C Biblioteket skulle vara GPL och därför förhindra länkning mot icke-GPL applikationer? Och fastän jag älskar friheten i Linux, så vill jag också kunna använda den mycket bra NVIDIA 3D grafikdrivrutinen. Jag förstår och accepterar anledningen till att NVIDIA inte vill ge bort drivrutinskod. Vi jobbar alla för företag och behöver lön eller åtninstone mat. Så för mig är en samexistens av öppen källkod och sluten källkodsmjukvara inte något dåligt, när det följer reglerna i LGPL. Jag skulle vilja se någon som skriver en Catia import/export processor för FreeCAD och distribuerar den gratis eller för lite pengar. Jag tycker inte om att tvinga honom att ge bort mer än han vill. Det skulle inte vara bra varken för honom eller FreeCAD.

Detta beslut är ändå bara gjort för FreeCAD's kärnsystem. Var och en som skriver en applikationsmodul kan ta sina egna beslut.

Jürgen Riegel

—15 October 2006


Dialog creation/sv
Tracker/sv


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.

Rapportera buggar

Om du tror att du funnit en bugg, så är du välkommen att rapportera den där. Men innan du rapporterar en bugg, kontrollera följande punkter:

  • Försäkra dig om att din bugg verkligen är en bugg, vilket är något som ska fungera men inte fungerar. Om du inte är säker, tveka inte att förklara ditt problem på forumet och fråga vad du ska göra.
  • Innan du skickar något, läs ofta ställda frågor, gör en sökning på forumet, och försäkra dig om att buggen inte har rapporterats innan , genom att söka i bug trackern.
  • Beskriv problemet så klart och noggrant som möjkligt, och hur det kan reproduceras. Om vi inte kan verifiera buggen, så kanske vi inte kan fixa den.
  • Skicka med följande information: Ditt operativsystem, om det är 32 eller 64 bitars, och vilken FreeCAD version du kör.
  • Var snäll och posta en separat rapport för varje bugg.
  • Om du är på ett linuxsystem och din bugg orsakar en krasch i FreeCAD, så kan du försöka köra en debug backtrace: Från en terminal så kör du gdb freecad (med antagandet att paketet gdb är installerat), sedan, inuti gdb, skriv run . FreeCAD kommer att starta. Efter att kraschen har uppstått , skriv bt , för att få hela backtracen. Inkludera denna backtrace i din buggrapport.

Begära funktioner

Om du vill ha något i FreeCAD som inte finns ännu, så är detta inte en bugg utan en funktionsbegäran. Du kan också skicka den på samma tracker (posta den som en funktionsbegäran istället för bugg), men tänk på att det finns inga garantier att din önskan blir uppfylld.

  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

Skicka patchar

Om du har programmerat en buggfix, en extension eller något annat som kan vara allmänt gångbart i FreeCAD, skapa en patch genom att använda Subversion's diff verktyg och posta den på samma tracker (posta den som en patch).

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



This page explains step by step how to compile FreeCAD 0.19 or newer on Windows using Microsoft's MSVC compiler. For information on using MSYS2/MinGW see Compile on MinGW. For other platforms see Compiling.

Prerequisites

Compiling FreeCAD on Windows requires several tools and libraries.

Required

  • A compiler. FreeCAD is tested with Visual Studio (MSVC)—other compilers may work, but instructions for use are not included here. Fore more details, see the section Compiler below.
  • Git (There are also GUI frontends available for Git, see the next section.)
  • 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.

Optional programs

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

Source code

Now you can get the source code of FreeCAD:

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

Using the command line

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

Compiler

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.

Optional system path configuration

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.

Configuration

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.

Options for the build process

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

Building 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


CompileOnUnix/sv


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.


Overview

Översikt

Detta är bibliotek som inte har förändrats i FreeCAD projektet. De används som de är som ett dynamiskt länkbibliotek (*.so or *.dll). Om en ändring är nödvändig eller om en wrapper klass behövs, så måste wrapperns kod eller den förändrade bibliotekskoden flyttas till FreeCADs baspaket.

De använda biblioteken är:

The dependencies need to be installed in the system before proceeding with compilation; see compile on Linux, compile on Windows, and compile on MacOS for more information.

Överväg att använda LibPack istället för att ladda ned och installera alla saker själv.

Länkar

Länktabell
Biblioteksnamn Nödvändig version Länk till den
Python >= 2.5.x http://www.python.org/
OpenCasCade >= 5.2 http://www.opencascade.org
Qt >= 4.1.x http://www.qtsoftware.com
Coin3D >= 2.x http://www.coin3d.org
ODE >= 0.10.x http://www.ode.org
SoQt >= 1.2 http://www.coin3d.org
Xerces-C++ >= 2.7.x < 3.0 http://xml.apache.org/xerces-c/
GTS >= 0.7.x http://gts.sourceforge.net/
Zlib >= 1.x.x http://www.zlib.net/
Boost >= 1.33.x http://www.boost.org/
Eigen3 >= 3.0.1 http://eigen.tuxfamily.org/index.php?title=Main_Page

Detaljer

Python

Python

Version: 2.5 eller högre

License: Python 2.5 licens

Python 2 became obsolete in 2019. Further development of FreeCAD will use exclusively Python 3; compatibility with Python 2 won't be tested, so old workbenches and macros that use this version will have to be updated or they may stop working. Please post on the FreeCAD forum if you encounter problems with Python 3.

Python is a popular all-purpose scripting language that is widely used in Linux and open source software. In FreeCAD, Python is used during compilation and also at runtime in different ways. It is used

  • to write test scripts to test for different conditions, such as memory leaks, to ensure functionality of the software after changes, for post build checks, and test coverage tests,
  • to write macros and macro recording,
  • to implement application logic for standard packages,
  • to implement auxiliary tools such as the Addon Manager,
  • to implement entire workbenches like Draft and Arch,
  • to dynamically load packages,
  • to implement rules for design (knowledge engineering),
  • to do fancy Internet interactions like work groups and PDM

Du kan använda käll- eller binärkod från http://www.python.org/ eller alternativt använda ActiveState Python från http://www.activestate.com/ fast det kan vara svårt att få avbuggningsbiblioteken från ActiveState.

Python was chosen as the scripting language for FreeCAD for different reasons:

  • It is more object oriented than Perl and Tcl.
  • The code is more readable than Perl and Visual Basic.
  • It is easier to embed in another application, unlike, say, Java.

In summary, Python is well documented, and it's easy to embed and extend in a C++ application. It is also well tested and has strong support from the open source community. Read more about Python and browse the official documentation at Python.org.

Boost

Version: 1.33.x

Licens: Boost Software License - Version 1.0

Boost C++ biblioteken är en samling av granskade, öppen källkodsbibliotek som utökar C++ funktionalitet. Biblioteken är licensierade under Boost Software License, som är anpassad för att Boost ska tillåtas att användas med både sluten och öppen källkodsprojekt. Många av Boosts grundare är med i C++ standardkommiten och flera Boost bibliotek har accepterats for integrering i Teknisk Rapport 1 av C++0x.

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.

För att försäkra effektivitet och flexibilitet, så använder Boost en hel del mallar. Boost har varit en källa för extensivt arbete och forskning i allmän programmering och meta-programmering i C++.

OpenCasCade

Version: 5.2 eller högre

Licens: OCTPL

OCC är en fullödig CAD Kärna. Från början utvecklades den av Matra Datavision i Frankrike för Strim (Styler) och Euclid Quantum applikationerna och ändrades senare till öppen källkod. Det är verkligen ett stort bibliotek, och gör en fri cad applikation möjlig, genom att erbjuda några paket som skulle vara svåra eller omöjliga att implementera i ett öppen källkodsprojekt:

  • En komplett STEP kompliant geometrikärna
  • En topologisk datamodell och alla nödvändiga funktioner att arbeta med (klipp, förena, extrudera, och så vidare. . . )
  • Standard Import- / Export processorer som STEP, IGES, VRML
  • 3D och 2D visare med markeringssupport
  • En dokument och projektdatastruktur med support för spara och återställa, extern länkning av dokument, omberäkning av designhistoria (parametrisk modellering) och en facilitet för att ladda nya datatyper dynamiskt som ett utökningspaket

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.

För att lära dig mer om OpenCasCade, ta en titt på OpenCasCade sidan eller http://www.opencascade.org.

Qt

Version: 4.1.x eller högre

Licens: GPL v2.0/v3.0 eller Kommersiell (från version 4.5 och framåt även v2.1)

Jag tror inte jag behöver berätta så mycket om Qt. Det är en av de mest använda verktygsseten för grafiskt gränssnitt i öppen källkodsprojekt. För mig är den viktigaste anledningen att använda Qt är Designer och möjligheten att ladda hela dialogrutor som en (XML) resurs och integrera specialiserade widgets. I en CAX applikation så är användarinteraktionen och dialogrutorna den absolut största delen av koden och för en bra dialogkonstruktör är dett mycket viktigt att lätt kunna utöka FreeCAD med ny funktionalitet. Ytterligare information och en mycket bra online dokumentation hittar du på http://www.qtsoftware.com.

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

Version: 2.0 eller högre

Licens: GPL v2.0 eller Kommersiell

Coin är ett högnivå 3D grafikbibliotek med ett C++ Applikationsprogrammeringsgränssnitt. Coin använder scengraf datastrukturer för att rendera realtidsgrafik som passar för de flesta vetenskapliga och konstruktions visualiserings applikationer.

Coin är byggt på industristandard OpenGL direktrenderingsbiblioteket, och adderar abstraktioner för högnivåprimitiver, erbjuder 3D interaktivitet, ökar bekvämligheten och produktiviteten för programmeraren, och innehåller många komplexa optimeringsfunktioner för snabb rendering som är transparent för programmeraren.

Coin är baserat på SGI Open Inventor API. Open Inventor, för de som inte vet vad det är, har sedan länge varit de facto standard grafikbibliotek för 3D visualisering och visuell simuleringsmjukvara i vetenskapliga och konstruktörssammanhang. Det har bevisat sitt värde i mer än 10 år, dess mogenhet bidrar till dess framgång som ett huvudsakligt byggblock i tusentals storskaliga ingenjörsapplikationer världen runt.

Vi kommer att använda OpenInventor som 3D visare i FreeCAD eftersom OpenCasCade visaren (AIS och Graphics3D) har allvarliga begränsningar och prestandaflaskhalsar, speciellt när det gäller storskalig konstruktionsrendering. Andra saker som texturer eller volymetrisk rendering är inte väl stödda, och så vidare ....

Coin kan portas över många plattformar: alla UNIX / Linux / *BSD plattformar, alla Microsoft Windows operativsystem, och Mac OS X.

SoQt

Version: 1.2.0 eller högre

Licens: GPL v2.0 eller Kommersiell

SoQt är Inventor bindningen till Qt gränssnittsverktygsset. Olyckligtvis så är det inte längre LGPL så vi måste ta bort det från FreeCADs kodbas och länka den som ett bibliotek. Den har samma licensmodell som Coin. Och du måste kompilera den med din Qt version.

SoQt is no longer used in FreeCAD, it was replaced by Quarter which is a more recent Qt binding.

Quarter

Version: 1.0 or higher

License: BSD 3-clause license

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

Version: 0.6.3 or higher

License: BSD 3-clause license

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

Version: 3.11 or higher

License: BSD 3-clause license

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

Version: 2.7.0 eller högre

Licens: Apache Software License Version 2.0

Xerces-C++ är en validerande XML läsare som är skriven i C++ portabla delset. Xerces-C++ gör det lätt att ge din applikation möjligheten att läsa och skriva XML data. Ett delat bibliotek erbjuds för läsning, generering, manipulering, och validering av XML dokument.

Läsaren används för att spara och återkalla parametrar i FreeCAD.

Eigen3

Version: 3.0 or higher

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

Version: 0.1.5 or higher

License: GNU Lesser General Public License 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

Version: 1.x.x

Licens: zlib Licens

zlib är designat att vara ett fritt, allmänt, juridiskt obegränsat -- vilket innebär, ej begränsat av några patent -- förlustfritt datakompressionsbibliotek som kan användas på i stort sett all datorhårdvara och operativsystem. zlib dataformat är i sig själv portabelt över olika plattformar. Till skillnad från kompressionsmetoden LZW som används i Unix compress(1) och i bildformatet GIF, så expanderar aldrig den kompressionsmetod som för närvarande används i zlib datan. (LZW kan dubblera eller tredubbla filstorleken i extrema fall.) zlib's storlek i minnet är också oberoende av inmatningsdatan och kan om nödvändigt reduceras, till en kostnad av kompressionsgrad.

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

License: BSD 3-clause license

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 CAM Workbench, so it is compiled together with it.

LibPack

LibPack

LibPack är ett smidigt paket med alla ovanstående bibliotek ihoppackade. Det är för närvarande tillgängligt för

Windows plattformen på Nedladdningssidan! Om du arbetar under Linux så behöver du inte LibPack, istället ska du använda paketförråden för din Linux distribution.

If you're working under Linux, you don't need the LibPack, as you can get the dependencies from your distribution's repositories as mentioned in the compile on Linux page.

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



Tool Page

Verktygssida

För allt seriös mjukvaruutveckling så behöver du verktyg. Här är en lista på verktyg som vi använder för att utveckla FreeCAD:

Platform independent tools

Qt-Toolkit

Plattformsoberoende verktyg

Qt-Toolkit

Qt-toolkit är en fantastisk, plattformsoberoende designverktyg för att skapa gränssnitt. den finns i FreeCAD's LibPack, men kan också laddas ned på Qt project.

Inkscape

InkScape

Bra vektorritningsprogram. Följer SVG standarden och används till att rita ikoner och bilder. Hämta det på www.inkscape.org.

Doxygen

Doxygen

Ett mycket bra och stabilt verktyg för att generera källdokumentation från .h och .cpp filerna.

Gimp

The Gimp

Inte mycket att säga om Gnu Image Manipulation Program. Förutom att det kan hantera .xpm filer vilket är en mycket smidigt sätt att hantera Ikoner i QT Program. XPM är egentligen C-kod som kan kompileras in i ett program.

Hämta GIMP här: 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

Free and open source software for video recording and live streaming. More details on official website: obsproject.com

OpenCamLib

OpenCamLib (OCL) is an open source library aiming to provide computer aided manufacturing (CAM) algorithms. FreeCAD uses OCL in the experimental 3D surface path operations and other experimental features.

StarUML

StarUML

Ett helt öppen källkod UML program. Det har många funktioner från de stora, inkluvive reverse engineering C++ källkod....

Ladda ned här: staruml.sourceforge.net

Verktyg på Windows

Visual Studio Community

Visual Studio 8 Express

Fastän VC8 är för C++ utveckling, så är det inte något stort steg från VisualStudio 6 (enligt min åsikt ett stort steg bakåt), det är ett fritt utvecklingssystem på Windows. För nativa Win32 applikationer såbehöver du ladda ned PlatformSDK från M$.

Så Express varianten är svår att hitta. Men du kan försöka med denna länk

CamStudio

CamStudio

Är ett öppen källkodsverktyg för att spela in skärmfilmer (Webfilmer). Det är ett mycket bra verktyg för att skapa övningar genom att spela in dem. Det är inte alls så tråkigt som att skriva dokumentation.

Se camstudio.org för detaljer.

Verktyg på Linux

ATTGÖRA


Third Party Libraries/sv
Start up and Configuration/sv


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

Denna sida visar olika sätt att starta FreeCAD och de viktigaste konfigurationsegenskaperna.

Starta FreeCAD från Kommandoraden

FreeCAD kan startas normalt, genom att dubbelklicka på dess skrivbordsikon eller genom att välja den från startmenyn, men det kan också startas direkt från kommandoraden. Detta tillåter dig att ändra några av standard uppstartsalternativen.

Using command line options without a command line shell

  • On Ubuntu you can create a desktop icon and edit its properties. Add the command line options separated by spaces behind the program name in the "Command" field.
  • On Windows create a shortcut and edit the properties. Add the command line options separated by spaces to "Target" field.

Kommandoradsalternativ

Kommandoradsalternativen förändras ofta, så därför är det en bra ide att kontrollera alternativen genom att skriva:

FreeCAD --help

Från svaret kan du läsa de möjliga parametrarna:

 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.

Respons och konfigurationsfiler

FreeCAD kan läsa en del av dessa alternativ från en konfigurationsfil. Denna fil måste ligga i bin sökvägen och måste ha namnet FreeCAD.cfg. Tänk på att alternativ som specificeras på kommandoraden har högre prioritet än konfigurationsfilen!

En del operativsystem har en låg gräns på kommandoradens längd. Det vanliga sättet att komma runt dessa begränsningar är att använda responsfiler. En responsfil är bara en konfigurationsfil som använder samma syntax som kommandoraden. Om kommandoraden specificerar namnet på den responsfil som ska användas, så laddas den och läses i tillägg till kommandoraden:

FreeCAD @ResponseFile.txt 

eller:

FreeCAD --response-file=ResponseFile.txt

or:

FreeCAD --response-file ResponseFile.txt

Gömda alternativ

Det finns en del alternativ som inte visas för användaren. Dessa alternativ är egentligen X-fönsterparametrar som läses av fönstersystemet:

  • -display display, väljer X skärmen (standard är $DISPLAY).
  • -geometry geometry, väljer klientgeometrin för det första fönstret som visas.
  • -fn or -font font, definierar applikationens typsnitt. Typsnittet ska specificeras med en X logisk typsnittsbeskrivning.
  • -bg or -background color, väljer standard bakgrundsfärg och en applikationspalett (ljusa och mörka skuggor beräknas).
  • -fg or -foreground color, väljer standard förgrundsfärg.
  • -btn or -button color, väljer standard knappfärg.
  • -name name, väljer applikationsnamnet.
  • -title title, väljer applikationstiteln.
  • -visual TrueColor, tvingar applikationen att använda TrueColor på en 8-bits skärm.
  • -ncols count, Begränsar antalet färger som allokeras i färgkuben på en 8-bitars skärm, om applikationen använder QApplication::ManyColor färgspecifikationen. Om antalet är 216 så används en 6x6x6 färgkub (d.v.s. 6 nivåer på rött, 6 på grönt, och 6 på blått); för andra värden, så används en kub som är ungefärligt proportionell till en 2x3x1 kub.
  • -cmap, får applikationen att installera en privat färgkarta på en 8-bitars skärm.

Köra FreeCAD utan användargränssnitt

FreeCAD startar normalt i gränssnittsläge, men du kan också tvinga det att starta i konsolläge genom att skriva:

FreeCAD --console

på kommandoraden. I konsolläge, så kommer inget användargränssnitt att visas, och du kommer att presenteras med en pythontolks prompt. Från den pythonprompten så har du samma funktionalitet som den pythontolk som körs inuti FreeCAD gränssnittet, med normal åtkomst till alla FreeCADs moduler och plugin, förutom FreeCADGui modulen. Tänk på att moduler som beror på FreeCADGui kanske inte heller finns tillgängliga.

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

En del bibliotek behöver anropa systemmiljövariabler. ibland när det är ett problem med en FreeCAD installation, så beror det på att en del miljövariabler saknas eller är felinställda. Därför dupliceras några viktiga variabler i Konfigurationen och sparas i loggfilen.

Python relaterade miljövariabler:

  • PYTHONPATH
  • PYTHONHOME
  • TCL_LIBRARY
  • TCLLIBPATH

OpenCascade relaterade miljövariabler:

  • CSF_MDTVFontDirectory
  • CSF_MDTVTexturesDirectory
  • CSF_UnitsDefinition
  • CSF_UnitsLexicon
  • CSF_StandardDefaults
  • CSF_PluginDefaults
  • CSF_LANGUAGE
  • CSF_SHMessage
  • CSF_XCAFDefaults
  • CSF_GraphicShr
  • CSF_IGESDefaults
  • CSF_STEPDefaults

Konfigurationssetet

Vid varje uppstart så undersöker FreeCAD sin omgivning och kommandoradsparametrarna. Det bygger upp ett configuration set vilket innehåller den huvudsakliga körinformationen. Denna information används senare för att avgöra vilken plats som användardata eller loggfiler ska sparas. Det är också mycket viktigt för postmortem analyser. Därför så sparas det i loggfilen.

Användarrelaterad information

Användarkonfiguration
Konfig. var. namn Förklaring Exempel M$ Exempel Posix (Linux)
UserAppData Sökväg där FreeCAD lagrar användarrelaterad applikationsdata. C:\Documents and Settings\username\Application Data\FreeCAD /home/username/.FreeCAD
UserParameter Fil där FreeCAD lagrar användarrelaterad applikationsdata. C:\Documents and Settings\username\Application Data\FreeCAD\user.cfg /home/username/.FreeCAD/user.cfg
SystemParameter Fil där FreeCAD lagrar applikationsrelaterad data. C:\Documents and Settings\username\Application Data\FreeCAD\system.cfg /home/username/.FreeCAD/system.cfg
UserHomePath Nuvarande användares sökväg till hem mappen 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.

Kommandoradsargument

Användarkonfiguration
Konfig. var. namn Förklaring Exempel
LoggingFile 1 om loggningen är påslagen 1
LoggingFileName Filnamn där loggen sparas C:\Documents and Settings\username\Application Data\FreeCAD\FreeCAD.log
RunMode Detta indikerar hur huvudslingan kommer att fungera. "Script" innebär att det givna skriptet anropas och avslutas efter det. "Cmd" kör kommandotolken. "Internal" kör ett internt skript. "Gui" startar händelseslingan för gränssnittet. "Module" laddar en given python modul. "Cmd"
FileName Innebörd beror på RunMode
ScriptFileName Innebörd beror på RunMode
Verbose FreeCADs pratighet, d.v.s. hur mycket som loggas "" eller "strict"
OpenFileCount Innehåller antalet filer som öppnas genom kommandoradsargument "12"
AdditionalModulePaths Innehåller sökvägen för de extramoduler som ges i kommandoraden "extraModules/"

Systemrelaterat

Användarkonfiguration
Konfig. var. namn Förklaring Exempel M$ Exempel Posix (Linux)
AppHomePath Sökväg där FreeCAD är installerat c:/Progam Files/FreeCAD_0.7 /user/local/FreeCAD_0.7
PythonSearchPath Innehåller en lista på sökvägar där python söker efter moduler. Detta är vid uppstart och kan ändras under körning

Bygga relaterad information

Tabellen nedan visar tillgänglig information om Byggversionen. Det flesta av dem kommer från Subversion förrådet. dessa saker behövs för att exakt återuppbygga en version!

Användarkonfiguration
Konfig. var. namn Förklaring Exempel
BuildVersionMajor Byggningens Major Versionsnummer. Definierad i src/Build/Version.h.in 0
BuildVersionMinor Byggningens Minor Versionsnummer. Definierad i src/Build/Version.h.in 7
BuildRevision Källkodens SVN Repository Revisionnummer i byggningen. Genererad av SVN 356
BuildRevisionRange Område för olika ändringar 123-356
BuildRepositoryURL URL adress för förråd https://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk/src
BuildRevisionDate Datum av ovanstående Revision 2007/02/03 22:21:18
BuildScrClean Indikerar om källkoden har ändrats efter kontroll Källkod ändrad
BuildScrMixed Källkod inte blandad

Märkningsrelaterat

Dessa konfigurationspunkter är relaterade till FreeCADs märkningsmekanism. Se Branding/sv för mer detaljer.

Användarkonfiguration
Konfig. var. namn Förklaring Exempel
ExeName Namn på den byggda körfilen. Kan skilja sig från FreeCAD om en annan main.cpp används. FreeCAD.exe
ExeVersion Allmän version som visas vid uppstart V0.7
AppIcon Ikon som används för körfilen, visas i Applikationens huvudfönster. "FCIcon"
ConsoleBanner Den banner som visas i konsolläge
SplashPicture Namn på den ikon som används till uppstartsskärmen "FreeCADSplasher"
SplashAlignment Textjustering i uppstartsdialogen Left"
SplashTextColor Textfärg i uppstartsfönstret "#000000"
StartWorkbench Namn på den arbetsbänk som ska startas automatiskt efter uppstart "Part design"
HiddenDockWindow Lista på dockningsfönster (separerade av semikolon) som kommer att inaktiveras "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/sv
FreeCAD Build Tool/sv


FreeCAD byggverktyg eller fcbt är ett pythonskript placerat i

trunc/src/Tools/fcbt.py

Det kan användas till att förenkla en del frekventa uppgifter vid byggande, distribution och utökning av FreeCAD.

Bruk

Med [Python] korrekt installerat, så kan fcbt startas med kommandot

python fbct.py

det visar en meny, där du kan välja den uppgift som du vill använda den till:

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

Mata vid inmatningsprompten in det förkortade kommandot som du vill använda. Skriv till exempel "CM" för Skapa en modul.

DistSrc

Kommandot "DS" skapar en källdistribution från det gällande källträdet.

DistBin

Kommandot "DB" skapar en binär distribution från det gällande källträdet.

DistSetup

Kommandot "DI" skapar en setup distribution från det gällande källträdet.

DistSetup

Kommandot "DUI" skapar en användar setup distribution från det gällande källträdet.

DistAll

Kommandot "DA" utför "DS", "DB" och "DI" i sekvens.

NextBuildNumber

Kommandot "NBN" ökar byggnumret för att skapa en ny släppversion av FreeCAD.

CreateModule

Kommandot "CM" skapar en ny applikationsmodul.


Start up and Configuration/sv
Module Creation/sv


<translate>

</translate>

<translate>

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:

</translate>

/Mod/
 +-- MyWorkbench/
     +-- Init.py
     +-- InitGui.py

<translate>

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:

</translate>

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();
    }
}

<translate>

The Init.py file

</translate>

"""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 LICENSE 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!")

<translate>

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

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:

</translate>

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())

<translate>

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:

</translate>

workbenches=
pylibs=
optionalpylibs=

<translate>

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:

</translate>

workbenches=FEM,Curves
pylibs=ezdxf
optionalpylibs=metadata,git

<translate>

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:

</translate>

import MyModuleGui

<translate>

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:

</translate>

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;
    };
}

<translate>

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

</translate>

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())

<translate>

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:

</translate>

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());
}

<translate>

"Compiling" your resource file

compileA2pResources.py from the A2Plus workbench:

</translate>

#!/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 LICENSE 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)

<translate>

Related


</translate>


Testa först

Innan du går igenom avbuggningssmärtan, använd testramverket för att kontrollera om standardtesterna fungerar korrekt. Om inte så kanske det kan bero på en trasig installation.

Before you go through the pain of debugging use the Test framework to check if the standard tests work properly. If they do not run complete there is possibly a broken installation.

kommandorad

Avbuggningen av FreeCAD stöds av en del interna mekanismer. Kommandoradsversionen av FreeCAD erbjuder alternativ för avbuggningsstöd:

-v
Med "v" alternativet så ger FreeCAD en mer pratig utmatning.
-l
Med "l" alternativet så skriver FreeCAD extra information till en loggfil.

The debugging of FreeCAD is supported by a few internal mechanisms. The command line version of FreeCAD provides some options for debugging support.

These are the currently recognized options in FreeCAD 0.19:

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/.local/share/FreeCAD/FreeCAD.log (Linux)
                           $HOME/Library/Application\ Support/FreeCAD/FreeCAD.log (macOS)
                           %APPDATA%\FreeCAD\FreeCAD.log (Windows)
 --log-file arg            Unlike to --write-log this allows to log 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

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.

For Linux

Linux Debugging →

Prerequisites:

  • software package gdb installed
  • a debug build of FreeCAD (at this time only available by building from source)
  • a FreeCAD model that causes a crash

Steps: Enter the following in your terminal window:

Find FreeCAD binary on your system:

$ whereis freecad
freecad: /usr/local/freecad <--- for example

$ cd /usr/local/freecad/bin
$ gdb FreeCAD

GNUdebugger will output some initializing information. The (gdb) shows GNUDebugger is running in the terminal, now input:

(gdb) handle SIG33 noprint nostop
(gdb) run

FreeCAD will now start up. Perform the steps that cause FreeCAD to crash or freeze, then enter in the terminal window:

(gdb) 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.

(gdb) bt full

Print the values of the local variables also. This can be combined with a number to limit the number of frames shown.

For macOS

macOS Debugging →

Prerequisites:

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


Module Creation/sv
Testing/sv


Test workbench icon

Introduction

This is the list of test apps as of 0.15 Git 4207:

FreeCAD kommer med ett extensivt testramverk. Testerna baseras på ett set med Pythonskript som finns i testmodulen.

You can run the tests from the command line, by using the -t or --run-test options.

Run all tests:

freecad --run-test 0

Run only some the specified unit test, for example:

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

Test menu

Each top level directory in FreeCAD should have a file with the tests that can be run for that particular workbench or module. The file usually starts with the word Test.

To run a test from within FreeCAD, switch to the Test Workbench, then Test commands → TestToolsGui → Self test → Select test name, then enter the name of the Python file with the tests; for example, for the Draft Workbench, this would be TestDraft, then press Start.

Test functions

This is the list of test apps as of 0.15 git 4207:

TestAPP.All

Add test function

Add test function

BaseTests

Add test function

UnitTests

Add test function

Document

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

TestCAMApp

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:

Workbench

Add test function

Menu

Add test function

Menu.MenuDeleteCases

Add test function

Menu.MenuCreateCases

Add test function

Scripting

See also: FreeCAD Scripting Basics.

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)

Example 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)

Additional Resources

Forum Topics


Debugging/sv
Branding/sv


Overview

Denna artikel diskuterar Branding av FreeCAD. Branding innebär att du gör din egen applikation med FreeCAD som bas. Det kan sträcka sig från att bara ha en egen startfil eller uppstartsbild till ett helt och hållet omarbetat program. På basis FreeCAD's flexibla arkitektur så är det lätt att använda den som bas för dina egna program för speciella ändmål.

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

Allmänt

Den mesta brandingen görs i MainCmd.cpp or MainGui.cpp. Dessa Projekt genererar FreeCAD's körbara filer. För att göra din egen variant så behöver du bara kopiera Main eller MainGui projekten och ge den körbara filen ett eget namn, d.v.s. FooApp.exe.

De viktigaste inställningarna för ett nytt utseende kan göras på en plats i main() funktionen. Här är den kodsektion som kontrollerar branding:

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;
}

Den första Config punkten definierar programmets namn. Detta är inte det körbara namnet, vilket kan ändras genom att döpa om eller genom inställningar i kompilatorn, utan det namn som visas i windows programrad eller i programlistan på Unixsystem.

Efterföljande rader definierar Config punkterna för din FooApp Applikation. En beskrivning av Config och dess punkter hittar du i Uppstart och Konfiguration.

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/sv
Localisation/sv


Lokalisering är i allmänhet den process som ger användargränssnittet i ett program flera språk. I FreeCAD så kan du ställa in användargränssnittets språk under Redigera?Alternativ?Allmänt. FreeCAD använder [Qt] för att aktivera flerspråkssupport. På Unix/Linux system så använder FreeCAD som standard de gällande locale-inställningarna för systemet.

Localisation is in general the process of providing a Software with a multiple language user interface. In FreeCAD you can set the language of the user interface under Edit → Preferences → General. FreeCAD uses Qt to enable multiple language support. On Unix/Linux systems, FreeCAD uses the current locale settings of your system by default.

Hjälpa till med att översätta FreeCAD

En av de mycket viktiga saker du kan göra för FreeCAD, om du inte är en programmerare, är att hjälpa till att översätta programmet till ditt språk. Det är nu lättare än någonsin att göra det då vi nu använder oss av Crowdin online översättningssystemet där man kan samarbeta med flera personer

Hur man översätter

FreeCAD utilizes a third party collaborative on-line translation system called Crowdin.

It is proprietary software but free to FOSS projects. Below are instructions on how to use it:

  • Gå till FreeCADs projektsida för översättning på Crowdin;
  • Logga in genom att skapa en ny profil, eller genom att använda ett tredjepartskonto som t.ex din Gmail adress;
  • Klicka på det språk som du vill översätta;
  • Börja översätt genom att klicka på Translate knappen intill en av filerna. FreeCAD.ts innehåller till exempel textsträngarna för FreeCADs huvudgränssnitt.
  • Du kan rösta på existerande översättningar, eller så kan du skapa dina egna.
Notera: Om du deltar aktivt i översättningen av FreeCAD och vill bli  
informerad innan nästa utgåva är klar att släppas, 
so du får tid att granska din översättning, så prenumerera på  
denna punkt: http://www.freecadweb.org/tracker/view.php?id=137

Note: Details on how to use crowdin can be found on the Crowdin Administration page.

Translating external workbenches

Visit Translating an external workbench.

FreeCAD Preferences for Translators

Starting with FreeCAD 0.20, the following variables can be manually added to the BaseApp/Preferences/General section of the user.cfg file to assist with the development of new translations:

AdditionalLanguageDomainEntries - to add entirely new languages to FreeCAD that are not currently supported by the source code, you can use this user preference to add to the list of available languages. The format of the languages is "Language Name"="code"; for example:

<FCText Name="AdditionalLanguageDomainEntries">"Esperanto"="eo";"French"="fr";</FCText>

AdditionalTranslationsDirectory - add an additional directory for FreeCAD to search for *.qm files. This location will take precedence over $userAppDataDir/translations and $resourceDir/translations. For example:

<FCText Name="AdditionalTranslationsDirectory">C:/Users/FreeCADUser/TestTranslations</FCText>

Översätta wikin

This wiki hosts a lot of contents, the majority of which build up the manual. You can browse the documentation starting from the Main Page, or have a look at the user's manual Online Help Toc.

To translate the wiki, you must have wiki edit permissions; see How can I get edit permission on the wiki?.

You should also have enough knowledge of wiki markup and follow the general styling guidelines described on WikiPages.

Mediawiki Translation Extension

When the wiki moved away from SourceForge, Yorik installed MediaWiki's Translation extension which facilitates translating pages. Advantages of the translation extension are that the page title can now be translated, it keeps track of translations, it notifies if the original page has been updated, and it maintains translations in sync with the original English page.

The tool is documented in Help:Extension:Translate, and is part of MediaWiki Language Extension Bundle.

To quickly get started on preparing a page for translation, please read the Page translation example. Essentially, a pair of

<translate> ... </translate>

tags need to surround the entire page to activate the translation system, and the page needs to be marked for translation.

To see an example of how the translation tool works, visit the Main Page. You will see an automatically generated language bar at the top. Click on Deutsch (German), it will get you to Main Page/de. Right under the title, "Hauptseite" (in English "Main Page"), you can read This page is a translated version of the page Main Page and the translation is XX% complete, XX being the current percentage of translation. Click on "Translate" at the top of the page to start the translation utility to update, correct and review the existing translation.

If you go to Main Page, you will notice that you cannot edit the page directly anymore by clicking the [Edit] tags, and the top link "Edit" has been substituted by the "Translate" link that opens the translation utility.

When adding new content, the English page should be created first, then translated into another language. If someone wants to change or add content in a page, the English page should be modified first.

Om du är osäker på hur du ska fortsätta, tveka inte att be om hjälp på forumet.

Important notes

Every wiki user that has "Editor" permissions is able to launch the translate utility to write, save and review translations.

However, only users with "Administrator" permissions are able to mark pages for translation. A page that is not marked for translation won't make use of the translation extension and won't be correctly synchronized to the English information.

The left sidebar is also translatable, but only Administrators can modify this element of the site. Please follow the dedicated instructions on Localisation Sidebar.

The first time you switch a page to the new translation system, it loses all its old "manual" translations. To recover a translation, you should save an offline copy of the old text before the switch. Then you can use this old translated text to fill in the translation units in the new system. You can also open an earlier version from the history, and get the old text in this way. This has to be done for every language that had a translated page.

Translate the FreeCAD documentation

As per general consensus, the reference page in the wiki is the English page, which should be created first. If you want to change or add content to a page, you should do it to the English page first, and only once the update is completed, port the modification to the translated page.

Old translation instructions

These instructions are for historical background only. Translations should use the new system with the #Mediawiki Translation Extension described above.

So the first step is to check if the manual translation has already been started for your language (look in the left sidebar, under "manual").
If not, head to the forum and say that you want to start a new translation, we'll create the basic setup for the language you want to work on.
You must then gain wiki edit permission.
If your language is already listed, see what pages are still missing a translation (they will be listed in red). The technique is simple: go into a red page, and copy/paste the contents of the corresponding English page, and start translating.
Do not forget to include all the tags and templates from the original English page. Some of those templates will have an equivalent in your language (for example, there is a French Docnav template called Docnav/fr). You should use a slash and your language code in almost all the links. Look at other already translated pages to see how they did it.
Add a slash and your language code in the categories, like [[Category:Developer Documentation/fr]]
And if you are unsure, head to the forums and ask people to check what you did and tell you if it's right or not.
Four templates are commonly used in manual pages. These 4 templates have localized versions (Template:Docnav/fr, Template:fr, etc...)

  • Template:GuiCommand : is the Gui Command information block in upper-right of command documentation.
  • Template:Docnav : it is the navigation bar at the bottom of the pages, showing previous and next pages.
  • Template:Userdocnavi : gives direct links to the main base pages

Page Naming Convention
Please take note that, due to limitations in the Sourceforge implementation of the MediaWiki engine, we require that your pages all keep their original English counterpart's name, appending a slash and your language code. For example, the translated page for About FreeCAD should be About Freecad/es for Spanish, About FreeCAD/pl for polish, etc. The reason is simple: so that if translators go away, the wiki's administrators, who do not speak all languages, will know what these pages are for. This will facilitate maintenance and avoid lost pages.
If you want the Docnav template to show linked pages in your language, you can use redirect pages. They are basically shortcut links to the actual page. Here is an example with the French page for About FreeCAD.

  • The page About FreeCAD/fr is the page with content
  • The page À propos de FreeCAD contains this code:
#REDIRECT [[About_FreeCAD/fr]]
  • In the About FreeCAD/fr page, the Docnav code will look like this:
{{docnav/fr|[[Online_Help_Startpage/fr|Bienvenue dans l'aide en ligne de FreeCAD]]|[[Feature_list/fr|Fonctionnalités]]}}

The page "Bienvenue dans l'aide en ligne de FreeCAD" redirects to Online_Help_Startpage/fr, and the page "Fonctionnalités" redirects to Feature_list/fr.

Translate the FreeCAD website

Translation of the FreeCAD website is now done through Crowdin. The file is named homepage.po.

Development - How to Add Localisation

This section is for developers who want to add localisation to their code.

Förbereda dina egna moduler/applikationer för översättning

These are the parts to the FreeCAD translation process:

  • extract text strings from source code into *.ts files
  • load *.ts files into FreeCAD Crowdin.
  • translation of strings within Crowdin
  • extract modified/new *.ts files from Crowdin
  • convert *.ts files into *.qm files and update each module's *.qrc file
  • update FreeCAD master

All of the above steps are performed by the "translation scripts" which are run by an administrator periodically.

Preparing your module for translation is quite easy. First, you need to ensure that you have a "translations" directory in myModule/Gui/Resources. Then open a terminal window (or Windows/OSX equivalent) in your "translations" directory and enter the following command:

lupdate -ts myModule.ts

This creates an empty translation file. Once this is done, you need to ensure that the translation scripts are updated as in this pull request.

Everything after this is automatic as far as a developer is concerned. The administrator will extract the text strings, the translators will translate them, then the administrator will extract the translations and update FreeCAD/master.

Förkrav

3rd party modules or macros are translated in much the same fashion, except that you must do some of the work yourself. This forum discussion describes the details.

Update: see Translating an external workbench

Older module translation techniques

Localization Older Methods describes the use of translation tools such as Qt Linguist, lupdate, lrelease, pylupdate4, etc in detail. Most of this is no longer required for FreeCAD/master modules, but may be helpful preparing and updating 3rd party modules.

Automating Crowdin Translation Updates

Currently FreeCAD maintainers use the Crowdin API via Crowdin Scripts to pull and push translations in to Crowdin and back in to the Github repo. The Crowdin API gives FreeCAD maintainers the ability to automate aspects of the project's translation workflow, for more info refer to the Crowdin API documentation.

Related Pages

Scripting

See also: FreeCAD Scripting Basics.

To get a dictionary with the languages the FreeCAD interface supports, use the supportedLocales method of the FreeCADGui module.

locales = FreeCADGui.supportedLocales()

After execution locales will contain:

{'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'}

To get the current interface language use the getLocale method of the same module:

locale = FreeCADGui.getLocale()

If the current language is English locale will contain:

'English'

To get the corresponding language code you can use use:

locale = FreeCADGui.supportedLocales()[Gui.getLocale()]

If the current language is English the result will be:

'en'

To set the current interface language use the setLocale method of the same module. You can specify the language or the language code:

FreeCADGui.setLocale('Russian')
FreeCADGui.setLocale('ru')


Branding/sv
Extra python modules/sv


Overview

This page lists several additional Python modules or other pieces of software that can be downloaded freely from the internet, and add functionality to your FreeCAD installation.

PySide (previously PyQt)

PySide (previously PyQt) is required by several modules of FreeCAD to access FreeCAD's Qt interface. It is already bundled in the windows verison of FreeCAD, and is usually installed automatically by FreeCAD on Linux, when installing from official repositories. If those modules (Draft, Arch, etc) are enabled after FreeCAD is installed, it means PySide (previously PyQt) is already there, and you don't need to do anything more.

Notera: av följande moduler, så är Pivy nu helt integrerad i alla FreeCAD installationspaket, och PyQt4 är också integrerat i Windows installationspaket.

Installation

Linux

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

Windows

The program can be downloaded from http://qt-project.org/wiki/Category:LanguageBindings::PySide::Downloads . You'll need to install the Qt and SIP libraries before installing PySide (to be documented).

MacOS

PySide on Mac can be installed via homebrew or port. See Install dependencies for more information.

Usage

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

import PySide

To access the FreeCAD interface, type:

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.

Installation

Prerequisites

I believe before compiling Pivy you will want to have Coin and SoQt installed.

I found for building on Mac it was sufficient to install the Coin3 binary package. Attempting to install coin from MacPorts was problematic: tried to add a lot of X Windows packages and ultimately crashed with a script error.

For Fedora I found an RPM with Coin3.

SoQt compiled from source fine on Mac and Linux.

Debian & Ubuntu

Debian & Ubuntu

Med början i Debian Squeeze och Ubuntu Lucid, så kommer pivy att finnas tillgängligt direkt från de officiella förråden, vilket sparar mycket krångel. Innan dess, så kan du antingen ladda ned ett av de paket som vi har gjort (för debian och ubuntu karmic) tillgängliga på Nedladdningssidorna, eller så kan du kompilera det själv.

Det bästa sättet att kompilera pivy smidigt är att hämta debians källkodspaket för pivy och göra ett paket med debuild. Det är samma källkod som på den officiella pivysajten, men debianfolket har gjort flera bugg-fixningstillägg. Det kompilerar också bra på ubuntu karmic: http://packages.debian.org/squeeze/python-pivy (ladda ned .orig.gz och .diff.gz file, packa upp båda, tillämpa sedan .diff på källkoden: gå till den uppackade pivy källkodsmappen, och tillämpa .diff patchen:

patch -p1 < ../pivy_0.5.0~svn765-2.diff

sedan

debuild

för att få pivy korrekt byggt till ett officiellt installerbart paket. Sedan så är det bara att installera paketet med gdebi.

Other linux distributions

First get the latest sources from the project's repository:

hg clone http://hg.sim.no/Pivy/default Pivy

As of March 2012, the latest version is Pivy-0.5.

Sedan behöver du ett verktyg som kallas för SWIG för att generera C++ koden för Pythonbindningarna. Det rekommenderas att version 1.3.25 av SWIG används, inte den senaste versionen, därför att pivy för tillfället endast fungerar korrekt med 1.3.25. Ladda ned 1.3.25 source tarball från http://www.swig.org. Packa sedan upp den, och gör som root följande i en konsol:

./configure
make
make install (or checkinstall if you use it)

Det tar bara några sekunder att bygga.

Alternatively, you can try building with a more recent SWIG. As of March 2012, a typical repository version is 2.0.4. Pivy has a minor compile problem with SWIG 2.0.4 on macOS (see below) but seems to build fine on Fedora Core 15.

Efter det, gå till pivy källkoden och anropa

python setup.py build

which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.

viltet skapar källkodsfilerna. Du kan få kompileringsfel där en 'const char*' inte kan konverteras till en 'char*'. För att fixa det så behöver du bara skriva en 'const' innan raderna som orsakade felet.

Det finns sex rader att fixa. Efter det, installera genom att skriva (som root):

python setup.py install (or checkinstall python setup.py install)

Klart! Pivy är installerat.

MacOS

These instructions may not be complete. Something close to this worked for OS 10.7 as of March 2012. I use MacPorts for repositories, but other options should also work.

As for linux, get the latest source:

hg clone http://hg.sim.no/Pivy/default Pivy

If you don't have hg, you can get it from MacPorts:

port install mercurial

Then, as above you need SWIG. It should be a matter of:

port install swig

I found I needed also:

port install swig-python

As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest

This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:

python setup.py build
sudo python setup.py install

Windows

Windows

När du använder Visual Studio 2005 eller senare så ska du öppna en kommandoprompt med 'Visual Studio 2005 Command prompt' från Tools menyn. Om du ännu inte har Pythontolken i systemsökvägen, gör

set PATH=path_to_python_2.5;%PATH%

För att få pivy att fungera så ska du hämta den senaste källkoden från projektets förråd:

svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy

Sedan behöver du ett verktyg som kallas för SWIG för att generera C++ koden för Python bindningarna. Det rekommenderas att version 1.3.25 av SWIG används, inte den senaste versionen, därför att pivy för tillfället endast fungerar korrekt med 1.3.25. Ladda ned binärkoden för 1.3.25 från http://www.swig.org. Packa sedan upp den och lägg till den i systemsökvägen från kommandoraden

set PATH=path_to_swig_1.3.25;%PATH%

och ställ in COINDIR till den riktiga sökvägen

set COINDIR=path_to_coin

På Windows så förväntar sig pivys konfigurationsfil SoWin istället för SoQt som standard. Jag har inte hittat en självklart sätt att bygga med SoQt, så Jag modifierade filen setup.py direkt.

Ta på rad 200 bort delen 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (ta inte bort den stängande parentesen).

Efter det, gå till pivy källkoden och anropa

python setup.py build

vilket skapar källkodsfilerna. Du kan få kompileringsfel för att flera headerfiler inte kunde hittas. I detta fall så får du justera INCLUDE variabeln

set INCLUDE=%INCLUDE%;path_to_coin_include_dir

och om SoQt headers int är på samma plats som Coin headers så får du också justera

set INCLUDE=%INCLUDE%;path_to_soqt_include_dir

och slutligen Qt headers

set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

Om du använder Expressutgåvan av Visual Studio så kan du få ett python keyerror undantag.

I detta fall så måste du ändra en del saker i msvccompiler.py som finns i din python installation.

Gå till rad 122 och byt ut raden

vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version

mot

vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version

Försök sedan igen.

Om du får ett andra fel som

error: Python was built with Visual Studio 2003;...

Så måste du även byta ut rad 128

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")

mot

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")

Försök igen. Om du åter får ett fel som

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.

så ska du kontrollera miljövariablerna DISTUTILS_USE_SDK och MSSDK med

echo %DISTUTILS_USE_SDK%
echo %MSSDK%

Om de inte är inställda än, ställ in dem till 1

set DISTUTILS_USE_SDK=1
set MSSDK=1

Nu kan du få kompileringsfel där en 'const char*' inte kan konverteras till en 'char*'. För att fixa det så behöver du bara skriva en 'const' innan raderna som orsakade felet. Det finns sex rader att fixa.

Kopiera sedan den genererade pivykatalogen till en plats där pythontolken i FreeCAD kan hitta den.

Usage

To check if Pivy is correctly installed:

import pivy

För att Pivy ska komma åt FreeCAD scengrafen, gör följande:

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

Nu kan du utforska FCSceneGraph med dir() kommandot.

Additonal Documentation

Dokumentation

Olyckligtvis så existerar det knappast ännu någon dokumentation om pivy på nätet. Men Coin dokumentationen kan vara användbar, eftersom pivy helt enkelt översätter Coin funktioner, noder och metoder i python, allt behåller samma namn och egenskaper, bara man tänker på syntaxskillnaden mellan C och python:

Du kan också titta på Draft.py filen i FreeCAD Mod/Draft mappen, eftersom den använder pivy mycket.

pyCollada

pyCollada is a Python library that allow programs to read and write Collada (*.DAE) files. When pyCollada is installed on your system, FreeCAD will be able to handle importing and exporting in the Collada file format.

Installation

Linux

sudo apt-get install python3-collada

You can check if pycollada was correctly installed by issuing in a Python console:

import collada

If it returns nothing (no error message), then all is OK

Windows

On Windows since 0.15 pycollada is included in both the FreeCAD release and developer builds so no additional steps are necessary.

MacOS

If you are using the Homebrew build of FreeCAD you can install pycollada into your system Python using pip.

If you need to install pip:

$ sudo easy_install pip

Install pycollada:

$ sudo pip install pycollada

If you are using a binary version of FreeCAD, you can tell pip to install pycollada into the site-packages inside FreeCAD.app:

$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada

or after downloading the pycollada code

$ 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

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

Since ifcopenshell is pretty new, you'll likely need to compile it yourself.

Linux

You will need a couple of development packages installed on your system in order to compile ifcopenshell:

liboce-*-dev
python-dev
swig

but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.

Grab the latest source code from here:

git clone https://github.com/IfcOpenShell/IfcOpenShell.git

The build process is very easy:

mkdir ifcopenshell-build
cd ifcopenshell-build
cmake ../IfcOpenShell/cmake

or, if you are using oce instead of 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

Tutorial Import/Export IFC - compiling IfcOpenShell

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

LazyLoader is included with FreeCAD v0.19

Usage

You will need to import LazyLoader, then change the import of whatever module you want to be deferred.

from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')

The variable Part is how the module is named in your script. You can replicate "import Part as P" by changing the 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


Localisation/sv
Source documentation/sv


Krediter

<translate>

</translate>

<translate>

</translate> <translate>

FreeCAD would not be what it is without the generous contributions of many people. Here's an overview of the people and companies who contributed to FreeCAD over time. For credits for the third party libraries see the Third Party Libraries page.

Development

Project managers

Lead developers of the FreeCAD project:

</translate>

<translate>

Main developers

People who work regularly on the FreeCAD code (retrieved from https://github.com/FreeCAD/FreeCAD/graphs/contributors):

</translate>

<translate>

Other coders

Other people who contributed code to the FreeCAD project:

</translate>

  • 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

<translate>

Companies

Companies which donated code, assets or developer time:

</translate>

<translate>

Forum moderators

People in charge of the FreeCAD forum (retrieved from http://forum.freecadweb.org/memberlist.php?mode=team):

</translate>

<translate>

Community

People from the community who put a lot of efforts in helping the FreeCAD project either by being active on the forum, keeping a blog about FreeCAD, making video tutorials, packaging FreeCAD for Windows/Linux/macOS, writing a FreeCAD book... (listed by alphabetical order) (retrieved from http://forum.freecadweb.org/memberlist.php?mode=&sk=d&sd=d#memberlist).

</translate>

<translate>

Documentation writers

People who wrote the documentation on this wiki:

</translate>

<translate>

Translators

People who helped to translate the FreeCAD application (retrieved from https://crowdin.com/project/freecad):

</translate>

<translate>

Addons developers

Developers of FreeCAD addons (retrieved from https://github.com/FreeCAD/FreeCAD-addons):

</translate>

<translate>


</translate>