Manual

From FreeCAD Documentation
Revision as of 09:17, 3 September 2008 by Jriegel (talk | contribs)

The FreeCAD manual. Includes the essencial parts out of the FreeCAD documentation wiki

Introduction

<translate>

FreeCAD is a general purpose open source parametric 3D CAD modeler licensed under the LGPL License. FreeCAD is aimed directly at mechanical engineering and product design but, being very generic, also fits in a wider range of uses around engineering, such as architecture, finite element analysis, 3D printing, and other tasks.

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.


</translate>

Getting started

<translate>

</translate>

<translate>

Foreword

FreeCAD is a 3D parametric modeling application. It is primarily made for mechanical design, but also serves all other uses where you need to model 3D objects with precision and control over modeling history.

FreeCAD has been under development since 2002, and it offers a large list of features. Capabilities are still missing but it is powerful enough for hobbyist use, and small workshops. There is a fast-growing community of enthusiastic users who participate in the FreeCAD forum, and you can find many examples of quality projects developed with FreeCAD there. See also, FreeCAD used in production.

Like all free software projects, FreeCAD depends on its community to grow, gain features, and fix bugs. Don't forget this when using FreeCAD; if you like it, you can donate and help FreeCAD in various ways, such as writing documentation and making translations.

See also:

Installing

First of all, download and install FreeCAD. See the Download page for information on current versions and updates, and the installation instructions for you operating system (Windows, Linux or macOS). FreeCAD is available from the package managers of many Linux distributions. As FreeCAD is open-source, you can also grab the source code and compile it yourself.

Exploring the interface

The standard FreeCAD interface

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.

Navigating in the 3D space

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:

</translate> <translate>

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:

</translate> <translate>

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


</translate>


<translate>

This is an extensive, but not complete, list of features which FreeCAD implements.

</translate>

<translate>

Release notes

Key features

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

General features

  • multi-platform. FreeCAD runs and behaves exactly the same way on Windows, Linux, macOS and other platforms.
  • full GUI application. FreeCAD has a complete Graphical User Interface based on the Qt framework, with a 3D viewer based on Open Inventor; allowing fast rendering of 3D scenes and a very accessible scene graph representation.
  • runs as a command line application. In command line mode, FreeCAD runs without its interface but with all its geometry tools. In this mode it has a relatively low memory footprint and can be used, for example, as a server to produce content for other applications.
  • can be imported as a Python module. FreeCAD can be imported into any application that can run Python scripts. As in command line mode, the interface part of FreeCAD is unavailable, but all geometry tools are accessible.
  • workbench concept. In the FreeCAD interface, tools are grouped by workbenches. This allows you to display only the tools used to accomplish a certain task, keeping the workspace uncluttered and responsive, and allowing the application to load rapidly.
  • plugin/module framework for late loading of features/data-types. FreeCAD is divided into a core application with modules that are loaded only when needed. Almost all tools and geometry types are stored in modules. Modules behave like plugins; in addition to delayed loading, individual modules can be added to or removed from an existing installation of FreeCAD.
  • parametric associative document objects. All objects in a FreeCAD document can be defined by parameters. Those parameters can be modified and recomputed at any time. Since object relationships are maintained, the modification of one object will automatically propagate to any dependent objects.
  • parametric primitive creation. Primitive objects such as box, sphere, cylinder, etc. can be created by specifying their geometry constraints.
  • graphical modification operations. FreeCAD can perform translation, rotation, scaling, mirroring, offset (either trivial or as described in Jung/Shin/Choi) or shape conversion, in any plane of the 3D space.
  • Constructive solid geometry (boolean operations). FreeCAD can do constructive solid geometry operations (union, difference, intersect).
  • graphical creation of planar geometry. Lines, wires, rectangles, B-splines, and circular or elliptic arcs can be created graphically in any plane of the 3D space.
  • modeling with straight or revolved extrusions, sections and fillets.
  • topological components like vertices, edges, wires and planes.
  • testing and repairing. FreeCAD has tools for testing meshes (solid test, non-two-manifolds test, self-intersection test) and for repairing meshes (hole filling, uniform orientation).
  • annotations. FreeCAD can insert annotations for text or dimensions.
  • Undo/Redo framework. Everything in FreeCAD is undo/redoable, with user access to the undo stack. Multiple steps can be undone at one time.
  • transaction oriented. The undo/redo stack stores document transactions, not single actions, allowing each tool to define exactly what must be undone or redone.
  • built-in scripting framework. FreeCAD features a built-in Python interpreter, with an API that covers almost any part of the application, the interface, the geometry and the representation of this geometry in the 3D viewer. The interpreter can run complex scripts as well as single commands; entire modules can be programmed completely in Python.
  • built-in Python console. The Python interpreter includes a console with syntax highlighting, autocomplete and a class browser. Python commands can be issued directly in FreeCAD and immediately return results, permitting script writers to test functionality on the fly, explore the contents of FreeCAD's modules and easily learn about FreeCAD internals.
  • mirrors user interaction. Everything the user does in the FreeCAD interface executes Python code, which can be printed on the console and recorded in macros.
  • full macro recording and editing capabilities. The Python commands issued when the user manipulates the interface can be recorded, edited if needed, and saved to be reproduced later.
  • compound (ZIP based) document save format. FreeCAD documents are saved with a .FCStd extension. The document can contain many different types of information such as geometry, scripts or thumbnail icons. The .FCStd file is itself a zip container; a saved FreeCAD file has already been compressed.
  • fully customizable/scriptable Graphical User Interface. The Qt-based interface of FreeCAD is entirely accessible via the Python interpreter. Aside from simple functions FreeCAD itself provides to workbenches, the entire Qt framework is accessible. The user may perform any operation on the GUI such as creating, adding, docking, modifying or removing widgets and toolbars.
  • thumbnailer. (currently only Linux systems) FreeCAD document icons show the contents of the file in most file manager applications such as Gnome's Nautilus.
  • modular MSI installer. FreeCAD's installer allows flexible installations on Windows systems. Packages for Ubuntu systems are also maintained.

Extra Workbenches

Power users have created various custom external workbenches.


</translate>

Scripting

<translate>

</translate>

<translate>

Python scripting in FreeCAD

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.

If you are not familiar with Python, we recommend you search for tutorials on the internet and have a quick look at its structure. Python is a very easy language to learn, especially because it can be run inside an interpreter, where simple commands, right up to complete programs, can be executed on the fly without the need to compile anything. FreeCAD has a built-in Python interpreter. If you don't see the window labeled Python console as shown below, you can activate it under the View → Panels → Python console.

The interpreter

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:

The FreeCAD Python interpreter

From the interpreter, you can execute Python code and browse through the available classes and functions. FreeCAD provides a very handy class browser for exploration of the FreeCAD world: When you type the name of a known class followed by a period (meaning you want to add something from that class), a class browser window opens, where you can navigate between available subclasses and methods. When you select something, an associated help text (if it exists) is displayed:

The FreeCAD class browser

So, start here by typing App. or Gui. and see what happens. Another more generic Python way of exploring the content of modules and classes is to use the print(dir()) command. For example, typing print(dir()) will list all modules currently loaded in FreeCAD. print(dir(App)) will show you everything inside the App module, etc.

Another useful feature of the interpreter is the possibility to go back through the command history and retrieve a line of code that you already typed earlier. To navigate through the command history, just use Up arrow or Down arrow.

By right-clicking in the interpreter window, you also have several other options, such as copy the entire history (useful when you want to experiment with things before making a full script of them), or insert a filename with complete path.

</translate>

Top

<translate>

Python Help

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.

</translate>

Top

<translate>

Built-in modules

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.

  • In the App module you'll find everything related to the application itself, like methods for opening or closing files, and to the documents, like setting the active document or listing their contents.
  • In the Gui module, you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interestingly, the graphical representation of all FreeCAD content.

Listing the content of these modules is not very useful because they grow quite fast as FreeCAD develops. But the two browsing tools provided (the class browser and the Python help) should give you complete and up-to-date documentation at any moment.

</translate>

Top

<translate>

The App and Gui objects

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.

This way of doing things allows a very wide range of uses, like having algorithms work only on the definition part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis.

For every App object in your document, there exists a corresponding Gui object. In fact the document itself has both an App and a Gui object. This, of course, only applies when you run FreeCAD with its full interface. In the command-line version no GUI exists, so only App objects are available. Note that the Gui part of objects is re-generated every time an App object is marked as 'to be recomputed' (for example when one of its parameters changes), so any changes made directly to the Gui object may be lost.

To access the App part of something, you type:

</translate>

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

<translate>

where "ObjectName" is the name of your object. You can also type:

</translate>

myObject = App.ActiveDocument.ObjectName

<translate>

To access the Gui part of the same object, you type:

</translate>

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

<translate>

where "ObjectName" is the name of your object. You can also type:

</translate>

myViewObject = App.ActiveDocument.ObjectName.ViewObject

<translate>

If you are in command-line mode and have no GUI, the last line will return None.

</translate>

Top

<translate>

The Document objects

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.

To access the App part of the currently open (active) document, you type:

</translate>

myDocument = App.ActiveDocument

<translate>

To create a new document, type:

</translate>

myDocument = App.newDocument("Document Name")

<translate>

To access the Gui part of the currently open (active) document, you type:

</translate>

myGuiDocument = Gui.ActiveDocument

<translate>

To access the current view, you type:

</translate>

myView = Gui.ActiveDocument.ActiveView

<translate>

</translate>

Top

<translate>

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.

</translate>

Top

<translate>

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:

</translate>

FreeCAD.ActiveDocument.supportedTypes()

<translate>

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

</translate>

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

<translate>

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:

</translate>

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

<translate>

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:

</translate>

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

<translate>

</translate>

Top

<translate>

Modifying objects

Modifying an object is done in the same way:

</translate>

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

<translate>

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

</translate>

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

<translate>

</translate>

Top

<translate>

Querying objects

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

</translate>

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

<translate>

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

</translate>

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

<translate>

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

</translate>

Top

<translate>


</translate>

Mesh scripting

<translate>

</translate>

<translate>

Introduction

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

</translate>

import Mesh

<translate>

Creation

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

</translate>

mesh = Mesh.Mesh()

<translate>

You can also create an object from a file:

</translate>

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

<translate>

Or create it out of a set of triangles described by their corner points:

</translate>

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)

<translate>

The Mesh-Kernel takes care of creating a topologically correct data structure by sorting coincident points and edges.

</translate>

Top

<translate>

Modeling

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

</translate>

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

<translate>

The first two parameters define the radii of the torus and the third parameter is a sub-sampling factor for how many triangles are created. The higher this value the smoother the mesh.

The Mesh module also provides three Boolean methods: union(), intersection() and difference():

</translate>

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

<translate>

Here is an example that creates a pipe using the difference() method:

</translate>

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

<translate>

</translate>

Top

<translate>

Notes

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.

</translate>

Top

<translate>

</translate>

Code Snippets

<translate>

</translate>

<translate>

Introduction

This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...

Snippets

A typical InitGui.py file

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.

</translate>

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

<translate>

</translate>

Top

<translate>

A typical module file

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.

</translate>

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

<translate>

</translate>

Top

<translate>

Import a new filetype

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:

This line must be added to the InitGui.py file to add the new file extension to the list:

</translate>

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

<translate>

Then in the Import_Ext.py file:

</translate>

def open(filename): 
   doc=App.newDocument()
   # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
   doc.recompute()

<translate>

To export your document to some new filetype works the same way, except that you use:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

</translate>

Top

<translate>

Add a line

A line simply has 2 points.

</translate>

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

<translate>

</translate>

Top

<translate>

Add a polygon

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

</translate>

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

<translate>

</translate>

Top

<translate>

Add and remove an object to/from a group

</translate>

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

<translate>

Note: You can even add other groups to a group...

</translate>

Top

<translate>

Add a Mesh

</translate>

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

<translate>

</translate>

Top

<translate>

Add an arc or a circle

</translate>

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

<translate>

</translate>

Top

<translate>

Access and change the representation of an object

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

</translate>

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

<translate>

</translate>

Top

<translate>

Replace the form of mouse with one image

</translate>

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

<translate>

</translate>

Top

<translate>

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

</translate>

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

<translate>

</translate>

Top

<translate>

Observe camera change in the 3D viewer via Python

This can be done adding a Node sensor to the camera:

</translate>

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)

<translate>

</translate>

Top

<translate>

Observe mouse events in the 3D viewer via Python

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.

</translate>

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)

<translate>


Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call

</translate>

v.removeEventCallback("SoMouseButtonEvent",c)

<translate>

The following event types are supported

  • SoEvent -- all kind of events
  • SoButtonEvent -- all mouse button and key events
  • SoLocation2Event -- 2D movement events (normally mouse movements)
  • SoMotion3Event -- 3D movement events (normally spaceball)
  • SoKeyboardEvent -- key down and up events
  • SoMouseButtonEvent -- mouse button down and up events
  • SoSpaceballButtonEvent -- spaceball button down and up events

The Python function that can be registered with addEventCallback() expects a dictionary. Depending on the watched event the dictionary can contain different keys.

For all events it has the keys:

  • Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
  • Time -- the current time as string
  • Position -- a tuple of two integers, mouse position
  • ShiftDown -- a boolean, true if Shift was pressed otherwise false
  • CtrlDown -- a boolean, true if Ctrl was pressed otherwise false
  • AltDown -- a boolean, true if Alt was pressed otherwise false

For all button events, i.e. keyboard, mouse or spaceball events

  • State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases

For keyboard events:

  • Key -- a character of the pressed key

For mouse button event

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY

For spaceball events:

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY

And finally motion events:

  • Translation -- a tuple of three floats
  • Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

</translate>

Top

<translate>

Display keys pressed and Events command

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

</translate>

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

<translate>

</translate>

Top

<translate>

Manipulate the scenegraph in Python

It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

</translate>

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

<translate>

The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python. However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with

</translate>

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

<translate>

</translate>

Top

<translate>

Add and remove objects to/from the scenegraph

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

</translate>

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)

<translate>

To remove it, simply issue: </translate>

sg.removeChild(no)

<translate>

</translate>

Top

<translate> </translate>

<translate>

Save the sceneGraph in 3 series of 36 files

View the code snippet by expanding this section

</translate>
<translate>

</translate>

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)

<translate>

</translate>

Top

<translate>

Add custom widgets to the interface

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

The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):

</translate>

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

<translate>

Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:

</translate>

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

<translate>

</translate>

Top

<translate>

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.

</translate>

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

<translate>

</translate>

Top

<translate>

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:

</translate>

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

<translate>

</translate>

Top

<translate>

Open a custom webpage

</translate>

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

<translate>

</translate>

Top

<translate>

Get the HTML contents of an opened webpage

</translate>

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

<translate>

</translate>

Top

<translate>

Retrieve the coordinates of 3 selected points or objects

</translate>

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

<translate>

</translate>

Top

<translate>

List all objects

</translate>

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

<translate>

</translate>

Top

<translate>

List the dimensions of an object, given its name

</translate>

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

<translate>

</translate>

Top

<translate>

Function resident with the mouse click action

Here with SelObserver on a object select

</translate>

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

<translate>

Other example with ViewObserver on a object select or view

</translate>

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)

<translate>

</translate>

Top

<translate>

Display the active document

</translate>

class DocObserver:                      # document Observer
    def slotActivateDocument(self,doc):
        print(doc.Name)

obs=DocObserver()
App.addDocumentObserver(obs)
#App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

<translate>

To remove the observer call:

</translate>

App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

<translate>

</translate>

Top

<translate>

Find/select all elements below the cursor

</translate>

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)

<translate>

</translate>

Top

<translate> </translate>

<translate>

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
</translate>
<translate>

</translate>

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

<translate>

</translate>

Top

<translate>

List the PropertiesList

</translate>

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

<translate>

</translate>

Top

<translate>

Add a single Property Comment

</translate>

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

<translate>

</translate>

Top

<translate>

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)

</translate>

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

<translate>

</translate>

Top

<translate>

Manual search of an element with label

</translate>

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

<translate>

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)

</translate>

Top

<translate>

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)

</translate>

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)

<translate>

Other method display on "Int" and "Float"

</translate>

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"

<translate>

</translate>

Top

<translate>

Select all objects in the document

</translate>

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

<translate>

</translate>

Top

<translate>

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

</translate>

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

<translate>

</translate>

Top

<translate>

Get the normal vector of a face of an object by Name object and number Face (r.Q)

</translate>

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

<translate>

</translate>

Top

<translate>

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

</translate>

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)

<translate>

</translate>

Top

<translate>

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

</translate>

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

<translate>

</translate>

Top

<translate>

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

</translate>

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)

<translate>

</translate>

Top

<translate>

Get the normal vector of the face and create a line at the point mouse clicked

</translate>

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

<translate>

</translate>

Top

<translate>

Get the normal vector of a surface from a STL file

</translate>

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)

<translate> you are done then run for quit:

</translate>

Gui.ActiveDocument.ActiveView.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), meth)

<translate>

</translate>

Top

<translate>

Create one object to the position of the Camera

</translate>

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

<translate>

here same code simplified

</translate>

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)

<translate>

</translate>

Top

<translate>

Read And write one Expression

</translate>

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

<translate>

</translate>

Top

<translate>

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.

</translate>

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

<translate>

</translate>

Top

<translate>

How to Simulate a Mouse Click at a given Coordinate

The position is relative to the GL widget. See forum thread.

</translate>

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)

<translate>

If you have a 3d point and want to get the 2d point on the opengl widget then use this:

</translate>

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)

<translate>

</translate>

Top

<translate>

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.

</translate>

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)

<translate>

</translate>

Top

<translate>

Close and restart FreeCAD

</translate>

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
        )

<translate>

</translate>

Top

<translate>

Coin3D

See Coin3d snippets

</translate>

Top

<translate>

Related

</translate>

Top

<translate>


</translate>

Extend & Embed

Compile on Unix/Linux

CompileOnUnix

Compile on Windows

<translate>

</translate>

<translate>

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

</translate> https://github.com/FreeCAD/FreeCAD.git <translate>

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:

</translate>

git clone https://github.com/FreeCAD/FreeCAD.git

<translate>

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:

</translate>

<translate>

Building with Visual Studio 15 (2017) or newer

</translate>

<translate>

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

<translate>

Building with Qt Creator (outdated)

</translate>

<translate>

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

<translate>

Command line build

</translate>

<translate>

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

</translate>

msbuild ALL_BUILD.vcxproj /p:Configuration=Release

<translate>

or

</translate>

msbuild INSTALL.vcxproj /p:Configuration=Release

<translate>

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

</translate>

compile-FC install

<translate>

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

</translate>

<translate>

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:

</translate>

git pull https://github.com/FreeCAD/FreeCAD.git master

<translate>

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


</translate>