Topological data scripting/sv

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.

Introduktion
Här kommer vi att förklara hur du kontrollerar Del Modulen direkt från FreeCADs python tolk, eller från ett externt skript. Titta igenom Skript avsnittet och FreeCAD Skript grunder sidorna om du behöver mer information om hur python skript fungerar i FreeCAD.

För att kunna använda Delmodulens funktioner så måste du ladda Del modulen i tolken:

Klass Diagram
Detta är en UML översikt över de viktigaste klasserna i Del modulen:



Geometri
De geomtriska objekten är byggblocken för alla topologiska objekt:


 * GEOM Basklass för geometriska objekt


 * LINE En rak linje i 3D, definierad av en start- och en slutpunkt


 * CIRCLE Cirkel eller cirkelsegment som definieras av en centrumpunkt, start- och en slutpunkt


 * ...... Och snart lite mer

Topologi
Följande topologiska datatyper finns tillgängliga:


 * COMPOUND En grupp av valfri typ av topologiska objekt.
 * COMPSOLID En kompositsolid är ett set av solider ihopkopplade genom dess ytor. Det expanderar begreppen WIRE och SHELL till solider.
 * SOLID En rymd som är begränsad av skal. Den är tredimensionell.
 * SHELL Ett set av ytor ihopkopplade genom dess kanter. Ett skal kan vara öppet eller slutet.
 * FACE I 2D så är det en del av ett plan; i 3D är det en del av en yta. Dess geometri är begränsad (trimmad) av konturer. Den är tvådimensionell.
 * WIRE Ett set av kanter som är ihopkopplade genom dess hörn. Det kan vara en öppen eller sluten kontur beroende på om kanterna är ihoplänkade eller inte.
 * EDGE Ett topologiskt element som motsvarar en begränsad kurva. En kant är vanligtvis begränsad av hörn. Det har en dimension.
 * VERTEX Ett topologiskt element som motsvarar en punkt. Dess dimension är noll.
 * SHAPE En allmän term som täcker allt ovan.

Quick example : Creating simple topology


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:

Arc


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

Line


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

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

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

Kort beskrivning
Du kan lätt skapa enkla topologiska objekt med "make..." metoden från Del Modulen: Några andra make... metoder fom finns:


 * makeBox(l,w,h,[p,d]) -- Skapa en låda placerad i p och pekar i riktningen d med dimensionerna (l,w,h). Som standard är p Vektor(0,0,0) och d är Vektor(0,0,1)
 * makeCircle(radius,[p,d,angle1,angle2]) -- Skapa en cirkel med en given radie. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) angle1=0 och angle2=360
 * makeCompound(list) -- Skapar en compound från en lista med former (shapes)
 * makeCone(radius1,radius2,height,[p,d,angle]) -- Skapa en kon med given radie och höjd. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) och angle=360
 * makeCylinder(radius,height,[p,d,angle]) -- Skapa en cylinder med given radie och höjd. Som standard är p Vektor(0,0,0), d är Vektor(0,0,1) och angle=360
 * makeLine((x1,y1,z1),(x2,y2,z2)) -- Skapa en linje mellan två punkter
 * makePlane(length,width,[p,d]) -- Skapa ett plan med längd och bredd. med given radie och höjd. Som standard är p Vektor(0,0,0), och d är Vektor(0,0,1)
 * makePolygon(list) -- Skapa en polygon från en lista med punkter
 * makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Skapa en sfär med given radie. Som standard är p Vektor(0,0,0), d Vektor(0,0,1), angle1=0, angle2=90 och angle3=360
 * makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Skapa en torus med given radie. Som standard är p Vektor(0,0,0), d Vektor(0,0,1), angle1=0, angle2=360 och angle3=360

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

Detaljerade förklaringar
Importera först följande:

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

Hur skapar man en kant?
En kant är inget annat än en linje med två hörn: Notera: Du kan inte skapa en kant som passerar två hörn. Du kan hitta en kants längd och centrum så här:

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

Hur skapar man en tråd?
en tråd kan skapas från en lista med kanter eller en lista med trådar: Part.show(wire3) kommer att visa fyra linjer som bildar en kvadrat:

Hur skapar man en yta?
Endast ytor som skapats av stängda trådar är giltiga.

I detta exempel, så är wire3 en stängd tråd men wire2 är inte det (se ovan) Endast ytor har en area, inte trådar eller kanter.

Hur skapar man en cirkel?
circle = Part.makeCircle(radius,[center,dir_normal,angle1,angle2]) -- Skapa en cirkel med en given radie

Som standard är, center=Vektor(0,0,0), dir_normal=Vektor(0,0,1), angle1=0 och angle2=360.

En cirkel kan skapas så här: Om du vill skapa den vid en viss position och med en viss riktning cirkeln kommer att skapas med en distans 10 från nollpunkten i x och kommer att vara vänd mot x axeln.

Notera: makeCircle accepterar endast Base.Vector men inte tupler.

Du kan också skapa en cirkelbåge genom att ge start- och slutvinkel: Både arc1 och arc2 kommer tillsammans skapa en cirkel.

Vinklar ska anges i grader, om du har radianer, konvertera det genom att använda formeln:

Grader = radianer * 180/PI

eller genom att använda python's math modul (efter att du importerat math, förstås):

grader = math.degrees(radianer)

Hur skapar man en cirkelbåge längs punkter?
Olyckligtvis så finns det ingen makeArc funktion men vi har Part.Arc funktionen för att skapa en cirkelbåge längs tre punkter.

Det kan antas vara en cirkelbåge som förenar start- och slutpunkt genom mittenpunkten.

Part.Arc skapar ett arc objekt på vilken .toShape måste kallas för att få kant objektet,

vilket i allmänhet skapas av makeLine eller makeCircle Notera: Arc accepterar endast Base.Vector för punkter men inte tupler.

arc_edge är vad vi vill ha, vilken vi kan visa med Part.show(arc_edge).

Om du vill ha en liten del av en cirkel som en cirkelbåge, så är det också möjligt: Arcs are valid edges, like lines. So they can be used in wires too.

Hur skapar man en polygon eller linje längs punkter?
En linje längs multipla punkter är inget annat än att skapa en tråd med multipla kanter.

makePolygon funktionen tar en lista med punkter och skapar en tråd längs dessa punkter:

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

Hur skapar man ett plan?
Ett plan är en platt yta, alltså en yta i 2D

makePlane(length,width,[start_pnt,dir_normal]) -- Skapa ett plan

Som standard start_pnt=Vector(0,0,0) och dir_normal=Vector(0,0,1).

dir_normal=Vector(0,0,1) kommer att skapa ett plan vinkelrätt mot z axeln.

dir_normal=Vector(1,0,0) kommer att skapa ett plan vinkelrätt mot x axeln: 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: Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0) Create a copy of the given ellipse 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. 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) 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 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: The above code will create a torus with diameter 20(radius 10) and thickness 4 (small cirlce radius 2) The above code will create a slice of the torus 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)

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.

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

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

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

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:

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

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

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

Section
A Section is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound with 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": 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:

Exploring shapes
You can easily explore the topological data structure: 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: 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.

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 Select now some faces or edges. With this script you can iterate all selected objects and their sub elements: Select some edges and this script will calculate the 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:

The complete script
Here is the complete MakeBottle script:

Detailed explanation
We will need,of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrixes. 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. Here we actually define the geometry: an arc, made of 3 points, and two line segments, made of 2 points. 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. 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. 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? Then, the body of our bottle is made, we still need to create a neck. So we make a new solid, with a cylinder. 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. 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: or, more simple:

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.

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: this will save our box into a STEP file. To load a BREP, IGES or STEP file, simply do the contrary: To convert an .stp in .igs file simply : 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