Topological data scripting/pl: Difference between revisions

From FreeCAD Documentation
(Updating to match new version of source page)
(Updating to match new version of source page)
(12 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
{{TutorialInfo
{{docnav|Mesh Scripting|Mesh to Part}}

{{TutorialInfo/pl
|Topic=Programming
|Topic=Programming
|Level=Intermediate
|Level=Intermediate
Line 12: Line 15:


== Introduction ==
== Introduction ==
We will here explain you how to control the [[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.
Here we will explain to you how to control the [[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.


=== Class Diagram ===
=== Class Diagram ===
Line 39: Line 42:
=== Quick example : Creating simple topology ===
=== Quick example : Creating simple topology ===


[[Image:Wire.png|right|Wire]]
[[Image:Wire.png|Wire]]



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.
Line 52: Line 56:


So we create first the points:
So we create first the points:

<syntaxhighlight>
{{Code|code=
from FreeCAD import Base
from FreeCAD import Base
V1 = Base.Vector(0,10,0)
V1 = Base.Vector(0,10,0)
Line 58: Line 63:
V3 = Base.Vector(30,-10,0)
V3 = Base.Vector(30,-10,0)
V4 = Base.Vector(0,-10,0)
V4 = Base.Vector(0,-10,0)
}}
</syntaxhighlight>

==== Arc ====
==== Arc ====


[[Image:Circel.png|right|Circle]]
[[Image:Circel.png|Circle]]



To create an arc of circle we make a helper point and create the arc of
To create an arc of circle we make a helper point and create the arc of
circle through three points:
circle through three points:

<syntaxhighlight>
{{Code|code=
VC1 = Base.Vector(-10,0,0)
VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
C1 = Part.Arc(V1,VC1,V4)
Line 71: Line 79:
VC2 = Base.Vector(40,0,0)
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)
C2 = Part.Arc(V2,VC2,V3)
}}
</syntaxhighlight>

==== Line ====
==== Line ====


[[Image:Line.png|right|Line]]
[[Image:Line.png|Line]]



The line can be created very simple out of the points:
The line segment can be created very simple out of the points:
<syntaxhighlight>

L1 = Part.Line(V1,V2)
{{Code|code=
L1 = Part.LineSegment(V1,V2)
# and the second one
# and the second one
L2 = Part.Line(V4,V3)
L2 = Part.LineSegment(V3,V4)
}}
</syntaxhighlight>

==== Putting all together ====
''Note: in FreeCAD 0.16 Part.Line was used, for FreeCAD 0.17 Part.LineSegment has to be used''

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

<syntaxhighlight>
{{Code|code=
S1 = Part.Shape([C1,C2,L1,L2])
S1 = Part.Shape([C1,L1,C2,L2])
</syntaxhighlight>
}}

==== Make a prism ====
==== Make a prism ====
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:

<syntaxhighlight>
{{Code|code=
W = Part.Wire(S1.Edges)
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0,0,10))
P = W.extrude(Base.Vector(0,0,10))
}}
</syntaxhighlight>

==== Show it all ====
==== Show it all ====

<syntaxhighlight>
{{Code|code=
Part.show(P)
Part.show(P)
}}
</syntaxhighlight>

== Creating basic shapes ==
== Creating basic shapes ==
You can easily create basic topological objects with the "make...()"
You can easily create basic topological objects with the "make...()"
methods from the Part Module:
methods from the Part Module:

<syntaxhighlight>
{{Code|code=
b = Part.makeBox(100,100,100)
b = Part.makeBox(100,100,100)
Part.show(b)
Part.show(b)
}}
</syntaxhighlight>

A couple of other make...() methods available:
Other make...() methods available:
* '''makeBox(l,w,h)''': Makes a box located in p and pointing into the direction d with the dimensions (l,w,h)
* '''makeBox(l,w,h)''': 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
* '''makeCircle(radius)''': Makes a circle with a given radius
* '''makeCone(radius1,radius2,height)''': Makes a cone with a given radii and height
* '''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.
* '''makeCylinder(radius,height)''': Makes a cylinder with a given radius and height.
* '''makeLine((x1,y1,z1),(x2,y2,z2))''': Makes a line of two points
* '''makeLine((x1,y1,z1),(x2,y2,z2))''': Makes a line from two points
* '''makePlane(length,width)''': Makes a plane with length and width
* '''makePlane(length,width)''': Makes a plane with length and width
* '''makePolygon(list)''': Makes a polygon of a list of points
* '''makePolygon(list)''': Makes a polygon from a list of points
* '''makeSphere(radius)''': Make a sphere with a given radius
* '''makeSphere(radius)''': Makes a sphere with a given radius
* '''makeTorus(radius1,radius2)''': Makes a torus with a given radii
* '''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.
See the [[Part API]] page for a complete list of available methods of the Part module.


Line 120: Line 142:
First we need to import the Part module so we can use its contents in python.
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:
We'll also import the Base module from inside the FreeCAD module:

<syntaxhighlight>
{{Code|code=
import Part
import Part
from FreeCAD import Base
from FreeCAD import Base
}}
</syntaxhighlight>

==== Creating a Vector ====
==== Creating a Vector ====
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most
important pieces of information when building shapes. They contain a 3 numbers
important pieces of information when building shapes. They usually contain three numbers
usually (but not necessarily always) the x, y and z cartesian coordinates. You
(but not necessarily always): the x, y and z cartesian coordinates. You
create a vector like this:
create a vector like this:

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

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
vectors are used everywhere. Part shapes also use another kind of point
representation, called Vertex, which is acually nothing else than a container
representation called Vertex which is simply a container
for a vector. You access the vector of a vertex like this:
for a vector. You access the vector of a vertex like this:

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

==== Creating an Edge ====
==== Creating an Edge ====
An edge is nothing but a line with two vertexes:
An edge is nothing but a line with two vertexes:

<syntaxhighlight>
{{Code|code=
edge = Part.makeLine((0,0,0), (10,0,0))
edge = Part.makeLine((0,0,0), (10,0,0))
edge.Vertexes
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
}}
</syntaxhighlight>

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

<syntaxhighlight>
{{Code|code=
vec1 = Base.Vector(0,0,0)
vec1 = Base.Vector(0,0,0)
vec2 = Base.Vector(10,0,0)
vec2 = Base.Vector(10,0,0)
line = Part.Line(vec1,vec2)
line = Part.LineSegment(vec1,vec2)
edge = line.toShape()
edge = line.toShape()
}}
</syntaxhighlight>

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

<syntaxhighlight>
{{Code|code=
edge.Length
edge.Length
> 10.0
> 10.0
edge.CenterOfMass
edge.CenterOfMass
> Vector (5, 0, 0)
> Vector (5, 0, 0)
}}
</syntaxhighlight>

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

<syntaxhighlight>
{{Code|code=
Part.show(edge)
Part.show(edge)
}}
</syntaxhighlight>

An object will be created in our FreeCAD document, and our "edge" shape
The show function creates an object in our FreeCAD document and assigns our "edge" shape
will be attributed to it. Use this whenever it's time to display your
creation on screen.
to it. Use this whenever it is time to display your creation on screen.


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

<syntaxhighlight>
{{Code|code=
edge1 = Part.makeLine((0,0,0), (10,0,0))
edge1 = Part.makeLine((0,0,0), (10,0,0))
edge2 = Part.makeLine((10,0,0), (10,10,0))
edge2 = Part.makeLine((10,0,0), (10,10,0))
Line 188: Line 224:
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)
Part.show(wire3)
}}
</syntaxhighlight>

Part.show(wire3) will display the 4 edges that compose our wire. Other
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:

<syntaxhighlight>
{{Code|code=
wire3.Length
wire3.Length
> 40.0
> 40.0
Line 200: Line 238:
wire2.isClosed()
wire2.isClosed()
> False
> False
}}
</syntaxhighlight>

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

<syntaxhighlight>
{{Code|code=
face = Part.Face(wire3)
face = Part.Face(wire3)
face.Area
face.Area
Line 217: Line 257:
face.isValid()
face.isValid()
> False
> False
}}
</syntaxhighlight>

Only faces will have an area, not wires nor edges.
Only faces will have an area, not wires nor edges.


==== Creating a Circle ====
==== Creating a Circle ====
A circle can be created as simply as this:
A circle can be created as simply as this:

<syntaxhighlight>
{{Code|code=
circle = Part.makeCircle(10)
circle = Part.makeCircle(10)
circle.Curve
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
}}
</syntaxhighlight>

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

{{Code|code=
ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.Vector(1,0,0))
ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.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))
}}
</syntaxhighlight>

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

{{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, Base.Vector(0,0,0), Base.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, Base.Vector(0,0,0), Base.Vector(0,0,1), 180, 360)
}}
</syntaxhighlight>

Both arc1 and arc2 jointly will make a circle. Angles should be provided in
Both arc1 and arc2 jointly will make a circle. Angles should be provided in
degrees, if you have radians simply convert them using formula:
degrees; if you have radians simply convert them using the formula:
degrees = radians * 180/PI or using python's math module (after doing import
degrees = radians * 180/PI or using python's math module (after doing import
math, of course):
math, of course):

<syntaxhighlight>
{{Code|code=
degrees = math.degrees(radians)
degrees = math.degrees(radians)
}}
</syntaxhighlight>

==== Creating an Arc along points ====
==== Creating an Arc along points ====
Unfortunately there is no makeArc function but we have Part.Arc function to
Unfortunately there is no makeArc function, but we have the Part.Arc function to
create an arc along three points. Basically it can be supposed as an arc
create an arc through three points. It creates an arc object
joining start point and end point along the middle point. Part.Arc creates
joining the start point to the end point through the middle point.
an arc object on which .toShape() has to be called to get the edge object,
The arc object's .toShape() function must be called to get an edge object,
the same way as when using Part.Line instead of Part.makeLine.
the same as when using Part.LineSegment instead of Part.makeLine.

<syntaxhighlight>
{{Code|code=
arc = Part.Arc(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0))
arc = Part.Arc(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0))
arc
arc
> <Arc object>
> <Arc object>
arc_edge = arc.toShape()
arc_edge = arc.toShape()
}}
</syntaxhighlight>

Arc only accepts Base.Vector() for points but not tuples. arc_edge is what
Arc only accepts Base.Vector() for points but not tuples. arc_edge is what
we want which we can display using Part.show(arc_edge). You can also obtain
we want which we can display using Part.show(arc_edge). You can also obtain
an arc by using a portion of a circle:
an arc by using a portion of a circle:

<syntaxhighlight>
{{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(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
arc = Part.Arc(c,0,pi)
arc = Part.Arc(circle,0,pi)
}}
</syntaxhighlight>

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


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

<syntaxhighlight>
{{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([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])
}}
</syntaxhighlight>

==== Creating a Bezier curve ====
==== Creating 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.)
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.)
<syntaxhighlight>

{{Code|code=
def makeBCurveEdge(Points):
def makeBCurveEdge(Points):
geomCurve = Part.BezierCurve()
geomCurve = Part.BezierCurve()
Line 285: Line 341:
edge = Part.Edge(geomCurve)
edge = Part.Edge(geomCurve)
return(edge)
return(edge)
}}
</syntaxhighlight>

==== Creating a Plane ====
==== Creating a Plane ====
A Plane is simply a flat rectangular surface. The method used to create one is
A Plane is simply a flat rectangular surface. The method used to create one is '''makePlane(length,width,[start_pnt,dir_normal])'''. By default
this: '''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)
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 z axis, while dir_normal = Vector(1,0,0) will create the
will create the plane facing in the positive z axis direction, while dir_normal = Vector(1,0,0) will create the
plane facing x axis:
plane facing in the positive x axis direction:

<syntaxhighlight>
{{Code|code=
plane = Part.makePlane(2,2)
plane = Part.makePlane(2,2)
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, Base.Vector(3,0,0), Base.Vector(0,1,0))
plane.BoundBox
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)
> BoundBox (3, 0, 0, 5, 0, 2)
}}
</syntaxhighlight>

BoundBox is a cuboid enclosing the plane with a diagonal starting at
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 in y axis is zero,
(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.
since our shape is totally flat.


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


==== Creating an ellipse ====
==== Creating an ellipse ====
There are several ways to create an ellipse:
To create an ellipse there are several ways:

<syntaxhighlight>
{{Code|code=
Part.Ellipse()
Part.Ellipse()
}}
</syntaxhighlight>

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

{{Code|code=
Part.Ellipse(Ellipse)
Part.Ellipse(Ellipse)
}}
</syntaxhighlight>

Create a copy of the given ellipse
Creates a copy of the given ellipse.
<syntaxhighlight>

{{Code|code=
Part.Ellipse(S1,S2,Center)
Part.Ellipse(S1,S2,Center)
}}
</syntaxhighlight>

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
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,
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.
and its minor radius is the distance between S2 and the major axis.

<syntaxhighlight>
{{Code|code=
Part.Ellipse(Center,MajorRadius,MinorRadius)
Part.Ellipse(Center,MajorRadius,MinorRadius)
}}
</syntaxhighlight>

Creates an ellipse with major and minor radii MajorRadius and MinorRadius,
Creates an ellipse with major and minor radii MajorRadius and MinorRadius,
and 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)

<syntaxhighlight>
{{Code|code=
eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0))
eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0))
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
</syntaxhighlight>
In the above code we have passed S1, S2 and center. Similarly to Arc,
Ellipse also creates an ellipse object but not edge, so we need to
convert it into edge using toShape() to display.


In the above code we have passed S1, S2 and center. Similar to Arc,
Note: Arc only accepts Base.Vector() for points but not tuples
Ellipse creates an ellipse object but not edge, so we need to
<syntaxhighlight>
convert it into an edge using toShape() for display.

Note: Arc only accepts Base.Vector() for points but not tuples.

{{Code|code=
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
</syntaxhighlight>

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


==== Creating a Torus ====
==== Creating a Torus ====
Using the method '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. By
Using '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''.
default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360.
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
Consider a torus as small circle sweeping along a big circle. Radius1 is the
radius of big cirlce, radius2 is the radius of small circle, pnt is the center
radius of the big cirlce, radius2 is the radius of the small circle, pnt is the center
of torus and dir is the normal direction. angle1 and angle2 are angles in
of the torus and dir is the normal direction. angle1 and angle2 are angles in
radians for the small circle, the last parameter angle is to make a section of
radians for the small circle; the last parameter angle is to make a section of
the torus:
the torus:

<syntaxhighlight>
{{Code|code=
torus = Part.makeTorus(10, 2)
torus = Part.makeTorus(10, 2)
}}
</syntaxhighlight>

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 cirlce radius 2)
(small circle radius 2)
<syntaxhighlight>

tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)
{{Code|code=
</syntaxhighlight>
tor=Part.makeTorus(10, 5, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 180)
The above code will create a slice of the torus
}}
<syntaxhighlight>

tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180)
The above code will create a slice of the torus.
</syntaxhighlight>

The above code will create a semi torus, only the last parameter is changed
{{Code|code=
tor=Part.makeTorus(10, 5, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 360, 180)
}}

The above code will create a semi torus; only the last parameter is changed.
i.e the angle and remaining angles are defaults. Giving the angle 180 will
i.e the angle and remaining angles are defaults. Giving the angle 180 will
create the torus from 0 to 180, that is, a half torus.
create the torus from 0 to 180, that is, a half torus.
Line 369: Line 445:
==== Creating a box or cuboid ====
==== Creating a box or cuboid ====
Using '''makeBox(length,width,height,[pnt,dir])'''.
Using '''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).

<syntaxhighlight>
{{Code|code=
box = Part.makeBox(10,10,10)
box = Part.makeBox(10,10,10)
len(box.Vertexes)
len(box.Vertexes)
> 8
> 8
}}
</syntaxhighlight>

==== Creating a Sphere ====
==== Creating a Sphere ====
Using '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. By default
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.
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
angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3
is the sphere diameter itself.
is the sphere diameter.

<syntaxhighlight>
{{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,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
}}
</syntaxhighlight>

==== Creating a Cylinder ====
==== Creating a Cylinder ====
Using '''makeCylinder(radius,height,[pnt,dir,angle])'''. By default
Using '''makeCylinder(radius,height,[pnt,dir,angle])'''. By default
pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360
pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360.
{{Code|code=
<syntaxhighlight>
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,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
}}
</syntaxhighlight>
==== Creating a Cone ====
==== Creating a Cone ====
Using '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. By default
Using '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. By default
pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360
pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360.
{{Code|code=
<syntaxhighlight>
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,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
}}
</syntaxhighlight>
== Modifying shapes ==
== Modifying shapes ==
There are several ways to modify shapes. Some are simple transformation operations
There are several ways to modify shapes. Some are simple transformation operations
such as moving or rotating shapes, other are more complex, such as unioning and
such as moving or rotating shapes, others are more complex, such as unioning and
subtracting one shape from another. Be aware that
subtracting one shape from another.


=== Transform operations ===
=== Transform operations ===
Line 408: Line 488:
Translating is the act of moving a shape from one place to another.
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:
Any shape (edge, face, cube, etc...) can be translated the same way:
{{Code|code=
<syntaxhighlight>
myShape = Part.makeBox(2,2,2)
myShape = Part.makeBox(2,2,2)
myShape.translate(Base.Vector(2,0,0))
myShape.translate(Base.Vector(2,0,0))
}}
</syntaxhighlight>
This will move our shape "myShape" 2 units in the x direction.
This will move our shape "myShape" 2 units in the x direction.


Line 417: Line 497:
To rotate a shape, you need to specify the rotation center, the axis,
To rotate a shape, you need to specify the rotation center, the axis,
and the rotation angle:
and the rotation angle:
{{Code|code=
<syntaxhighlight>
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180)
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180)
}}
</syntaxhighlight>
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.


Line 426: Line 506:
world. In a single matrix, you can set translation, rotation and scaling
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:
{{Code|code=
<syntaxhighlight>
myMat = Base.Matrix()
myMat = Base.Matrix()
myMat.move(Base.Vector(2,0,0))
myMat.move(Base.Vector(2,0,0))
myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi/2)
}}
</syntaxhighlight>
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 3 numbers, so those 2 lines do the same thing:
that take a vector can also take three numbers, so these two lines do the same thing:
{{Code|code=
<syntaxhighlight>
myMat.move(2,0,0)
myMat.move(2,0,0)
myMat.move(Base.Vector(2,0,0))
myMat.move(Base.Vector(2,0,0))
}}
</syntaxhighlight>
When our matrix is set, we can apply it to our shape. FreeCAD provides 2
Once our matrix is set, we can apply it to our shape. FreeCAD provides two
methods to do that: transformShape() and transformGeometry(). The difference
methods for doing that: transformShape() and transformGeometry(). The difference
is that with the first one, you are sure that no deformations will occur (see
is that with the first one, you are sure that no deformations will occur (see
"scaling a shape" below). So we can apply our transformation like this:
"scaling a shape" below). We can apply our transformation like this:
{{Code|code=
<syntaxhighlight>
myShape.trasformShape(myMat)
myShape.transformShape(myMat)
}}
</syntaxhighlight>
or
or
{{Code|code=
<syntaxhighlight>
myShape.transformGeometry(myMat)
myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
==== Scaling a shape ====
==== Scaling a shape ====
Scaling a shape is a more dangerous operation because, unlike translation
Scaling a shape is a more dangerous operation because, unlike translation
Line 453: Line 533:
can modify the structure of the shape. For example, scaling a circle with
can modify the structure of the shape. For example, scaling a circle with
a higher value horizontally than vertically will transform it into an
a higher value horizontally than vertically will transform it into an
ellipse, which behaves mathematically very differenty. For scaling, we
ellipse, which behaves mathematically very differently. For scaling, we
can't use the transformShape, we must use transformGeometry():
can't use the transformShape, we must use transformGeometry():
{{Code|code=
<syntaxhighlight>
myMat = Base.Matrix()
myMat = Base.Matrix()
myMat.scale(2,1,1)
myMat.scale(2,1,1)
myShape=myShape.transformGeometry(myMat)
myShape=myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
=== Boolean Operations ===
=== Boolean Operations ===


Line 465: Line 545:
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon
and is done like this:
and is done like this:
{{Code|code=
<syntaxhighlight>
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
sphere = Part.makeSphere(5,Base.Vector(5,0,0))
sphere = Part.makeSphere(5,Base.Vector(5,0,0))
diff = cylinder.cut(sphere)
diff = cylinder.cut(sphere)
}}
</syntaxhighlight>
==== Intersection ====
==== Intersection ====
The same way, the intersection between 2 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:
{{Code|code=
<syntaxhighlight>
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
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))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
common = cylinder1.common(cylinder2)
common = cylinder1.common(cylinder2)
}}
</syntaxhighlight>
==== Union ====
==== Union ====
Union is called "fuse" and works the same way:
Union is called "fuse" and works the same way:
{{Code|code=
<syntaxhighlight>
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
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))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
fuse = cylinder1.fuse(cylinder2)
fuse = cylinder1.fuse(cylinder2)
}}
</syntaxhighlight>
==== Section ====
==== Section ====
A Section is the intersection between a solid shape and a plane shape.
A Section is the intersection between a solid shape and a plane shape.
It will return an intersection curve, a compound with edges
It will return an intersection curve, a compound curve composed of edges.
{{Code|code=
<syntaxhighlight>
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
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))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
Line 498: Line 578:
<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>]
}}
</syntaxhighlight>
==== Extrusion ====
==== Extrusion ====
Extrusion is the act of "pushing" a flat shape in a certain direction resulting in
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":
a solid body. Think of a circle becoming a tube by "pushing it out":
{{Code|code=
<syntaxhighlight>
circle = Part.makeCircle(10)
circle = Part.makeCircle(10)
tube = circle.extrude(Base.Vector(0,0,2))
tube = circle.extrude(Base.Vector(0,0,2))
}}
</syntaxhighlight>
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:
{{Code|code=
<syntaxhighlight>
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(Base.Vector(0,0,2))
}}
</syntaxhighlight>
== Exploring shapes ==
== Exploring shapes ==
You can easily explore the topological data structure:
You can easily explore the topological data structure:
{{Code|code=
<syntaxhighlight>
import Part
import Part
b = Part.makeBox(100,100,100)
b = Part.makeBox(100,100,100)
Line 529: Line 609:
v = e.Vertexes[0]
v = e.Vertexes[0]
v.Point
v.Point
}}
</syntaxhighlight>
By typing the lines above in the python interpreter, you will gain a good
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
understanding of the structure of Part objects. Here, our makeBox() command
Line 542: Line 622:
do a discretization. In FreeCAD the edges are parametrized by their lengths.
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:
{{Code|code=
<syntaxhighlight>
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
}}
</syntaxhighlight>
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
position. That means if the edge is 100mm long the start position is 0 and
the end position 100.
the end position 100.
{{Code|code=
<syntaxhighlight>
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 561: Line 641:
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)
}}
</syntaxhighlight>
=== Using the selection ===
=== Using the selection ===
Here we see now how we can use the selection the user did in the viewer.
Here we see now how we can use the selection the user did in the viewer.
First of all we create a box and shows it in the viewer
First of all we create a box and show it in the viewer.
{{Code|code=
<syntaxhighlight>
import Part
import Part
Part.show(Part.makeBox(100,100,100))
Part.show(Part.makeBox(100,100,100))
Gui.SendMsgToActiveView("ViewFit")
Gui.SendMsgToActiveView("ViewFit")
}}
</syntaxhighlight>
Select now some faces or edges. With this script you can
Now select some faces or edges. With this script you can
iterate all selected objects and their sub elements:
iterate over all selected objects and their sub elements:
{{Code|code=
<syntaxhighlight>
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
print o.ObjectName
print o.ObjectName
Line 579: Line 659:
for s in o.SubObjects:
for s in o.SubObjects:
print "object: ",s
print "object: ",s
}}
</syntaxhighlight>
Select some edges and this script will calculate the length:
Select some edges and this script will calculate the length:
{{Code|code=
<syntaxhighlight>
length = 0.0
length = 0.0
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
Line 587: Line 667:
length += s.Length
length += s.Length
print "Length of the selected edges:" ,length
print "Length of the selected edges:" ,length
}}
</syntaxhighlight>
== Complete example: The OCC bottle ==
== Complete example: The OCC bottle ==
A typical example found in the
A typical example found in the
[http://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html#sec1 OpenCasCade Technology Tutorial]
[http://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html#sec1 OpenCasCade Technology Tutorial]
is how to build a bottle. This is a good exercise for FreeCAD too. In fact,
is how to build a bottle. This is a good exercise for FreeCAD too. In fact,
you can follow our example below and the OCC page simultaneously, you will
if you follow our example below and the OCC page simultaneously, you will
understand well how OCC structures are implemented in FreeCAD. The complete script
see how well OCC structures are implemented in FreeCAD. The complete script
below is also included in FreeCAD installation (inside the Mod/Part folder) and
below is also included in the FreeCAD installation (inside the Mod/Part folder) and
can be called from the python interpreter by typing:
can be called from the python interpreter by typing:
{{Code|code=
<syntaxhighlight>
import Part
import Part
import MakeBottle
import MakeBottle
bottle = MakeBottle.makeBottle()
bottle = MakeBottle.makeBottle()
Part.show(bottle)
Part.show(bottle)
}}
</syntaxhighlight>
=== The complete script ===
=== The complete script ===
Here is the complete MakeBottle script:
Here is the complete MakeBottle script:
{{Code|code=
<syntaxhighlight>
import Part, FreeCAD, math
import Part, FreeCAD, math
from FreeCAD import Base
from FreeCAD import Base

def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt1=Base.Vector(-myWidth/2.,0,0)
Line 616: Line 696:
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment1=Part.LineSegment(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
aSegment2=Part.LineSegment(aPnt4,aPnt5)
aEdge1=aSegment1.toShape()
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge2=aArcOfCircle.toShape()
Line 653: Line 733:
continue
continue
myBody = myBody.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
myBody = myBody.makeFillet(myThickness/12.0,myBody.Edges)
return myBody
return myBody

</syntaxhighlight>
el = makeBottle()
Part.show(el)
}}
=== Detailed explanation ===
=== Detailed explanation ===
{{Code|code=
<syntaxhighlight>
import Part, FreeCAD, math
import Part, FreeCAD, math
from FreeCAD import Base
from FreeCAD import Base
}}
</syntaxhighlight>
We will need,of course, the Part module, but also the FreeCAD.Base module,
We will need, of course, the Part module, but also the FreeCAD.Base module,
which contains basic FreeCAD structures like vectors and matrixes.
which contains basic FreeCAD structures like vectors and matrixes.
{{Code|code=
<syntaxhighlight>
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt1=Base.Vector(-myWidth/2.,0,0)
Line 671: Line 754:
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
}}
</syntaxhighlight>
Here we define our makeBottle function. This function can be called without
Here we define our makeBottle function. This function can be called without
arguments, like we did above, in which case default values for width, height,
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
and thickness will be used. Then, we define a couple of points that will be used
for building our base profile.
for building our base profile.
{{Code|code=
<syntaxhighlight>
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment1=Part.LineSegment(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
aSegment2=Part.LineSegment(aPnt4,aPnt5)
}}
</syntaxhighlight>
Here we actually define the geometry: an arc, made of 3 points, and two
Here we actually define the geometry: an arc, made of three points, and two
line segments, made of 2 points.
line segments, made of two points.
{{Code|code=
<syntaxhighlight>
aEdge1=aSegment1.toShape()
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
}}
</syntaxhighlight>
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. 3 edges (edges can be straight
shapes out of our construction geometry. Three edges (edges can be straight
or curved), then a wire made of those three edges.
or curved), then a wire made of those three edges.
{{Code|code=
<syntaxhighlight>
aTrsf=Base.Matrix()
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
myWireProfile=Part.Wire([aWire,aMirroredWire])
}}
</syntaxhighlight>
Until now we built only a half profile. Easier than building the whole profile
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 halfs together.
the same way, we can just mirror what we did and glue both halves together.
So we first create a matrix. A matrix is a very common way to apply transformations
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
to objects in the 3D world, since it can contain in one structure all basic
transformations that 3D objects can suffer (move, rotate and scale). Here,
transformations that 3D objects can undergo (move, rotate and scale).
after we create the matrix, we mirror it, and we create a copy of our wire
After we create the matrix we mirror it, then we create a copy of our wire
with that transformation matrix applied to it. We now have two wires, and
with that transformation matrix applied to it. We now have two wires, and
we can make a third wire out of them, since wires are actually lists of edges.
we can make a third wire out of them, since wires are actually lists of edges.
{{Code|code=
<syntaxhighlight>
myFaceProfile=Part.Face(myWireProfile)
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
aPrismVec=Base.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)
}}
</syntaxhighlight>
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. Doing so, we actually made a solid. Then we apply a nice little
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?
fillet to our object because we care about good design, don't we?
{{Code|code=
<syntaxhighlight>
neckLocation=Base.Vector(0,0,myHeight)
neckLocation=Base.Vector(0,0,myHeight)
neckNormal=Base.Vector(0,0,1)
neckNormal=Base.Vector(0,0,1)
Line 721: Line 804:
myNeckHeight = myHeight / 10
myNeckHeight = myHeight / 10
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)
}}
</syntaxhighlight>
Then, the body of our bottle is made, 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.
{{Code|code=
<syntaxhighlight>
myBody = myBody.fuse(myNeck)
myBody = myBody.fuse(myNeck)
}}
</syntaxhighlight>
The fuse operation, which in other apps is sometimes called union, is very
The fuse operation, which in other applications is sometimes called a union, is very
powerful. It will take care of gluing what needs to be glued and remove parts that
powerful. It will take care of gluing what needs to be glued and remove parts that
need to be removed.
need to be removed.
{{Code|code=
<syntaxhighlight>
return myBody
return myBody
}}
</syntaxhighlight>
Then, we return our Part solid as the result of our function. That Part solid,
Then, we return our Part solid as the result of our function.
{{Code|code=
like any other Part shape, can be attributed to an object in a FreeCAD document, with:
el = makeBottle()
<syntaxhighlight>
Part.show(el)
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
}}
myObject.Shape = bottle
Finally, we call the function to actually create the part, then make it visible.
</syntaxhighlight>

or, more simple:
<syntaxhighlight>
Part.show(bottle)
</syntaxhighlight>
==Box pierced==
==Box pierced==
Here a complete example of building a box pierced.
Here is a complete example of building a pierced box.


The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.
The construction is done one side at a time; when the cube is finished, it is hollowed out by cutting a cylinder through it.
{{Code|code=
<syntaxhighlight>
import Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4
import Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4
from math import sqrt, pi, sin, cos, asin
from math import sqrt, pi, sin, cos, asin
Line 794: Line 874:


Part.show(cut_part)
Part.show(cut_part)
}}
</syntaxhighlight>
== Loading and Saving ==
== Loading and Saving ==
There are several ways to save your work in the Part module. You can
There are several ways to save your work in the Part module. You can
Line 801: Line 881:


Saving a shape to a file is easy. There are exportBrep(), exportIges(),
Saving a shape to a file is easy. There are exportBrep(), exportIges(),
exportStl() and exportStep() methods availables for all shape objects.
exportStl() and exportStep() methods available for all shape objects.
So, doing:
So, doing:
{{Code|code=
<syntaxhighlight>
import Part
import Part
s = Part.makeBox(0,0,0,10,10,10)
s = Part.makeBox(0,0,0,10,10,10)
s.exportStep("test.stp")
s.exportStep("test.stp")
}}
</syntaxhighlight>
this will save our box into a STEP file. To load a BREP,
will save our box into a STEP file. To load a BREP,
IGES or STEP file, simply do the contrary:
IGES or STEP file:
{{Code|code=
<syntaxhighlight>
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("test.stp")
s.read("test.stp")
}}
</syntaxhighlight>
To convert an '''.stp''' in '''.igs''' file simply :
To convert an '''.stp''' file to an '''.igs''' file:
{{Code|code=
<syntaxhighlight>
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
}}
</syntaxhighlight>
Note that importing or opening BREP, IGES or STEP files can also be done
Note that importing or opening BREP, IGES or STEP files can also be done
directly from the File -> Open or File -> Import menu, while exporting
directly from the File Open or File Import menu, while exporting
is with File -> Export
can be done with File Export.


{{docnav|Mesh Scripting|Mesh to Part}}
{{docnav|Mesh Scripting|Mesh to Part}}


{{Userdocnavi}}
[[Category:Poweruser Documentation/pl]] [[Category:Python Code/pl]] [[Category:Tutorials/pl]]

<div class="mw-translate-fuzzy">
[[Category:Poweruser Documentation/pl]] [[Category:Python Code/pl]]
</div>

[[Category:Python Code]]




{{clear}}
{{clear}}
<languages/>

Revision as of 09:08, 8 March 2019

Mesh Scripting
Mesh to Part
Ćwiczenie
Temat
Programming
Poziom trudności
Intermediate
Czas wykonania
Autorzy
Wersja FreeCAD
Pliki z przykładami
Zobacz również
-


This page describes several methods for creating and modifying Part shapes from python. Before reading this page, if you are new to python, it is a good idea to read about python scripting and how python scripting works in FreeCAD.

Introduction

Here we will explain to you how to control the 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. 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.

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
Python classes of the Part module

Geometry

The geometric objects are the building block 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
  • ...... And soon some more

Topology

The following topological data types are available:

  • Compound A group of any type of topological object.
  • 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.

Quick example : Creating simple topology

Wire


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

Creating Geometry

First we have to create the distinct geometric parts of this wire. And we have to take care that the vertexes of the geometric parts are at the same position. Otherwise later on we might not be able to connect the geometric parts to a topology!

So we create first the points:

from FreeCAD import Base
V1 = Base.Vector(0,10,0)
V2 = Base.Vector(30,10,0)
V3 = Base.Vector(30,-10,0)
V4 = Base.Vector(0,-10,0)

Arc

Circle


To create an arc of circle we make a helper point and create the arc of circle through three points:

VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
# and the second one
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)

Line

Line


The line segment can be created very simple out of the points:

L1 = Part.LineSegment(V1,V2)
# and the second one
L2 = Part.LineSegment(V3,V4)

Note: in FreeCAD 0.16 Part.Line was used, for FreeCAD 0.17 Part.LineSegment has to be used

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

Make a prism

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

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

Show it all

Part.show(P)

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

Other make...() methods available:

  • makeBox(l,w,h): 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.

Importing the needed modules

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:

import Part
from FreeCAD import Base

Creating 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 = Base.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)

Creating an Edge

An edge is nothing but a line with two vertexes:

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 = Base.Vector(0,0,0)
vec2 = Base.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)

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

Creating 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

Creating a Face

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

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

Only faces will have an area, not wires nor edges.

Creating a Circle

A circle can be created as simply as 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, Base.Vector(10,0,0), Base.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 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:

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

Both arc1 and arc2 jointly will make a circle. Angles should be provided in degrees; if you have radians simply convert them using the formula: degrees = radians * 180/PI or using python's math module (after doing import math, of course):

degrees = math.degrees(radians)

Creating 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(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0))
arc
> <Arc object>
arc_edge = arc.toShape()

Arc only accepts Base.Vector() for points but not tuples. arc_edge is what we want which we can display using Part.show(arc_edge). You can also obtain an arc by using a portion of a circle:

from math import pi
circle = Part.Circle(Base.Vector(0,0,0),Base.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.

Creating 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([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])

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

Creating a Plane

A Plane is simply 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, Base.Vector(3,0,0), Base.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 Base.Vector() for start_pnt and dir_normal but not tuples.

Creating 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(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.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 but not edge, so we need to convert it into an edge using toShape() for display.

Note: Arc only accepts Base.Vector() for points but not tuples.

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

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

Creating 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 cirlce, 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 radians for the small circle; the last parameter angle 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, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 180)

The above code will create a slice of the torus.

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

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

Creating 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

Creating 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,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)

Creating 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,Base.Vector(20,0,0),Base.Vector(0,0,1),180)

Creating 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,Base.Vector(20,0,0),Base.Vector(0,0,1),180)

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

Transform operations

Translating 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(Base.Vector(2,0,0))

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

Rotating a shape

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

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

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

Generic transformations with matrixes

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 = Base.Matrix()
myMat.move(Base.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(Base.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)

Scaling 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 can't use the transformShape, we must use transformGeometry():

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

Boolean Operations

Subtraction

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

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

Intersection

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

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))
common = cylinder1.common(cylinder2)

Union

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

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))
fuse = cylinder1.fuse(cylinder2)

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

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(Base.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(Base.Vector(0,0,2))

Exploring 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 vertexes. Straight edges have only two vertexes, obviously.

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)

Using the selection

Here we see now how we can use the 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

Complete example: The OCC bottle

A typical example found in the OpenCasCade Technology Tutorial 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 complete script below is also 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)

The complete script

Here is the complete MakeBottle script:

import Part, FreeCAD, math
from FreeCAD import Base

def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
   aPnt1=Base.Vector(-myWidth/2.,0,0)
   aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
   aPnt3=Base.Vector(0,-myThickness/2.,0)
   aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
   aPnt5=Base.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=Base.Matrix()
   aTrsf.rotateZ(math.pi) # rotate around the z-axis
   
   aMirroredWire=aWire.transformGeometry(aTrsf)
   myWireProfile=Part.Wire([aWire,aMirroredWire])
   myFaceProfile=Part.Face(myWireProfile)
   aPrismVec=Base.Vector(0,0,myHeight)
   myBody=myFaceProfile.extrude(aPrismVec)
   myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges)
   neckLocation=Base.Vector(0,0,myHeight)
   neckNormal=Base.Vector(0,0,1)
   myNeckRadius = myThickness / 4.
   myNeckHeight = myHeight / 10
   myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)	
   myBody = myBody.fuse(myNeck)
   
   faceToRemove = 0
   zMax = -1.0
   
   for xp in myBody.Faces:
       try:
           surf = xp.Surface
           if type(surf) == Part.Plane:
               z = surf.Position.z
               if z > zMax:
                   zMax = z
                   faceToRemove = xp
       except:
           continue
   
   myBody = myBody.makeFillet(myThickness/12.0,myBody.Edges)
   
   return myBody

el = makeBottle()
Part.show(el)

Detailed explanation

import Part, FreeCAD, math
from FreeCAD import Base

We will need, of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrixes.

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

Here we define our makeBottle 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 actually 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=Base.Matrix()
   aTrsf.rotateZ(math.pi) # rotate around the z-axis
   aMirroredWire=aWire.transformGeometry(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 with that transformation matrix applied 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=Base.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=Base.Vector(0,0,myHeight)
   neckNormal=Base.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, which in other applications is sometimes called a union, 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 = makeBottle()
Part.show(el)

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

Box pierced

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 Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4
from math import sqrt, pi, sin, cos, asin
from FreeCAD import Base

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 = FreeCAD.Matrix()
myMat.rotateZ(math.pi/2)
face2.transformShape(myMat)
face2.translate(FreeCAD.Vector(size, 0, 0))

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

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

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

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

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

mySolid = Part.makeSolid(myShell)
mySolidRev = mySolid.copy()
mySolidRev.reverse()

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

cut_part = mySolidRev.cut(myCyl)

Part.show(cut_part)

Loading and Saving

There are several ways to save your work in the Part module. 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(), exportStl() and exportStep() methods available for all shape objects. So, doing:

import Part
s = Part.makeBox(0,0,0,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 an .stp 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

Note that importing or opening BREP, IGES or STEP files can also be done directly from the File → Open or File → Import menu, while exporting can be done with File → Export.

Mesh Scripting
Mesh to Part