Topological data scripting: Difference between revisions

From FreeCAD Documentation
No edit summary
No edit summary
(34 intermediate revisions by 8 users not shown)
Line 4: Line 4:
<!--T:111-->
<!--T:111-->
{{Docnav
{{Docnav
|[[Part_scripting|Part scripting]]
|[[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]]
|[[Scripted_objects|Scripted objects]]
|[[Mesh_Scripting|Mesh Scripting]]
}}
}}


Line 14: Line 14:
==Introduction== <!--T:2-->
==Introduction== <!--T:2-->


<!--T:114-->
Here we will explain to you how to control the [[Part_Module|Part Module]] directly from the FreeCAD Python interpreter, or from any external script. The basics about Topological data scripting are described in [[Part_Module#Explaining_the_concepts|Part Module Explaining the concepts]]. Be sure to browse the [[Scripting]] section and the [[FreeCAD_Scripting_Basics]] pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the [[Introduction_to_Python|Introduction to Python]].
Here we will explain to you how to control the [[Part_Workbench|Part]] module directly from the FreeCAD Python interpreter, or from any external script. Be sure to browse the [[Scripting]] section and the [[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]] pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the [[Introduction_to_Python|Introduction to Python]].


===Class diagram=== <!--T:3-->
===See also=== <!--T:202-->


<!--T:203-->
* [[Part_scripting|Part scripting]]
* [[OpenCASCADE|OpenCASCADE]]

==Class diagram== <!--T:3-->

<!--T:115-->
This is a [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)] overview of the most important classes of the Part module:
This is a [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)] overview of the most important classes of the Part module:
[[Image:Part_Classes.jpg|Python classes of the Part module]]
[[Image:Part_Classes.jpg|Python classes of the Part module]]


</translate>{{Top}}<translate>
[[#top|top]]


===Geometry=== <!--T:4-->
===Geometry=== <!--T:4-->


<!--T:117-->
The geometric objects are the building blocks of all topological objects:
The geometric objects are the building blocks of all topological objects:
* '''Geom''' Base class of the geometric objects.
* '''Geom''' Base class of the geometric objects.
* '''Line''' A straight line in 3D, defined by starting point and end point.
* '''Line''' A straight line in 3D, defined by starting point and end point.
* '''Circle''' Circle or circle segment defined by a center point and start and end point.
* '''Circle''' Circle or circle segment defined by a center point and start and end point.
* '''......''' Etc.
* Etc.


</translate>{{Top}}<translate>
[[#top|top]]


===Topology=== <!--T:5-->
===Topology=== <!--T:5-->


<!--T:119-->
The following topological data types are available:
The following topological data types are available:
* '''Compound''' A group of any type of topological objects.
* '''Compound''' A group of any type of topological objects.
Line 46: Line 56:
* '''Shape''' A generic term covering all of the above.
* '''Shape''' A generic term covering all of the above.


</translate>{{Top}}<translate>
[[#top|top]]


==Example: Create simple topology== <!--T:6-->
==Example: Create simple topology== <!--T:6-->
Line 54: Line 64:


<!--T:8-->
<!--T:8-->
We will now create a topology by constructing it out of simpler geometry.
We will now create a topology by constructing it out of simpler geometry. As a case study we will use a part as seen in the picture which consists of four vertices, two arcs and two lines.
As a case study we will use a part as seen in the picture which consists of
four vertices, two arcs and two lines.


</translate>{{Top}}<translate>
[[#top|top]]


===Create geometry=== <!--T:9-->
===Create geometry=== <!--T:9-->


<!--T:122-->
First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later
First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices.
share the same vertices.


<!--T:10-->
<!--T:10-->
Line 70: Line 78:
</translate>
</translate>
{{Code|code=
{{Code|code=
import FreeCAD as App
import Part
import Part
V1 = App.Vector(0, 10, 0)
from FreeCAD import Base
V1 = Base.Vector(0, 10, 0)
V2 = App.Vector(30, 10, 0)
V2 = Base.Vector(30, 10, 0)
V3 = App.Vector(30, -10, 0)
V3 = Base.Vector(30, -10, 0)
V4 = App.Vector(0, -10, 0)
V4 = Base.Vector(0, -10, 0)
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Arc=== <!--T:11-->
===Arc=== <!--T:11-->
Line 92: Line 100:
</translate>
</translate>
{{Code|code=
{{Code|code=
VC1 = Base.Vector(-10, 0, 0)
VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
C1 = Part.Arc(V1, VC1, V4)
VC2 = Base.Vector(40, 0, 0)
VC2 = App.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)
C2 = Part.Arc(V2, VC2, V3)
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Line=== <!--T:14-->
===Line=== <!--T:14-->
Line 117: Line 125:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Put it all together=== <!--T:17-->
===Put it all together=== <!--T:17-->


<!--T:126-->
The last step is to put the geometric base elements together
and bake a topological shape:
The last step is to put the geometric base elements together and bake a topological shape:


</translate>
</translate>
Line 130: Line 138:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Make a prism=== <!--T:18-->
===Make a prism=== <!--T:18-->


<!--T:128-->
Now extrude the wire in a direction and make an actual 3D shape:
Now extrude the wire in a direction and make an actual 3D shape:


Line 139: Line 148:
{{Code|code=
{{Code|code=
W = Part.Wire(S1.Edges)
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0, 0, 10))
P = W.extrude(App.Vector(0, 0, 10))
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Show it all=== <!--T:19-->
===Show it all=== <!--T:19-->
Line 153: Line 162:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Create basic shapes== <!--T:20-->
==Create basic shapes== <!--T:20-->


<!--T:131-->
You can easily create basic topological objects with the {{incode|make...()}}
methods from the Part Module:
You can easily create basic topological objects with the {{incode|make...()}} methods from the Part module:


</translate>
</translate>
Line 169: Line 178:
<!--T:21-->
<!--T:21-->
Some available {{incode|make...()}} methods:
Some available {{incode|make...()}} methods:
* {{incode|makeBox(l, w, h)}} Makes a box located in p and pointing into the direction d with the dimensions (l,w,h).
* {{incode|makeBox(l, w, h, [p, d])}} Makes a box located in p and pointing into the direction d with the dimensions (l,w,h).
* {{incode|makeCircle(radius)}} Makes a circle with a given radius.
* {{incode|makeCircle(radius)}} Makes a circle with a given radius.
* {{incode|makeCone(radius1, radius2, height)}} Makes a cone with the given radii and height.
* {{incode|makeCone(radius1, radius2, height)}} Makes a cone with the given radii and height.
Line 180: Line 189:
See the [[Part_API|Part API]] page for a complete list of available methods of the Part module.
See the [[Part_API|Part API]] page for a complete list of available methods of the Part module.


</translate>{{Top}}<translate>
[[#top|top]]


===Import modules=== <!--T:22-->
===Import modules=== <!--T:22-->


<!--T:133-->
First we need to import the Part module so we can use its contents in Python.
We'll also import the Base module from inside the FreeCAD module:
First we need to import the FreeCAD and Part modules so we can use their contents in Python:


</translate>
</translate>
{{Code|code=
{{Code|code=
import FreeCAD as App
import Part
import Part
from FreeCAD import Base
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a vector=== <!--T:23-->
===Create a vector=== <!--T:23-->


<!--T:135-->
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most
important pieces of information when building shapes. They usually contain three numbers
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this:
(but not necessarily always): the X, Y and Z cartesian coordinates. You
create a vector like this:


</translate>
</translate>
{{Code|code=
{{Code|code=
myVector = Base.Vector(3, 2, 0)
myVector = App.Vector(3, 2, 0)
}}
}}
<translate>
<translate>


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


</translate>
</translate>
{{Code|code=
{{Code|code=
myVertex = myShape.Vertexes[0]
myVertex = myShape.Vertexes[0]
print myVertex.Point
print(myVertex.Point)
> Vector (3, 2, 0)
> Vector (3, 2, 0)
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create an edge=== <!--T:25-->
===Create an edge=== <!--T:25-->


<!--T:137-->
An edge is nothing but a line with two vertices:
An edge is nothing but a line with two vertices:


Line 242: Line 247:
</translate>
</translate>
{{Code|code=
{{Code|code=
vec1 = Base.Vector(0, 0, 0)
vec1 = App.Vector(0, 0, 0)
vec2 = Base.Vector(10, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()
edge = line.toShape()
Line 261: Line 266:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Put the shape on screen=== <!--T:28-->
===Put the shape on screen=== <!--T:28-->


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


Line 277: Line 281:


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


</translate>{{Top}}<translate>
[[#top|top]]


===Create a wire=== <!--T:30-->
===Create a wire=== <!--T:30-->


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


</translate>
</translate>
Line 303: Line 306:


<!--T:31-->
<!--T:31-->
{{incode|Part.show(wire3)}} will display the 4 edges that compose our wire. Other
{{incode|Part.show(wire3)}} will display the 4 edges that compose our wire. Other useful information can be easily retrieved:
useful information can be easily retrieved:


</translate>
</translate>
Line 319: Line 321:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a face=== <!--T:32-->
===Create a face=== <!--T:32-->


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


</translate>
</translate>
Line 338: Line 340:
> True
> True
sface = Part.Face(wire2)
sface = Part.Face(wire2)
face.isValid()
sface.isValid()
> False
> False
}}
}}
Line 346: Line 348:
Only faces will have an area, wires and edges do not.
Only faces will have an area, wires and edges do not.


</translate>{{Top}}<translate>
[[#top|top]]


===Create a circle=== <!--T:34-->
===Create a circle=== <!--T:34-->


<!--T:145-->
A circle can be created like this:
A circle can be created like this:


Line 365: Line 368:
</translate>
</translate>
{{Code|code=
{{Code|code=
ccircle = Part.makeCircle(10, Base.Vector(10, 0, 0), Base.Vector(1, 0, 0))
ccircle = Part.makeCircle(10, App.Vector(10, 0, 0), App.Vector(1, 0, 0))
ccircle.Curve
ccircle.Curve
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))
Line 372: Line 375:


<!--T:36-->
<!--T:36-->
ccircle will be created at distance 10 from the X origin and will be facing
ccircle will be created at distance 10 from the X origin and will be facing outwards along the X axis. Note: {{incode|makeCircle()}} only accepts {{incode|App.Vector()}} for the position and normal parameters, not tuples. You can also create part of the circle by giving a start and an end angle:
outwards along the X axis. Note: {{incode|makeCircle()}} only accepts {{incode|Base.Vector()}} for the position
and normal parameters, not tuples. You can also create part of the circle by giving
a start and an end angle:


</translate>
</translate>
{{Code|code=
{{Code|code=
from math import pi
from math import pi
arc1 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180)
arc1 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 180, 360)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)
}}
}}
<translate>
<translate>
Line 396: Line 396:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create an arc along points=== <!--T:38-->
===Create an arc along points=== <!--T:38-->


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


</translate>
</translate>
{{Code|code=
{{Code|code=
arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.Vector(5, 5, 0))
arc = Part.Arc(App.Vector(0, 0, 0), App.Vector(0, 5, 0), App.Vector(5, 5, 0))
arc
arc
> <Arc object>
> <Arc object>
Line 417: Line 414:


<!--T:39-->
<!--T:39-->
{{incode|Arc()}} only accepts {{incode|Base.Vector()}} for points and not tuples. You can also obtain
{{incode|Arc()}} only accepts {{incode|App.Vector()}} for points and not tuples. You can also obtain an arc by using a portion of a circle:
an arc by using a portion of a circle:


</translate>
</translate>
{{Code|code=
{{Code|code=
from math import pi
from math import pi
circle = Part.Circle(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10)
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)
arc = Part.Arc(circle,0,pi)
}}
}}
Line 431: Line 427:
Arcs are valid edges like lines, so they can be used in wires also.
Arcs are valid edges like lines, so they can be used in wires also.


</translate>{{Top}}<translate>
[[#top|top]]


===Create a polygon=== <!--T:41-->
===Create a polygon=== <!--T:41-->


<!--T:149-->
A polygon is simply a wire with multiple straight edges. The {{incode|makePolygon()}}
function takes a list of points and creates a wire through those points:
A polygon is simply a wire with multiple straight edges. The {{incode|makePolygon()}} function takes a list of points and creates a wire through those points:


</translate>
</translate>
{{Code|code=
{{Code|code=
lshape_wire = Part.makePolygon([Base.Vector(0, 5, 0), Base.Vector(0, 0, 0), Base.Vector(5, 0, 0)])
lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a bézier curve=== <!--T:42-->
===Create a Bézier curve=== <!--T:42-->


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


</translate>
</translate>
Line 460: Line 457:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a plane=== <!--T:43-->
===Create a plane=== <!--T:43-->


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


</translate>
</translate>
Line 473: Line 469:
plane
plane
> <Face object at 028AF990>
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, Base.Vector(3, 0, 0), Base.Vector(0, 1, 0))
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.Vector(0, 1, 0))
plane.BoundBox
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)
> BoundBox (3, 0, 0, 5, 0, 2)
Line 480: Line 476:


<!--T:44-->
<!--T:44-->
{{incode|BoundBox}} is a cuboid enclosing the plane with a diagonal starting at
{{incode|BoundBox}} is a cuboid enclosing the plane with a diagonal starting at (3, 0, 0) and ending at (5, 0, 2). Here the {{incode|BoundBox}} thickness along the Y axis is zero, since our shape is totally flat.
(3, 0, 0) and ending at (5, 0, 2). Here the {{incode|BoundBox}} thickness along the Y axis is zero,
since our shape is totally flat.


<!--T:45-->
<!--T:45-->
Note: {{incode|makePlane()}} only accepts {{incode|Base.Vector()}} for start_pnt and dir_normal and not tuples.
Note: {{incode|makePlane()}} only accepts {{incode|App.Vector()}} for start_pnt and dir_normal and not tuples.


</translate>{{Top}}<translate>
[[#top|top]]


===Create an ellipse=== <!--T:46-->
===Create an ellipse=== <!--T:46-->


<!--T:155-->
There are several ways to create an ellipse:
There are several ways to create an ellipse:


Line 518: Line 513:


<!--T:49-->
<!--T:49-->
Creates an ellipse centered on the point Center, where the plane of the
Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius is the distance between S2 and the major axis.
ellipse is defined by Center, S1 and S2, its major axis is defined by
Center and S1, its major radius is the distance between Center and S1,
and its minor radius is the distance between S2 and the major axis.


</translate>
</translate>
Line 530: Line 522:


<!--T:50-->
<!--T:50-->
Creates an ellipse with major and minor radii MajorRadius and MinorRadius,
Creates an ellipse with major and minor radii MajorRadius and MinorRadius, located in the plane defined by Center and the normal (0, 0, 1)
located in the plane defined by Center and the normal (0, 0, 1)


</translate>
</translate>
{{Code|code=
{{Code|code=
eli = Part.Ellipse(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0, 0))
eli = Part.Ellipse(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.Vector(0, 0, 0))
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
}}
Line 541: Line 532:


<!--T:51-->
<!--T:51-->
In the above code we have passed S1, S2 and center. Similar to {{incode|Arc}},
In the above code we have passed S1, S2 and center. Similar to {{incode|Arc}}, {{incode|Ellipse}} creates an ellipse object not an edge, so we need to convert it into an edge using {{incode|toShape()}} for display.
{{incode|Ellipse}} creates an ellipse object not an edge, so we need to
convert it into an edge using {{incode|toShape()}} for display.


<!--T:52-->
<!--T:52-->
Note: {{incode|Ellipse()}} only accepts {{incode|Base.Vector()}} for points and not tuples.
Note: {{incode|Ellipse()}} only accepts {{incode|App.Vector()}} for points and not tuples.


</translate>
</translate>
{{Code|code=
{{Code|code=
eli = Part.Ellipse(Base.Vector(0, 0, 0), 10, 5)
eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
}}
Line 558: Line 547:
For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.
For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.


</translate>{{Top}}<translate>
[[#top|top]]


===Create a torus=== <!--T:54-->
===Create a torus=== <!--T:54-->


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


</translate>
</translate>
Line 577: Line 561:


<!--T:55-->
<!--T:55-->
The above code will create a torus with diameter 20 (radius 10) and thickness 4
The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle radius 2)
(small circle radius 2)


</translate>
</translate>
{{Code|code=
{{Code|code=
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180)
tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
}}
}}
<translate>
<translate>
Line 591: Line 574:
</translate>
</translate>
{{Code|code=
{{Code|code=
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 360, 180)
tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 360, 180)
}}
}}
<translate>
<translate>


<!--T:57-->
<!--T:57-->
The above code will create a semi torus; only the last parameter is changed.
The above code will create a semi torus; only the last parameter is changed. i.e the remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.
i.e the remaining angles are defaults. Giving the angle 180 will
create the torus from 0 to 180, that is, a half torus.


</translate>{{Top}}<translate>
[[#top|top]]


===Create a box or cuboid=== <!--T:58-->
===Create a box or cuboid=== <!--T:58-->


<!--T:159-->
Using {{incode|makeBox(length, width, height, [pnt, dir])}}.
Using {{incode|makeBox(length, width, height, [pnt, dir])}}.
By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1).
By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1).
Line 615: Line 597:
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a sphere=== <!--T:59-->
===Create a sphere=== <!--T:59-->


<!--T:161-->
Using {{incode|makeSphere(radius, [pnt, dir, angle1, angle2, angle3])}}. By default
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360.
Using {{incode|makeSphere(radius, [pnt, dir, angle1, angle2, angle3])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter.
angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3
is the sphere diameter.


</translate>
</translate>
{{Code|code=
{{Code|code=
sphere = Part.makeSphere(10)
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), -90, 90, 180)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a cylinder=== <!--T:60-->
===Create a cylinder=== <!--T:60-->


<!--T:163-->
Using {{incode|makeCylinder(radius, height, [pnt, dir, angle])}}. By default
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.
Using {{incode|makeCylinder(radius, height, [pnt, dir, angle])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.


</translate>{{Code|code=
</translate>
{{Code|code=
cylinder = Part.makeCylinder(5, 20)
cylinder = Part.makeCylinder(5, 20)
partCylinder = Part.makeCylinder(5, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Create a cone=== <!--T:61-->
===Create a cone=== <!--T:61-->


<!--T:165-->
Using {{incode|makeCone(radius1, radius2, height, [pnt, dir, angle])}}. By default
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.
Using {{incode|makeCone(radius1, radius2, height, [pnt, dir, angle])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.


</translate>{{Code|code=
</translate>
{{Code|code=
cone = Part.makeCone(10, 0, 20)
cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Modify shapes== <!--T:62-->
==Modify shapes== <!--T:62-->


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


</translate>{{Top}}<translate>
[[#top|top]]


==Transform operations== <!--T:63-->
==Transform operations== <!--T:63-->
Line 669: Line 652:
===Translate a shape=== <!--T:64-->
===Translate a shape=== <!--T:64-->


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


</translate>{{Code|code=
</translate>
{{Code|code=
myShape = Part.makeBox(2, 2, 2)
myShape = Part.makeBox(2, 2, 2)
myShape.translate(Base.Vector(2, 0, 0))
myShape.translate(App.Vector(2, 0, 0))
}}
}}<translate>
<translate>


<!--T:65-->
<!--T:65-->
This will move our shape "myShape" 2 units in the X direction.
This will move our shape "myShape" 2 units in the X direction.


</translate>{{Top}}<translate>
[[#top|top]]


===Rotate a shape=== <!--T:66-->
===Rotate a shape=== <!--T:66-->


<!--T:171-->
To rotate a shape, you need to specify the rotation center, the axis,
and the rotation angle:
To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:


</translate>{{Code|code=
</translate>
{{Code|code=
myShape.rotate(Base.Vector(0, 0, 0),Base.Vector(0, 0, 1), 180)
myShape.rotate(App.Vector(0, 0, 0),App.Vector(0, 0, 1), 180)
}}<translate>
}}
<translate>


<!--T:67-->
<!--T:67-->
The above code will rotate the shape 180 degrees around the Z Axis.
The above code will rotate the shape 180 degrees around the Z Axis.


</translate>{{Top}}<translate>
[[#top|top]]


===Matrix transformations=== <!--T:68-->
===Matrix transformations=== <!--T:68-->


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


</translate>{{Code|code=
</translate>
{{Code|code=
myMat = Base.Matrix()
myMat = App.Matrix()
myMat.move(Base.Vector(2, 0, 0))
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi/2)
}}
}}<translate>
<translate>


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


</translate>{{Code|code=
</translate>
{{Code|code=
myMat.move(2, 0, 0)
myMat.move(2, 0, 0)
myMat.move(Base.Vector(2, 0, 0))
myMat.move(App.Vector(2, 0, 0))
}}
}}<translate>
<translate>


<!--T:70-->
<!--T:70-->
Once our matrix is set, we can apply it to our shape. FreeCAD provides two
Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: {{incode|transformShape()}} and {{incode|transformGeometry()}}. The difference is that with the first one, you are sure that no deformations will occur (see [[#Scaling a shape|Scaling a shape]] below). We can apply our transformation like this:
methods for doing that: {{incode|transformShape()}} and {{incode|transformGeometry()}}. The difference
is that with the first one, you are sure that no deformations will occur (see
[[#Scaling a shape|Scaling a shape]] below). We can apply our transformation like this:


</translate>{{Code|code=
</translate>
{{Code|code=
myShape.transformShape(myMat)
myShape.transformShape(myMat)
}}
}}<translate>
<translate>


<!--T:71-->
<!--T:71-->
or
or


</translate>{{Code|code=
</translate>
{{Code|code=
myShape.transformGeometry(myMat)
myShape.transformGeometry(myMat)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Scale a shape=== <!--T:72-->
===Scale a shape=== <!--T:72-->


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


</translate>{{Code|code=
</translate>
{{Code|code=
myMat = Base.Matrix()
myMat = App.Matrix()
myMat.scale(2, 1, 1)
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)
myShape=myShape.transformGeometry(myMat)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Boolean operations== <!--T:73-->
==Boolean operations== <!--T:73-->
Line 757: Line 745:
===Subtraction=== <!--T:74-->
===Subtraction=== <!--T:74-->


<!--T:177-->
Subtracting a shape from another one is called "cut" in FreeCAD
and is done like this:
Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:


</translate>{{Code|code=
</translate>
{{Code|code=
cylinder = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
sphere = Part.makeSphere(5, Base.Vector(5, 0, 0))
cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)
diff = cylinder.cut(sphere)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Intersection=== <!--T:75-->
===Intersection=== <!--T:75-->


<!--T:179-->
The same way, the intersection between two shapes is called "common" and is done
The same way, the intersection between two shapes is called "common" and is done this way:
this way:


</translate>{{Code|code=
</translate>
{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1))
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)
common = cylinder1.common(cylinder2)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Union=== <!--T:76-->
===Union=== <!--T:76-->


<!--T:181-->
Union is called "fuse" and works the same way:
Union is called "fuse" and works the same way:


</translate>{{Code|code=
</translate>
{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1))
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)
fuse = cylinder1.fuse(cylinder2)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Section=== <!--T:77-->
===Section=== <!--T:77-->


<!--T:183-->
A "section" is the intersection between a solid shape and a plane shape.
It will return an intersection curve, a compound curve composed of edges.
A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges.


</translate>{{Code|code=
</translate>
{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1))
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section = cylinder1.section(cylinder2)
section.Wires
section.Wires
Line 808: Line 804:
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D8F4BB0>]
<Edge object at 0D8F4BB0>]
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Extrusion=== <!--T:78-->
===Extrusion=== <!--T:78-->


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


</translate>{{Code|code=
</translate>
{{Code|code=
circle = Part.makeCircle(10)
circle = Part.makeCircle(10)
tube = circle.extrude(Base.Vector(0, 0, 2))
tube = circle.extrude(App.Vector(0, 0, 2))
}}
}}<translate>
<translate>


<!--T:79-->
<!--T:79-->
If your circle is hollow, you will obtain a hollow tube. If your circle is actually
If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc with a filled face, you will obtain a solid cylinder:
a disc with a filled face, you will obtain a solid cylinder:


</translate>{{Code|code=
</translate>
{{Code|code=
wire = Part.Wire(circle)
wire = Part.Wire(circle)
disc = Part.Face(wire)
disc = Part.Face(wire)
cylinder = disc.extrude(Base.Vector(0, 0, 2))
cylinder = disc.extrude(App.Vector(0, 0, 2))
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Explore shapes== <!--T:80-->
==Explore shapes== <!--T:80-->


<!--T:187-->
You can easily explore the topological data structure:
You can easily explore the topological data structure:


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
b = Part.makeBox(100, 100, 100)
b = Part.makeBox(100, 100, 100)
Line 852: Line 854:
v = e.Vertexes[0]
v = e.Vertexes[0]
v.Point
v.Point
}}
}}<translate>
<translate>


<!--T:81-->
<!--T:81-->
By typing the lines above in the Python interpreter, you will gain a good understanding of the structure of Part objects. Here, our {{incode|makeBox()}} command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertices. Straight edges have only two vertices, obviously.
By typing the lines above in the Python interpreter, you will gain a good
understanding of the structure of Part objects. Here, our {{incode|makeBox()}} command
created a solid shape. This solid, like all Part solids, contains faces.
Faces always contain wires, which are lists of edges that border the face.
Each face has at least one closed wire (it can have more if the face has a hole).
In the wire, we can look at each edge separately, and inside each edge, we can
see the vertices. Straight edges have only two vertices, obviously.


</translate>{{Top}}<translate>
[[#top|top]]


===Edge analysis=== <!--T:82-->
===Edge analysis=== <!--T:82-->


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


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
box = Part.makeBox(100, 100, 100)
box = Part.makeBox(100, 100, 100)
anEdge = box.Edges[0]
anEdge = box.Edges[0]
print(anEdge.Length)
print(anEdge.Length)
}}
}}<translate>
<translate>


<!--T:83-->
<!--T:83-->
Now you can access a lot of properties of the edge by using the length as a
Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 100.
position. That means if the edge is 100mm long the start position is 0 and
the end position 100.


</translate>{{Code|code=
</translate>
{{Code|code=
anEdge.tangentAt(0.0) # tangent direction at the beginning
anEdge.tangentAt(0.0) # tangent direction at the beginning
anEdge.valueAt(0.0) # Point at the beginning
anEdge.valueAt(0.0) # Point at the beginning
Line 893: Line 890:
anEdge.curvatureAt(50.0) # the curvature
anEdge.curvatureAt(50.0) # the curvature
anEdge.normalAt(50) # normal vector at that position (if defined)
anEdge.normalAt(50) # normal vector at that position (if defined)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Use a selection=== <!--T:84-->
===Use a selection=== <!--T:84-->


<!--T:191-->
Here we see now how we can use a selection the user did in the viewer.
First of all we create a box and show it in the viewer.
Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer.


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
Part.show(Part.makeBox(100, 100, 100))
Part.show(Part.makeBox(100, 100, 100))
Gui.SendMsgToActiveView("ViewFit")
Gui.SendMsgToActiveView("ViewFit")
}}
}}<translate>
<translate>


<!--T:85-->
<!--T:85-->
Now select some faces or edges. With this script you can
Now select some faces or edges. With this script you can iterate over all selected objects and their sub elements:
iterate over all selected objects and their sub elements:


</translate>{{Code|code=
</translate>
{{Code|code=
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
print(o.ObjectName)
print(o.ObjectName)
Line 919: Line 919:
for s in o.SubObjects:
for s in o.SubObjects:
print("object: ", s)
print("object: ", s)
}}
}}<translate>
<translate>


<!--T:86-->
<!--T:86-->
Select some edges and this script will calculate the length:
Select some edges and this script will calculate the length:


</translate>{{Code|code=
</translate>
{{Code|code=
length = 0.0
length = 0.0
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
Line 931: Line 933:


print("Length of the selected edges: ", length)
print("Length of the selected edges: ", length)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Example: The OCC bottle== <!--T:87-->
==Example: The OCC bottle== <!--T:87-->


<!--T:193-->
A typical example found on the [https://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html OpenCasCade Technology website] is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the {{FileName|Mod/Part}} folder) and can be called from the Python interpreter by typing:
A typical example found on the [https://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html OpenCasCade Technology website] is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the {{FileName|Mod/Part}} folder) and can be called from the Python interpreter by typing:


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
import MakeBottle
import MakeBottle
bottle = MakeBottle.makeBottle()
bottle = MakeBottle.makeBottle()
Part.show(bottle)
Part.show(bottle)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===The script=== <!--T:88-->
===The script=== <!--T:88-->


<!--T:195-->
For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.
For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.


</translate>{{Code|code=
</translate>
{{Code|code=
import FreeCAD as App
import Part, math
import Part, math
from FreeCAD import Base


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


aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
Line 972: Line 980:
aWire=Part.Wire([aEdge1, aEdge2, aEdge3])
aWire=Part.Wire([aEdge1, aEdge2, aEdge3])


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


Line 980: Line 988:


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


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


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


myNeckRadius = myThickness / 4.
myNeckRadius = myThickness / 4.
Line 997: Line 1,005:
el = makeBottleTut()
el = makeBottleTut()
Part.show(el)
Part.show(el)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


===Detailed explanation=== <!--T:89-->
===Detailed explanation=== <!--T:89-->


</translate>{{Code|code=
</translate>
{{Code|code=
import FreeCAD as App
import Part, math
import Part, math
}}
from FreeCAD import Base
}}<translate>
<translate>


<!--T:90-->
<!--T:90-->
We will need, of course, the {{incode|Part}} module, but also the {{incode|FreeCAD.Base}} module, which contains basic FreeCAD structures like vectors and matrices.
We will, of course, need the {{incode|FreeCAD}} and {{incode|Part}} modules.


</translate>
</translate>
{{Code|code=
{{Code|code=
def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
aPnt1=Base.Vector(-myWidth / 2., 0, 0)
aPnt1=App.Vector(-myWidth / 2., 0, 0)
aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0)
aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
aPnt3=Base.Vector(0, -myThickness / 2., 0)
aPnt3=App.Vector(0, -myThickness / 2., 0)
aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0)
aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
aPnt5=Base.Vector(myWidth / 2., 0, 0)
aPnt5=App.Vector(myWidth / 2., 0, 0)
}}
}}
<translate>
<translate>


<!--T:91-->
<!--T:91-->
Here we define our {{incode|makeBottleTut}} function. This function can be called without
Here we define our {{incode|makeBottleTut}} function. This function can be called without arguments, like we did above, in which case default values for width, height, and thickness will be used. Then, we define a couple of points that will be used for building our base profile.
arguments, like we did above, in which case default values for width, height,
and thickness will be used. Then, we define a couple of points that will be used
for building our base profile.


</translate>
</translate>
Line 1,051: Line 1,059:


<!--T:93-->
<!--T:93-->
Remember the difference between geometry and shapes? Here we build
Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. Three edges (edges can be straight or curved), then a wire made of those three edges.
shapes out of our construction geometry. Three edges (edges can be straight
or curved), then a wire made of those three edges.


</translate>
</translate>
{{Code|code=
{{Code|code=
...
...
aTrsf=Base.Matrix()
aTrsf=App.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aTrsf.rotateZ(math.pi) # rotate around the z-axis


Line 1,068: Line 1,074:


<!--T:94-->
<!--T:94-->
So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what we did and glue both halves together. We first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our wire and apply the transformation matrix to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges.
So far we have built only a half profile. Instead of building the whole profile
the same way, we can just mirror what we did and glue both halves together.
We first create a matrix. A matrix is a very common way to apply transformations
to objects in the 3D world, since it can contain in one structure all basic
transformations that 3D objects can undergo (move, rotate and scale).
After we create the matrix we mirror it, then we create a copy of our wire
and apply the transformation matrix to it. We now have two wires, and
we can make a third wire out of them, since wires are actually lists of edges.


</translate>
</translate>
Line 1,081: Line 1,080:
...
...
myFaceProfile=Part.Face(myWireProfile)
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0, 0, myHeight)
aPrismVec=App.Vector(0, 0, myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
myBody=myFaceProfile.extrude(aPrismVec)


Line 1,089: Line 1,088:


<!--T:95-->
<!--T:95-->
Now that we have a closed wire, it can be turned into a face. Once we have a face,
Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we?
we can extrude it. In doing so, we make a solid. Then we apply a nice little
fillet to our object because we care about good design, don't we?


</translate>{{Code|code=
</translate>
{{Code|code=
...
...
neckLocation=Base.Vector(0, 0, myHeight)
neckLocation=App.Vector(0, 0, myHeight)
neckNormal=Base.Vector(0, 0, 1)
neckNormal=App.Vector(0, 0, 1)


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


<!--T:96-->
<!--T:96-->
At this point, the body of our bottle is made, but we still need to create a neck. So we
At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a cylinder.
make a new solid, with a cylinder.


</translate>{{Code|code=
</translate>
{{Code|code=
...
...
myBody = myBody.fuse(myNeck)
myBody = myBody.fuse(myNeck)
}}
}}<translate>
<translate>


<!--T:97-->
<!--T:97-->
The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed.
The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed.


</translate>{{Code|code=
</translate>
{{Code|code=
...
...
return myBody
return myBody
}}
}}<translate>
<translate>


<!--T:98-->
<!--T:98-->
Then, we return our Part solid as the result of our function.
Then, we return our Part solid as the result of our function.


</translate>{{Code|code=
</translate>
{{Code|code=
el = makeBottleTut()
el = makeBottleTut()
Part.show(el)
Part.show(el)
}}
}}<translate>
<translate>


<!--T:99-->
<!--T:99-->
Finally, we call the function to actually create the part, then make it visible.
Finally, we call the function to actually create the part, then make it visible.


</translate>{{Top}}<translate>
[[#top|top]]


==Example: Pierced box== <!--T:100-->
==Example: Pierced box== <!--T:100-->


<!--T:198-->
Here is a complete example of building a pierced box.
Here is a complete example of building a pierced box.


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


</translate>{{Code|code=
</translate>
{{Code|code=
import FreeCAD as App
import Part, math
import Part, math
from FreeCAD import Base


size = 10
size = 10
Line 1,154: Line 1,160:
face6 = Part.Face(poly)
face6 = Part.Face(poly)
myMat = Base.Matrix()
myMat = App.Matrix()


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


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


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


myMat = Base.Matrix()
myMat = App.Matrix()


myMat.rotateX(-math.pi / 2)
myMat.rotateX(-math.pi / 2)
Line 1,174: Line 1,180:


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


myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])
myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])
Line 1,180: Line 1,186:


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


cut_part = mySolid.cut(myCyl)
cut_part = mySolid.cut(myCyl)


Part.show(cut_part)
Part.show(cut_part)
}}
}}<translate>
<translate>


</translate>{{Top}}<translate>
[[#top|top]]


==Loading and saving== <!--T:102-->
==Loading and saving== <!--T:102-->


<!--T:200-->
There are several ways to save your work. You can of course save your FreeCAD document, but you can also save [[Part_workbench|Part]] objects directly to common CAD formats, such as BREP, IGS, STEP and STL.
There are several ways to save your work. You can of course save your FreeCAD document, but you can also save [[Part_Workbench|Part]] objects directly to common CAD formats, such as BREP, IGS, STEP and STL.


<!--T:103-->
<!--T:103-->
Saving a shape to a file is easy. There are {{incode|exportBrep()}}, {{incode|exportIges()}}, {{incode|exportStep()}} and {{incode|exportStl()}} methods available for all shape objects.
Saving a shape to a file is easy. There are {{incode|exportBrep()}}, {{incode|exportIges()}}, {{incode|exportStep()}} and {{incode|exportStl()}} methods available for all shape objects. So, doing:
So, doing:


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
s = Part.makeBox(10, 10, 10)
s = Part.makeBox(10, 10, 10)
s.exportStep("test.stp")
s.exportStep("test.stp")
}}
}}<translate>
<translate>


<!--T:104-->
<!--T:104-->
will save our box into a STEP file. To load a BREP, IGES or STEP file:
will save our box into a STEP file. To load a BREP, IGES or STEP file:


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("test.stp")
s.read("test.stp")
}}
}}<translate>
<translate>


<!--T:105-->
<!--T:105-->
To convert a STEP file to an IGS file:
To convert a STEP file to an IGS file:


</translate>{{Code|code=
</translate>
{{Code|code=
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("file.stp") # incoming file igs, stp, stl, brep
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
s.exportIges("file.igs") # outbound file igs
}}
}}<translate>
<translate>

</translate>{{Top}}<translate>


[[#top|top]]


<!--T:107-->
<!--T:107-->
{{Docnav
{{Docnav
|[[Part_scripting|Part scripting]]
|[[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]]
|[[Scripted_objects|Scripted objects]]
|[[Mesh_Scripting|Mesh Scripting]]
}}
}}


</translate>
</translate>
{{Powerdocnavi{{#translation:}}}}
{{Powerdocnavi{{#translation:}}}}
[[Category:Developer Documentation{{#translation:}}]]
[[Category:Python Code{{#translation:}}]]
[[Category:Python Code{{#translation:}}]]
{{clear}}

Revision as of 11:47, 10 May 2022

Introduction

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

See also

Class diagram

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

Top

Geometry

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

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

Top

Topology

The following topological data types are available:

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

Top

Example: Create simple topology

Wire

We will now create a topology by constructing it out of simpler geometry. As a case study we will use a part as seen in the picture which consists of four vertices, two arcs and two lines.

Top

Create geometry

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

So we create the points first:

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

Top

Arc

Circle


For each arc we need a helper point:

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

Top

Line

Line


The line segments can be created from two points:

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

Top

Put it all together

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

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

Top

Make a prism

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

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

Top

Show it all

Part.show(P)

Top

Create basic shapes

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

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

Some available make...() methods:

  • makeBox(l, w, h, [p, d]) Makes a box located in p and pointing into the direction d with the dimensions (l,w,h).
  • makeCircle(radius) Makes a circle with a given radius.
  • makeCone(radius1, radius2, height) Makes a cone with the given radii and height.
  • makeCylinder(radius, height) Makes a cylinder with a given radius and height.
  • makeLine((x1, y1, z1), (x2, y2, z2)) Makes a line from two points.
  • makePlane(length, width) Makes a plane with length and width.
  • makePolygon(list) Makes a polygon from a list of points.
  • makeSphere(radius) Makes a sphere with a given radius.
  • makeTorus(radius1, radius2) Makes a torus with the given radii.

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

Top

Import modules

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

import FreeCAD as App
import Part

Top

Create a vector

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

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

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

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

Top

Create an edge

An edge is nothing but a line with two vertices:

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

Note: You can also create an edge by passing two vectors:

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

You can find the length and center of an edge like this:

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

Top

Put the shape on screen

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

Part.show(edge)

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

Top

Create a wire

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

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

Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved:

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

Top

Create a face

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

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

Only faces will have an area, wires and edges do not.

Top

Create a circle

A circle can be created like this:

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

If you want to create it at a certain position and with a certain direction:

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

ccircle will be created at distance 10 from the X origin and will be facing outwards along the X axis. Note: makeCircle() only accepts App.Vector() for the position and normal parameters, not tuples. You can also create part of the circle by giving a start and an end angle:

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

Angles should be provided in degrees. If you have radians simply convert them using the formula: degrees = radians * 180/pi or by using Python's math module:

import math
degrees = math.degrees(radians)

Top

Create an arc along points

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

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

Arc() only accepts App.Vector() for points and not tuples. You can also obtain an arc by using a portion of a circle:

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

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

Top

Create a polygon

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

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

Top

Create a Bézier curve

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

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

Top

Create a plane

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

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

BoundBox is a cuboid enclosing the plane with a diagonal starting at (3, 0, 0) and ending at (5, 0, 2). Here the BoundBox thickness along the Y axis is zero, since our shape is totally flat.

Note: makePlane() only accepts App.Vector() for start_pnt and dir_normal and not tuples.

Top

Create an ellipse

There are several ways to create an ellipse:

Part.Ellipse()

Creates an ellipse with major radius 2 and minor radius 1 with the center at (0, 0, 0).

Part.Ellipse(Ellipse)

Creates a copy of the given ellipse.

Part.Ellipse(S1, S2, Center)

Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius is the distance between S2 and the major axis.

Part.Ellipse(Center, MajorRadius, MinorRadius)

Creates an ellipse with major and minor radii MajorRadius and MinorRadius, located in the plane defined by Center and the normal (0, 0, 1)

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

In the above code we have passed S1, S2 and center. Similar to Arc, Ellipse creates an ellipse object not an edge, so we need to convert it into an edge using toShape() for display.

Note: Ellipse() only accepts App.Vector() for points and not tuples.

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

For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.

Top

Create a torus

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

torus = Part.makeTorus(10, 2)

The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle radius 2)

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

The above code will create a slice of the torus.

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

The above code will create a semi torus; only the last parameter is changed. i.e the remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.

Top

Create a box or cuboid

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

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

Top

Create a sphere

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

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

Top

Create a cylinder

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

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

Top

Create a cone

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

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

Top

Modify shapes

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

Top

Transform operations

Translate a shape

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

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

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

Top

Rotate a shape

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

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

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

Top

Matrix transformations

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

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

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

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

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

myShape.transformShape(myMat)

or

myShape.transformGeometry(myMat)

Top

Scale a shape

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

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

Top

Boolean operations

Subtraction

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

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

Top

Intersection

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

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

Top

Union

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

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

Top

Section

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

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

Top

Extrusion

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

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

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

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

Top

Explore shapes

You can easily explore the topological data structure:

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

By typing the lines above in the Python interpreter, you will gain a good understanding of the structure of Part objects. Here, our makeBox() command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertices. Straight edges have only two vertices, obviously.

Top

Edge analysis

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

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

Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 100.

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

Top

Use a selection

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

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

Now select some faces or edges. With this script you can iterate over all selected objects and their sub elements:

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

Select some edges and this script will calculate the length:

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

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

Top

Example: The OCC bottle

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

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

Top

The script

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

import FreeCAD as App
import Part, math

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

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

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

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

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

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

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

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

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

    return myBody

el = makeBottleTut()
Part.show(el)

Top

Detailed explanation

import FreeCAD as App
import Part, math

We will, of course, need the FreeCAD and Part modules.

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

Here we define our makeBottleTut function. This function can be called without arguments, like we did above, in which case default values for width, height, and thickness will be used. Then, we define a couple of points that will be used for building our base profile.

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

Here we define the geometry: an arc, made of three points, and two line segments, made of two points.

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

Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. Three edges (edges can be straight or curved), then a wire made of those three edges.

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

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

So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what we did and glue both halves together. We first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our wire and apply the transformation matrix to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges.

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

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

Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we?

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

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

At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a cylinder.

...
    myBody = myBody.fuse(myNeck)

The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed.

...
    return myBody

Then, we return our Part solid as the result of our function.

el = makeBottleTut()
Part.show(el)

Finally, we call the function to actually create the part, then make it visible.

Top

Example: Pierced box

Here is a complete example of building a pierced box.

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

import FreeCAD as App
import Part, math

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

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

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

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

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

myMat = App.Matrix()

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

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

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

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

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)

Top

Loading and saving

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

Saving a shape to a file is easy. There are exportBrep(), exportIges(), exportStep() and exportStl() methods available for all shape objects. So, doing:

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

will save our box into a STEP file. To load a BREP, IGES or STEP file:

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

To convert a STEP file to an IGS file:

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

Top