Topological data scripting/ru: Difference between revisions

From FreeCAD Documentation
(Updating to match new version of source page)
Line 1: Line 1:
This page describes several methods for creating and modifying [[Part Module|Part shapes]] from python. Before reading this page, if you are new to python, it is a good idea to read about [[Introduction to Python|python scripting]] and [[FreeCAD Scripting Basics|how python scripting works in FreeCAD]].
== Введение ==


== Introduction ==
Здесь мы объясним вам как управлять [[Part Module/ru|Модулем Деталей]] напрямую из интепритатора python FreeCAD, или из любого внешнего сценария. Для уверенности , просмотрите раздел [[Scripting/ru|Написание Сценариев]] и страницу [[FreeCAD Scripting Basics/ru|Основ сценариев в FreeCAD]] если вам необходимо больше информации, о том как работает написание сценариев в FreeCAD.
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.


=== Class Diagram ===
Для первого использования функциональности модуля Деталей вы должны загрузить модуль Деталей в интепретатор:
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:
<code python>
[[Image:Part_Classes.jpg|center|Python classes of the Part module]]
import Part
</code>


=== Geometry ===
=== Диаграмма Классов ===
The geometric objects are the building block of all topological objects:
Это UML обзор наиболее важных классов модуля Деталей:
* '''Geom''' Base class of the geometric objects
[[Image:Part_Classes.jpg|center|Python классы содержащиеся в модуле Деталей]]
* '''Line''' A straight line in 3D, defined by starting point and and 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.
* '''GEOM''' Базовый класс геометрических объектов
* '''Compsolid''' A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids.
* '''LINE''' Прямая линия в 3D, задается начальной и конечной точкой
* '''Solid''' A part of space limited by shells. It is three dimensional.
* '''CIRCLE''' Окружность или дуга задается центром, начальной и конечной точкой
* '''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 ===
=== Топология ===
Доступны нижеследующие топологические типы данных:
* '''COMPOUND''' Группа из топологических объектов любого типа.
* '''COMPSOLID''' Составное твердое тело, как набор твердых тел соединенными гранями. Он расширяет понятие Ломаной кривой(WIRE) и оболочки(SHELL) для твердых тел.
* '''SOLID''' Часть пространства ограниченная оболочкой. Она трехмерная.
* '''SHELL''' Набор граней соединенных между собой через ребра. Оболочки могут быть открытыми или закрытыми.
* '''FACE''' В 2D это часть плоскости; в 3D это часть поверхности. Это геометрия ограничена (обрезана) по контуам. Она двухмерная.
* '''WIRE''' Набор ребер соединенных через вершины. Он может быть как открытым, так и закрытым в зависимости от того связаны ли крайние ребра или нет.
* '''EDGE''' Топологический элемент соответствующий ограниченной кривой. Ребро как правило ограничивается вершинами. Оно одномерное.
* '''VERTEX''' Топологический элемент соответствующий точке. Обладает нулевой размерность.
* '''SHAPE''' общий термин охватывающий все выше сказанное.


[[Image:Wire.png|right|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 ====
Вы легко можете создать базовый топологический объект с помощью методов "make...()" содержащихся в модуле Деталей:
First we have to create the distinct geometric parts of this wire.
b = Part.makeBox(100,100,100)
And we have to take care that the vertexes of the geometric parts
Part.show(b)
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:
Куча других доступных make...() методов:
<syntaxhighlight>
* makeBox(l,w,h,[p,d]) -- Создает коробку расположенную в точке p и в указанном направлении d с размерами (l,w,h). По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1)
from FreeCAD import Base
* makeCircle(radius,[p,d,angle1,angle2]) -- Создает окружность с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0 и angle2=360
V1 = Base.Vector(0,10,0)
* makeCompound(list) -- Создает составное тело из списка форм
V2 = Base.Vector(30,10,0)
* makeCone(radius1,radius2,height,[p,d,angle]) -- Создает конус с заданным радиусами и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
V3 = Base.Vector(30,-10,0)
* makeCylinder(radius,height,[p,d,angle]) -- Создает цилиндр с заданным радиусом и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
V4 = Base.Vector(0,-10,0)
* makeLine((x1,y1,z1),(x2,y2,z2)) -- Создает линию проходящую через две точки
</syntaxhighlight>
* makePlane(length,width,[p,d]) -- Создает плоскость с заданной длинной и шириной. По умолчанию p=Vector(0,0,0) и d=Vector(0,0,1)
==== Arc ====
* makePolygon(list) -- Создает многоугольник из списка точек
* makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Создает сферу с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=90 и angle3=360
* makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Создает тор по заданными радиусамi.По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=360 и angle3=360


[[Image:Circel.png|right|Circle]]
=== Подробные объяснения ===


To create an arc of circle we make a helper point and create the arc of
Сначала импортируем следующее:
circle through three points:
<syntaxhighlight>
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)
</syntaxhighlight>
==== Line ====


[[Image:Line.png|right|Line]]
>>> import Part
>>> from FreeCAD import Base


The line can be created very simple out of the points:
<syntaxhighlight>
L1 = Part.Line(V1,V2)
# and the second one
L2 = Part.Line(V4,V3)
</syntaxhighlight>
==== Putting all together ====
The last step is to put the geometric base elements together
and bake a topological shape:
<syntaxhighlight>
S1 = Part.Shape([C1,C2,L1,L2])
</syntaxhighlight>
==== Make a prism ====
Now extrude the wire in a direction and make an actual 3D shape:
<syntaxhighlight>
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0,0,10))
</syntaxhighlight>
==== Show it all ====
<syntaxhighlight>
Part.show(P)
</syntaxhighlight>
== Creating basic shapes ==
You can easily create basic topological objects with the "make...()"
methods from the Part Module:
<syntaxhighlight>
b = Part.makeBox(100,100,100)
Part.show(b)
</syntaxhighlight>
A couple of 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 a 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 of two points
* '''makePlane(length,width)''': Makes a plane with length and width
* '''makePolygon(list)''': Makes a polygon of a list of points
* '''makeSphere(radius)''': Make a sphere with a given radius
* '''makeTorus(radius1,radius2)''': Makes a torus with a 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:
<syntaxhighlight>
import Part
from FreeCAD import Base
</syntaxhighlight>
==== Creating a Vector ====
[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
usually (but not necessarily always) the x, y and z cartesian coordinates. You
create a vector like this:
<syntaxhighlight>
myVector = Base.Vector(3,2,0)
</syntaxhighlight>
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 acually nothing else than a container
for a vector. You access the vector of a vertex like this:
<syntaxhighlight>
myVertex = myShape.Vertexes[0]
print myVertex.Point
> Vector (3, 2, 0)
</syntaxhighlight>
==== Creating an Edge ====
An edge is nothing but a line with two vertexes:
<syntaxhighlight>
edge = Part.makeLine((0,0,0), (10,0,0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
</syntaxhighlight>
Note: You can also create an edge by passing two vectors:
<syntaxhighlight>
vec1 = Base.Vector(0,0,0)
vec2 = Base.Vector(10,0,0)
line = Part.Line(vec1,vec2)
edge = line.toShape()
</syntaxhighlight>
You can find the length and center of an edge like this:
<syntaxhighlight>
edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)
</syntaxhighlight>
==== Putting the shape on screen ====
So far we created an edge object, but it doesn't appear anywhere on screen.
This is because we just manipulated python objects here. The FreeCAD 3D scene
only displays what you tell it to display. To do that, we use this simple
method:
<syntaxhighlight>
Part.show(edge)
</syntaxhighlight>
An object will be created in our FreeCAD document, and our "edge" shape
will be attributed to it. Use this whenever it's time to display your
creation on screen.


==== Creating a Wire ====
<code python>
A wire is a multi-edge line and can be created from a list of edges
>>> vertex = Part.Vertex((1,0,0))
or even a list of wires:
</code>
<syntaxhighlight>
Вершина это точка созданная в x=1,y=0,z=0
edge1 = Part.makeLine((0,0,0), (10,0,0))
устанавливающая(задающая) объект вершины,вот так, вы можете найти её расположение:
edge2 = Part.makeLine((10,0,0), (10,10,0))
<code python>
wire1 = Part.Wire([edge1,edge2])
>>> vertex.Point
edge3 = Part.makeLine((10,10,0), (0,10,0))
Vector (1, 0, 0)
edge4 = Part.makeLine((0,10,0), (0,0,0))
</code>
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)
</syntaxhighlight>
Part.show(wire3) will display the 4 edges that compose our wire. Other
useful information can be easily retrieved:
<syntaxhighlight>
wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False
</syntaxhighlight>
==== 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)
<syntaxhighlight>
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
</syntaxhighlight>
Only faces will have an area, not wires nor edges.


====Как создать Ребро?====
==== Creating a Circle ====
A circle can be created as simply as this:

<syntaxhighlight>
Ребра не что иное как линия с двумя вершинами:
circle = Part.makeCircle(10)
<code python>
circle.Curve
>>> edge = Part.makeLine((0,0,0), (10,0,0))
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
>>> edge.Vertexes
</syntaxhighlight>
[<Vertex object at 01877430>, <Vertex object at 014888E0>]
If you want to create it at certain position and with certain direction:
</code>
<syntaxhighlight>
Примечание: Вы не можете создать ребро передав две вершины.
ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.Vector(1,0,0))
Вы можете узнать длинну и центр ребра, вот так:
ccircle.Curve
<code python>
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))
>>> edge.Length
</syntaxhighlight>
10.0
ccircle will be created at distance 10 from origin on x and will be facing
>>> edge.CenterOfMass
towards x axis. Note: makeCircle only accepts Base.Vector() for position
Vector (5, 0, 0)
and normal but not tuples. You can also create part of the circle by giving
</code>
start angle and end angle as:

<syntaxhighlight>
====Как создать ломанную кривую?====
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)
<code python>
</syntaxhighlight>
>>> edge1 = Part.makeLine((0,0,0), (10,0,0))
Both arc1 and arc2 jointly will make a circle. Angles should be provided in
>>> edge2 = Part.makeLine((10,0,0), (10,10,0))
degrees, if you have radians simply convert them using formula:
>>> wire1 = Part.Wire([edge1,edge2])
degrees = radians * 180/PI or using python's math module (after doing import
>>> edge3 = Part.makeLine((10,10,0), (0,10,0))
math, of course):
>>> edge4 = Part.makeLine((0,10,0), (0,0,0))
<syntaxhighlight>
>>> 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)
</code>
Part.show(wire3) будет отображать четыре лини как квадарат:
<code python>
>>> wire3.Length
40.0
>>> wire3.CenterOfMass
Vector (5, 5, 0)
>>> wire3.isClosed()
True
>>> wire2.isClosed()
False
</code>

====Как создать Грань?====

Действительны , только грани созданные из замкнутых ломаных.
В данном примере, wire3 замкнутая ломанная,а wire2 не замкнута (смотри выше)
<code python>
>>> 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
</code>
Только грани обладают поверхностью, а не ломанные и ребра.

====Как создать окружность?====

circle = Part.makeCircle(radius,[center,dir_normal,angle1,angle2]) -- Создает окружность с заданным радиусом

По умолчанию, center=Vector(0,0,0), dir_normal=Vector(0,0,1), angle1=0 and angle2=360.
Окружность может быть просто создана, как здесь:
<code python>
>>> circle = Part.makeCircle(10)
>>> circle.Curve
Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
</code>
Если вы хотите создать её с определенным положением и в определенном направлении
<code python>
>>> 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))
</code>
Окружность будет создана на расстоянии 10 от базовой(оригинальной) координаты х x и будет обращена в сторону оси x.
Примечание: makeCircleпринимает только тип Base.Vector() в качестве позиции и нормали а не кортеж.
Вы также можете создать часть окружности, задав угол начальный и конечный угол, как тут:
<code python>
>>> 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)
</code>
Обе arc1 и arc2 вместе составляют окружность.
Углы задаются в градусах, если вы хотите задать раддианами, просто преобразуйте используя формулу:
degrees = radians * 180/PI
или используя pythonовский math модуль (прежде, конечно, выполнив import math):
degrees = math.degrees(radians)
degrees = math.degrees(radians)
</syntaxhighlight>
==== Creating an Arc along points ====
Unfortunately there is no makeArc function but we have Part.Arc function to
create an arc along three points. Basically it can be supposed as an arc
joining start point and end point along the middle point. Part.Arc creates
an arc object on which .toShape() has to be called to get the edge object,
the same way as when using Part.Line instead of Part.makeLine.
<syntaxhighlight>
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()
</syntaxhighlight>
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:
<syntaxhighlight>
from math import pi
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
arc = Part.Arc(c,0,pi)
</syntaxhighlight>
Arcs are valid edges, like lines. So they can be used in wires too.


==== 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 along those points:
<syntaxhighlight>
lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])
</syntaxhighlight>
==== Creating a Bezier 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.)
<syntaxhighlight>
def makeBCurveEdge(Points):
geomCurve = Part.BezierCurve()
geomCurve.setPoles(Points)
edge = Part.Edge(geomCurve)
return(edge)
</syntaxhighlight>
==== Creating a Plane ====
A Plane is simply a flat rectangular surface. The method used to create one is
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)
will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the
plane facing x axis:
<syntaxhighlight>
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)
</syntaxhighlight>
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,
since our shape is totally flat.


Note: makePlane only accepts Base.Vector() for start_pnt and dir_normal but not tuples
К сожалению нет функции makeArc но мы обладаем функцией Part.Arc для созданимя дуги проходящей через три точки.
В основном эта может быть дуга соединящая начальную и конечную точку через средню точку.
Part.Arc создает объект дугу on which на котором .toShape() вызванная для получения объекта ребра,
которое обычно создается с помошью makeLine или makeCircle
<code python>
>>> 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()
</code>
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж.
arc_edge это то что мы хотим, мы можем показать его используя Part.show(arc_edge).
Если вы хотите небольшую часть круга, в качестве дуги, это тоже возможно:
<code python>
>>> from math import pi
>>> circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
>>> arc = Part.Arc(circle,0,pi)
</code>


==== Creating an ellipse ====
====Как создать многоугольник или линию по точкам?====
To create an ellipse there are several ways:
<syntaxhighlight>
Part.Ellipse()
</syntaxhighlight>
Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0)
<syntaxhighlight>
Part.Ellipse(Ellipse)
</syntaxhighlight>
Create a copy of the given ellipse
<syntaxhighlight>
Part.Ellipse(S1,S2,Center)
</syntaxhighlight>
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.
<syntaxhighlight>
Part.Ellipse(Center,MajorRadius,MinorRadius)
</syntaxhighlight>
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)
<syntaxhighlight>
eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0))
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.


Note: Arc only accepts Base.Vector() for points but not tuples
Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер.
<syntaxhighlight>
функция makePolygon берет список точек и создает ломанную по этим точкам:
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)
<code python>
Part.show(eli.toShape())
>>> lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])
</syntaxhighlight>
</code>
for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius


==== Creating a Torus ====
====Как создать плоскость?====
Using the method '''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 big cirlce, radius2 is the radius of small circle, pnt is the center
of 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:
<syntaxhighlight>
torus = Part.makeTorus(10, 2)
</syntaxhighlight>
The above code will create a torus with diameter 20(radius 10) and thickness 4
(small cirlce radius 2)
<syntaxhighlight>
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)
</syntaxhighlight>
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)
</syntaxhighlight>
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 ====
Плоскасть это ровная поверхность, в смысле 2D грань
Using '''makeBox(length,width,height,[pnt,dir])'''.
makePlane(length,width,[start_pnt,dir_normal]) -- Создает плоскость
По умолчанию start_pnt=Vector(0,0,0) и dir_normal=Vector(0,0,1).
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)
<syntaxhighlight>
dir_normal=Vector(0,0,1) создат плоскость нормальную к оси z.
box = Part.makeBox(10,10,10)
dir_normal=Vector(1,0,0) создат плоскость нормальную к оси х:
len(box.Vertexes)
<code python>
> 8
>>> plane = Part.makePlane(2,2)
</syntaxhighlight>
>>> plane
==== Creating a Sphere ====
<Face object at 028AF990>
Using '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. By default
>>> plane = Part.makePlane(2,2, Base.Vector(3,0,0), Base.Vector(0,1,0))
pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 and angle3=360.
>>> plane.BoundBox
angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3
BoundBox (3, 0, 0, 5, 0, 2)
is the sphere diameter itself.
</code>
<syntaxhighlight>
BoundBox является параллелепипед вмещающих плоскость с диагональю, начиная с (3,0,0) и концом в (5,0,2).
sphere = Part.makeSphere(10)
Здесь толщинаhe BoundBoxпо оси y равна нулю.
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
примечание: makePlane доступны только Base.Vector() для задания start_pnt и dir_normal а не кортежи
</syntaxhighlight>
==== 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
<syntaxhighlight>
cylinder = Part.makeCylinder(5,20)
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</syntaxhighlight>
==== 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
<syntaxhighlight>
cone = Part.makeCone(10,0,20)
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</syntaxhighlight>
== Modifying shapes ==
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
subtracting one shape from another. Be aware that


=== 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:
Part.Ellipse()
<syntaxhighlight>
myShape = Part.makeBox(2,2,2)
myShape.translate(Base.Vector(2,0,0))
</syntaxhighlight>
This will move our shape "myShape" 2 units in the x direction.


==== Rotating a shape ====
Создает эллипс с большой полуосью 2 и малой полуосью 1 с центром
To rotate a shape, you need to specify the rotation center, the axis,
в (0,0,0)
and the rotation angle:
<syntaxhighlight>
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.


==== Generic transformations with matrixes ====
Part.Ellipse(Ellipse)
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:
<syntaxhighlight>
myMat = Base.Matrix()
myMat.move(Base.Vector(2,0,0))
myMat.rotateZ(math.pi/2)
</syntaxhighlight>
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:
<syntaxhighlight>
myMat.move(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
methods to do 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). So we can apply our transformation like this:
<syntaxhighlight>
myShape.trasformShape(myMat)
</syntaxhighlight>
or
<syntaxhighlight>
myShape.transformGeometry(myMat)
</syntaxhighlight>
==== 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 differenty. For scaling, we
can't use the transformShape, we must use transformGeometry():
<syntaxhighlight>
myMat = Base.Matrix()
myMat.scale(2,1,1)
myShape=myShape.transformGeometry(myMat)
</syntaxhighlight>
=== Boolean Operations ===


==== Subtraction ====
Создает копию данного эллипса
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon
and is done like this:
<syntaxhighlight>
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)
</syntaxhighlight>
==== Intersection ====
The same way, the intersection between 2 shapes is called "common" and is done
this way:
<syntaxhighlight>
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)
</syntaxhighlight>
==== Union ====
Union is called "fuse" and works the same way:
<syntaxhighlight>
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)
</syntaxhighlight>
==== Section ====
A Section is the intersection between a solid shape and a plane shape.
It will return an intersection curve, a compound with edges
<syntaxhighlight>
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>]
</syntaxhighlight>
==== 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":
<syntaxhighlight>
circle = Part.makeCircle(10)
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
a disc, with a filled face, you will obtain a solid cylinder:
<syntaxhighlight>
wire = Part.Wire(circle)
disc = Part.makeFace(wire)
cylinder = disc.extrude(Base.Vector(0,0,2))
</syntaxhighlight>
== Exploring shapes ==
You can easily explore the topological data structure:
<syntaxhighlight>
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
</syntaxhighlight>
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 ===
Part.Ellipse(S1,S2,Center)
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.
Создаст эллипс с центров точке Center, где
That means you can walk an edge/curve by its length:
плоскость эллипса определяет Center, S1 и S2,
<syntaxhighlight>
это большая ось ззаданная Center и S1,
import Part
это больший радиус расстояние между Center и S1, и
box = Part.makeBox(100,100,100)
меньший радиус это расстояние между S2 и юольшей осью.
anEdge = box.Edges[0]

print anEdge.Length
Part.Ellipse(Center,MajorRadius,MinorRadius)
</syntaxhighlight>

Now you can access a lot of properties of the edge by using the length as a
Создает эллипс с большим и меньшим радиусом MajorRadius и
position. That means if the edge is 100mm long the start position is 0 and
MinorRadius, и расположенным в плоскости заданной точкой Center и
the end position 100.
нормалью (0,0,1)
<syntaxhighlight>

anEdge.tangentAt(0.0) # tangent direction at the beginning
<code python>
anEdge.valueAt(0.0) # Point at the beginning
>>> eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0))
anEdge.valueAt(100.0) # Point at the end of the edge
>>> Part.show(eli.toShape())
anEdge.derivative1At(50.0) # first derivative of the curve in the middle
</code>
anEdge.derivative2At(50.0) # second derivative of the curve in the middle
в приведенном выше коде мы ввели S1, S2 и center.
anEdge.derivative3At(50.0) # third derivative of the curve in the middle
Аналогично Дуге, Эллипс также создает объект, а не ребро,
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
так что мы должны превратить его в ребро используя toShape() для отображения
anEdge.curvatureAt(50.0) # the curvature

anEdge.normalAt(50) # normal vector at that position (if defined)
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж.
</syntaxhighlight>
<code python>
=== Using the selection ===
>>> eli = Part.Ellipse(Base.Vector(0,0,0),10,5)
Here we see now how we can use the selection the user did in the viewer.
>>> Part.show(eli.toShape())
First of all we create a box and shows it in the viewer
</code>
<syntaxhighlight>
Для верхнем конструкторе Эллипса мы ввели center, MajorRadius и MinorRadius
import Part

Part.show(Part.makeBox(100,100,100))
====Как создать Тор?====
Gui.SendMsgToActiveView("ViewFit")

</syntaxhighlight>
makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Создает тор с указаными радиусами и углами.
Select now some faces or edges. With this script you can
По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle1=360 и angle=360
iterate all selected objects and their sub elements:

<syntaxhighlight>
Расмотрим тор как маленький круг, вытянутый вдоль большого круга:
for o in Gui.Selection.getSelectionEx():

print o.ObjectName
radius1 это радиус большого круга, radius2 это радиус малого круга,
for s in o.SubElementNames:
pnt это центр тора и dir это направление нормали.
print "name: ",s
angle1 и angle2 углы в радианах для малого круга, создаст дугу
for s in o.SubObjects:
последний параметр angle создаст секцию(часть) тора:
print "object: ",s
<code python>
</syntaxhighlight>
>>> torus = Part.makeTorus(10, 2)
Select some edges and this script will calculate the length:
</code>
<syntaxhighlight>
В коде выше, был создан тор с диаметром 20(радиус 10) и толщиной 4(малая окружность радиусом 2)
length = 0.0
<code python>
for o in Gui.Selection.getSelectionEx():
>>> tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)
for s in o.SubObjects:
</code>
length += s.Length
В приведенном выше коде, создан кусочек тора
print "Length of the selected edges:" ,length
<code python>
</syntaxhighlight>
>>> tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180)
== Complete example: The OCC bottle ==
</code>
A typical example found on the
В приведенном выше коде, создан полу тор, изменен только последний параметр т.е. angle а остальные углы установлены по умолчанию.
[http://www.opencascade.org/org/gettingstarted/appli/ OpenCasCade Getting Started Page]

is how to build a bottle. This is a good exercise for FreeCAD too. In fact,
Подстановка угла 180 создаст тор от 0 до 180 т.е. половину
you can follow our example below and the OCC page simultaneously, you will

understand well how OCC structures are implemented in FreeCAD. The complete script
====Как создать блок или паралелепипед?====
below is also included in FreeCAD installation (inside the Mod/Part folder) and

can be called from the python interpreter by typing:
makeBox(length,width,height,[pnt,dir]) -- Создает блок расположенный в pnt с размерами (length,width,height)
<syntaxhighlight>

import Part
По умолчанию pnt=Vector(0,0,0) и dir=Vector(0,0,1)
import MakeBottle

bottle = MakeBottle.makeBottle()
<code python>
>>> box = Part.makeBox(10,10,10)
Part.show(bottle)
</syntaxhighlight>
>>> len(box.Vertexes)
=== The complete script ===
8
Here is the complete MakeBottle script:
</code>
<syntaxhighlight>

import Part, FreeCAD, math
====Как создать Сферу?====
from FreeCAD import Base

makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Создает сферу с заданным радиусом.
По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 и angle3=360.
angle1 и angle2 это вертиуальный минимум и максимум сферы(срезает часть сферы снизу или сверху),
angle3 определяет замкнутое ли это тело вращения или его секция
<code python>
>>> sphere = Part.makeSphere(10)
>>> hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
</code>

====Как создать Цилиндр?====

makeCylinder(radius,height,[pnt,dir,angle]) -- Создает цилиндр с указанным радиусом и высотой

По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1) и angle=360

<code python>
>>> cylinder = Part.makeCylinder(5,20)
>>> partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</code>

====Как создать Конус?====

makeCone(radius1,radius2,height,[pnt,dir,angle]) -- Создает конус с указанными радиусами и высотой

По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360
<code python>
>>> cone = Part.makeCone(10,0,20)
>>> semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</code>

=== Логические Операции ===

====Как вырезать одну форму из других?====

cut(...) - Вычисление различий задано в топологическом классе shape.
<code python>
>>> 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)
>>> diff.Solids
[<Solid object at 018AB630>, <Solid object at 0D8CDE48>]
>>> diff.ShapeType
'Compound'
</code>

====Как получить пересечение двух форм?====

common(...) - Пересечение задано в топологическом классе shape
<code python>
>>> 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)
</code>

====Как объединить две формы?====

fuse(...) - Объединение задано в топологическом классе shape
<code python>
>>> 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)
>>> fuse.Solids
[<Solid object at 0DA5B8A0>]
</code>

====Как получить сечение тела и заданой формы?====

section(...) - Сечение задано в топологическом классе shape.

Вернет секущую кривую, состоящую из ребер
<code python>
>>> 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>]
</code>

== Исследование Форм ==

Вы легко можете исследовать структуру топологических данных:
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

Если ввести строчку выше в интепритатор python , вы получите хорошее представление об устройстве Part объектов. Здесь, наша команда makeBox() создает твердое тело. Это тело, как и все Part тела, содержит грани. Грани, всегда содержат ломанные, которые являются набором ребер ограничивающих грань. Каждая грань обладает ровно одной замкнутой ломаной. В ломанной, мы можем посмотреть на отдельно на каждое ребро, и по краям каждого ребра , мы можем увидеть вершины. Очевидно, что прямые ребра обладают только двумя вершинами. Вершины модуля Part являются OCC(OpenCascade) формами, но они обладают атрибутом Point который возвращает FreeCAD вектор.

=== Исследование Рёбер ===
В случае ребра, которое является произвольной кривой, вы наверняка захотите произвести дискретизицию. В FreeCAD ребра задаются с помощью параметра длинны. Это означает что вы можете перемещатся вдоль ребра/кривой задавая длинну:
import Part
anEdge = Part.makeBox(100,100,100).Edges[0] # make a box with 100mm edge length и get the first edge
print anEdge.Length # get the length of the edge in mm (modeling unit)
Теперь вы получить доступ ко всем свойствам ребра, с помощью длинны или позиции. Это означает, что у ребра
в 100mm длинной, начальная позиция это 0 а конечная это 100.
anEdge.tangentAt(0.0) # касательная в начальной точке
anEdge.valueAt(0.0) # Начальная точка
anEdge.valueAt(100.0) # Конец ребра
anEdge.derivative1At(50.0) # Первая производная кривой в середине
anEdge.derivative2At(50.0) # Вторая производная по середине кривой
anEdge.derivative3At(50.0) # Третья производная кривой в средней точке
anEdge.centerOfCurvatureAt(50) # Расположение центра кривизны в данной позиции
anEdge.curvatureAt(50.0) # кривизна
anEdge.normalAt(50) # вектор нормали в данной точке(если он определен)

== Использование выделения(выбора) ==
Здесь мы увидим как можно использовать "выделение", которое пользователь сделал в программе просмотра.
прежде всего мы создадим блок и отобразим его в окне просмотра

import Part
Part.show(Part.makeBox(100,100,100))
Gui.SendMsgToActiveView("ViewFit")
Теперь выберем грани или ребра. С помощью этого сценария вы можете, поворить все выделенные объекты и их под элементы:
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

Выделим несколько ребер и этот сценарий подсчитает их сумарную длину:
length = 0.0
for o in Gui.Selection.getSelectionEx():
for s in o.SubObjects:
length += s.Length
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
print "Length of the selected edges:" ,length
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.Line(aPnt1,aPnt2)
aSegment2=Part.Line(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.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
return myBody
</syntaxhighlight>
=== Detailed explanation ===
<syntaxhighlight>
import Part, FreeCAD, math
from FreeCAD import Base
</syntaxhighlight>
We will need,of course, the Part module, but also the FreeCAD.Base module,
which contains basic FreeCAD structures like vectors and matrixes.
<syntaxhighlight>
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)
</syntaxhighlight>
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.
<syntaxhighlight>
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
</syntaxhighlight>
Here we actually define the geometry: an arc, made of 3 points, and two
line segments, made of 2 points.
<syntaxhighlight>
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
</syntaxhighlight>
Remember the difference between geometry and shapes? Here we build
shapes out of our construction geometry. 3 edges (edges can be straight
or curved), then a wire made of those three edges.
<syntaxhighlight>
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
</syntaxhighlight>
Until now we built only a half profile. Easier than building the whole profile
the same way, we can just mirror what we did, and glue both halfs together.
So 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 suffer (move, rotate and scale). Here,
after we create the matrix, we mirror it, and 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.
<syntaxhighlight>
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
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,
we can extrude it. Doing so, we actually made a solid. Then we apply a nice little
fillet to our object because we care about good design, don't we?
<syntaxhighlight>
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)
</syntaxhighlight>
Then, the body of our bottle is made, we still need to create a neck. So we
make a new solid, with a cylinder.
<syntaxhighlight>
myBody = myBody.fuse(myNeck)
</syntaxhighlight>
The fuse operation, which in other apps is sometimes called union, is very
powerful. It will take care of gluing what needs to be glued and remove parts that
need to be removed.
<syntaxhighlight>
return myBody
</syntaxhighlight>
Then, we return our Part solid as the result of our function. That Part solid,
like any other Part shape, can be attributed to an object in a FreeCAD document, with:
<syntaxhighlight>
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
myObject.Shape = bottle
</syntaxhighlight>
or, more simple:
<syntaxhighlight>
Part.show(bottle)
</syntaxhighlight>
==Box pierced==
Here a complete example of building a box pierced.


The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.
==Примеры==
<syntaxhighlight>
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)])
[[Image:Wire.png|right|Wire]]
Теперь мы создадим топологию из геометрических примитивов.
Для изучения мы используем деталь(part) , как показано на
картинке состоящую из четырех вершин, двух окружностей и двух линий.


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)
from FreeCAD import Base
V1 = Base.Vector(0,10,0)
face3.translate(FreeCAD.Vector(size, size, 0))
V2 = Base.Vector(30,10,0)
V3 = Base.Vector(30,-10,0)
V4 = Base.Vector(0,-10,0)


myMat.rotateZ(math.pi/2)
==== Arc ====
face4.transformShape(myMat)
[[Image:Circel.png|right|Circle]]
face4.translate(FreeCAD.Vector(0, size, 0))
Создавая дугу из окружности мы создаем вспомогательную точку и создаем дугу через три точки:
VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
# и the second one
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)


myMat = FreeCAD.Matrix()
==== Line ====
myMat.rotateX(-math.pi/2)
[[Image:Line.png|right|Line]]
face5.transformShape(myMat)
Линия может быть очень просто создана из точек:
L1 = Part.Line(V1,V2)
# и the second one
L2 = Part.Line(V4,V3)


face6.transformShape(myMat)
==== Соединяем все вместе ====
face6.translate(FreeCAD.Vector(0,0,size))
Последний шаг собираем все основные геометрические элементы вместе и получаем форму:
S1 = Part.Shape([C1,C2,L1,L2])


myShell = Part.makeShell([face1,face2,face3,face4,face5,face6])
==== Создание призмы ====
Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму:
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0,0,10))


mySolid = Part.makeSolid(myShell)
=== OCC бутыль ===
mySolidRev = mySolid.copy()
Типовой пример на [http://www.opencascade.org/org/gettingstarted/appli/ OpenCasCade Getting Started Page] можно узнать как построить бутыль.
mySolidRev.reverse()
Также это отличный пример для FreeCAD. В самом деле вы можете последовать нашему примеру изложенному ниже и странице OCC одновременно, вы лучше поймете как реализованы OCC структуры в FreeCAD.


myCyl = Part.makeCylinder(2,20)
Готовый сценарий описанный ниже, также включен в установленный FreeCAD (в папке Mod/Part ) и может быть вызван интепритатором python, вводом:
myCyl.translate(FreeCAD.Vector(size/2, size/2, 0))
import Part
import MakeBottle
bottle = MakeBottle.makeBottle()
Part.show(bottle)


cut_part = mySolidRev.cut(myCyl)
==== Готовый сценарий ====


Part.show(cut_part)
Здесь представлен готовый сценарий MakeBottle:
</syntaxhighlight>
== 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(),
import Part, FreeCAD, math
exportStl() and exportStep() methods availables for all shape objects.
from FreeCAD import Base
So, doing:
<syntaxhighlight>
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
import Part
aPnt1=Base.Vector(-myWidth/2.,0,0)
s = Part.makeBox(0,0,0,10,10,10)
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
s.exportStep("test.stp")
aPnt3=Base.Vector(0,-myThickness/2.,0)
</syntaxhighlight>
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
this will save our box into a STEP file. To load a BREP,
aPnt5=Base.Vector(myWidth/2.,0,0)
IGES or STEP file, simply do the contrary:
<syntaxhighlight>
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
import Part
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
s = Part.Shape()
s.read("test.stp")
aEdge1=aSegment1.toShape()
</syntaxhighlight>
aEdge2=aArcOfCircle.toShape()
To convert an '''.stp''' in '''.igs''' file simply :
aEdge3=aSegment2.toShape()
<syntaxhighlight>
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.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
return myBody

==== Подробные объяснения ====

import Part, FreeCAD, math
from FreeCAD import Base
Нам ,конечно, необходимы Part модуль, а также FreeCAD.Base модуль, который содержит основные структуры FreeCAD такие как векторы и матрицы.
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)
Здесь мы задаем нашу функцию makeBottle. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения.
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
Здесь мы фактически задаём геометрию: дугу, созданую по 3 точкам, и два линейных сегменты, созданные по 2 точкам.
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
Запомнили раличие между геометрией и формой? Здесь мы создаем форму из нашей строительной геометрии 3 рёбер (ребра могут быть прямыми или кривыми), затем из рёбер создается ломанная.
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
На данный момент мы построили только половину сечения. Проще, чем строить таким же образом целое сечение, мы можем просто отразить то что мы сделали и склеить две половинки. Сначала создадим матрицу(Нео ау). Матрица является распространенным способом произвести изменения над объектом в 3D пространстве, также она может содержать в одной структуре все базовые преобразования которые позволяют 3D объекты(перемещение, вращение и масштабирование). Здесь , после создания матрицы, мы отражаем её и создаем копию нашеё ломанной, применя к ней преобразование матрицой. Теперь мы получили две ломанные и мы можем создать из них третью ломаную, так как ломанные это всего лишь список ребер.
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)
Очень мощная операция слияния, которая обычно называется в других приложениях объединением. Она заботится о склеивании, о том что должно быть приклено и удаляет детали которые нужно удалить.
return myBody
Теперь мы получаем нашу твердотельную Деталь как результат нашей функции. Это Деталь - твердотельная, как и любая другая Деталь форма, может быть свзана с объектом в документе FreeCAD, с помошью:
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
myObject.Shape = bottle
или , ещё проще:
Part.show(bottle)

== Загрузка и Сохранение ==

Есть несколько путей чтобы сохранения вышей работы в Part модули. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL.

Сохраненить форму в файл , легко. Есть доступные для всех форм методы exportBrep(), exportIges(), exportStl() и exportStep() . Таким образом:
import Part
s = Part.makeBox(0,0,0,10,10,10)
s.exportStep("test.stp")
это сохранит наш блок в файл формата STEP. Для загрузки BREP, IGES или STEP файлов, просто сделайте наоборот:
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("test.stp")
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
Примечание этот импорт или открытие BREP, IGES or STEP файлов также можно сделать напрямую с помощью меню File -> Open or File -> Import. На данный момент экспорт ещё не включен, но будет там в ближайшее время.
</syntaxhighlight>
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
is with File -> Export


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


[[Category:Poweruser Documentation]]
{{languages/ru | {{en|Topological_data_scripting}} {{es|Topological_data_scripting/es}} {{fr|Topological_data_scripting/fr}} {{jp|Topological_data_scripting/jp}} {{se|Topological_data_scripting/se}} }}
[[Category:Python Code]]
[[Category:Tutorials]]


{{clear}}
[[Category:Poweruser Documentation/ru]]
<languages/>

Revision as of 16:43, 28 November 2014

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

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. 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 and 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
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
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
Line

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

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

Putting all together

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

S1 = Part.Shape([C1,C2,L1,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)

A couple of 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 a 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 of two points
  • makePlane(length,width): Makes a plane with length and width
  • makePolygon(list): Makes a polygon of a list of points
  • makeSphere(radius): Make a sphere with a given radius
  • makeTorus(radius1,radius2): Makes a torus with a 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 contain a 3 numbers usually (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 acually nothing else than 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.Line(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 screen. This is because we just manipulated python objects here. The FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:

Part.show(edge)

An object will be created in our FreeCAD document, and our "edge" shape will be attributed to it. Use this whenever it's 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 certain position and with 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 origin on x and will be facing towards x axis. Note: makeCircle only accepts Base.Vector() for position and normal but not tuples. You can also create part of the circle by giving start angle and end angle as:

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 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 Part.Arc function to create an arc along three points. Basically it can be supposed as an arc joining start point and end point along the middle point. Part.Arc creates an arc object on which .toShape() has to be called to get the edge object, the same way as when using Part.Line 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(c,0,pi)

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

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 along those points:

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

Creating a Bezier 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 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) will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the plane facing x axis:

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

To create an ellipse there are several ways:

Part.Ellipse()

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

Part.Ellipse(Ellipse)

Create 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, and 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. Similarly to Arc, Ellipse also creates an ellipse object but not edge, so we need to convert it into edge using toShape() to 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 the method 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 big cirlce, radius2 is the radius of small circle, pnt is the center of 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 cirlce 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 itself.

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, other are more complex, such as unioning and subtracting one shape from another. Be aware that

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 3 numbers, so those 2 lines do the same thing:

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

When our matrix is set, we can apply it to our shape. FreeCAD provides 2 methods to do 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). So we can apply our transformation like this:

 myShape.trasformShape(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 differenty. 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 2 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 with 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.makeFace(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 shows it in the viewer

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

Select now some faces or edges. With this script you can iterate 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 on the OpenCasCade Getting Started Page 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 understand well how OCC structures are implemented in FreeCAD. The complete script below is also included in 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.Line(aPnt1,aPnt2)
   aSegment2=Part.Line(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.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
   
   return myBody

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.Line(aPnt1,aPnt2)
   aSegment2=Part.Line(aPnt4,aPnt5)

Here we actually define the geometry: an arc, made of 3 points, and two line segments, made of 2 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. 3 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])

Until now we built only a half profile. Easier than building the whole profile the same way, we can just mirror what we did, and glue both halfs together. So 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 suffer (move, rotate and scale). Here, after we create the matrix, we mirror it, and 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. Doing so, we actually made 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)

Then, the body of our bottle is made, 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 apps is sometimes called 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. That Part solid, like any other Part shape, can be attributed to an object in a FreeCAD document, with:

myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
myObject.Shape = bottle

or, more simple:

Part.show(bottle)

Box pierced

Here a complete example of building a box pierced.

The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.

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 availables for all shape objects. So, doing:

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

this will save our box into a STEP file. To load a BREP, IGES or STEP file, simply do the contrary:

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

To convert an .stp in .igs file simply :

 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 is with File -> Export

Mesh Scripting
Mesh to Part