Topological data scripting/fr

= Topological data scripting/fr =

Cette page décrit différentes méthodes pour créer et modifier Part shapes de Python. Avant de lire cette page, si vous nouveau dans la programmation Python, vous pouvez vous diriger sur cette page d'introduction à Python et scripts de base en Python pour FreeCAD.

Introduction
Nous allons ici vous expliquer comment contrôler la boîte à outils (Part Module) ou de n'importe quel script externe, directement à partir de l'interpréteur Python inclus dans FreeCAD,. Assurez-vous de parcourir l'article de familiarisation et scripts de base si vous avez besoin de plus amples renseignements sur la façon dont les scripts Python fonctionnent dans FreeCAD.

Class Diagram
Ceci est un Unified Modeling Language (UML) de la classe la plus importante de Part Module:

Figures géométriques
Les objets géométriques sont la base de tous les objets topologiques :


 * Geom La classe de base des objets géométriques
 * Line Une ligne droite en 3D, défini par un point de départ et point d'arrivée
 * Circle Circle or circle segment défini par un point central, un point de départ et un point d'arrivée
 * ...... Et bien plus encore très rapidement ;-)

Topology
Sont aussi disponibles des données de type topologique:


 * Compound Groupe de types différents d'objets topologiques.
 * Compsolid Un groupe de solides reliés par leurs faces. C'est un concept des notions de WIRE (filaire,bord..) et SHELL (coquille,enveloppe) des solides.
 * Solid Une portion de l'espace limité par son enveloppe. Il est en 3 dimensions.
 * Shell Un groupe de faces reliés par leurs bords.Un "SHELL" peut être ouvert ou fermé.
 * Face En 2D, c'est une surface plane; en 3D, c'est une seule face du volume. Sa géométrie est coupée par des contours. Il est en deux dimensions.
 * Wire Un ensemble relié par ses VERTEX (sommets). Il peut être de contour ouvert ou fermé suivant si les sommets sont reliés ou non.
 * Edge Elément topologique correspondant à une courbe retenue. Un "Edge" est généralement limité par des sommets. Il a une dimension.
 * Vertex Elément topologiques correspondant à un point. Il n'a pas de dimension.
 * Shape Est le terme générique pour traduire tout ce qui précède.

Exemple rapide : Création topologique simple
Nous allons créer une topologie avec une géométrie toute simple. Nous devrons veiller à ce que les sommets des pièces géométriques soient à la même position, quatre sommets, deux cercles et deux lignes.

Création de la géométrie
Nous devons d'abord créer les parties distinctes géométriques en filaire. Nous devons veiller à ce que tous les sommets des pièces géométriques qui vont êtres raccordées soient à la même position. Sinon, plus tard nous pourrions ne pas être en mesure de relier les pièces géométriques en une topologie! Donc, nous créons d'abord les 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
Pour créer un arc de cercle, nous créons un point de repère puis nous créons l'arc de cercle passant par trois points:

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

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

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

Tout relier
La dernière étape consiste à relier les éléments géométriquement ensemble, et façonner une forme topologique:

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

Construire un prisme
Maintenant nous allons extruder notre forme filaire dans une direction, et créer une forme en 3 Dimensions:

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

Affichons le tout
Part.show(P)

Création de formes simples
Vous pouvez créer facilement des formes topologiques avec "make..." qui est une méthode du "Module Part":

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

La combinaison de make... avec d'autres methodes sont disponibles:


 * makeBox(l,w,h): Construit un cube et pointe sur p dans la direction d et de dimensions (longueur,largeur,hauteur).
 * makeCircle(radius): Construit un cercle de rayon (r).
 * makeCone(radius1,radius2,height): Construit un cône de (rayon1,rayon2,hauteur).
 * makeCylinder(radius,height): Construit un cylindre de (rayon,hauteur).
 * makeLine((x1,y1,z1),(x2,y2,z2)): Construit une ligne aux coordonnées (x1,y1,z1),(x2,y2,z2) dans l'espace 3D.
 * makePlane(length,width): Construit un rectangle de (longueur,largeur).
 * makePolygon(list): Construit un polygone (liste de points).
 * makeSphere(radius): Construit une sphère de (rayon).
 * makeTorus(radius1,radius2): Construit un tore de (rayon1,rayon2).

La liste complète des API du module est sur la page Part API.

Importer les modules nécessaires
Nous avons d'abord besoin d'importer le module Part afin que nous puissions utiliser son contenu Python. Nous allons également importer le module Base à l'intérieur du module de FreeCAD:

import Part from FreeCAD import Base

Création d'un Vecteur
Les Vecteurs sont l'une des informations les plus importantes lors de la construction des formes géométriques. Ils contiennent habituellement 3 nombres (mais pas toujours) les coordonnées cartésiennes x, y et z. Vous pouvez créez un vecteur comme ceci:

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

Nous venons de créer un vecteur de coordonnées x = 3, y = 2, z = 0. Dans le module Part, les vecteurs sont utilisés partout. Le module Part utilise aussi une autre façon de représenter un point, appelé Vertex, qui n'est actuellement rien d'autre qu'un conteneur pour un vecteur. Vous pouvez accéder aux vecteurs d'un sommet comme ceci:

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

Création d'une arête
Une arête (bord) n'est rien d'autre qu'une ligne avec deux Vertex (sommets):

edge = Part.makeLine((0,0,0), (10,0,0)) edge.Vertexes > [, ]

PS: Vous pouvez aussi créer un arête en donnant deux Vecteurs:

vec1 = Base.Vector(0,0,0) vec2 = Base.Vector(10,0,0) line = Part.Line(vec1,vec2) edge = line.toShape

Vous pouvez trouver la longueur et le centre d'une arête comme ceci:

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 > [, , , ] 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_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 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 > 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,angle1=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

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.transformGeometry(myMat)

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

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)

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

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