Topological data scripting/es

Introducción
Aquí le explicamos cómo controlar el Part Module] directamente desde el intérprete de Python FreeCAD, o desde cualquier guión externo. Asegúrese de navegar por la sección [[Scripting y las páginas FreeCAD Scripting Basics si necesita más información acerca de cómo funcionan los guiones, scripting, en python FreeCAD.

Antes de utilizar el módulo Parte, tiene que cargar el módulo en el intérprete:

Diagrama de clases
Ésta es una descripción UML sobre las clases más importante del módulo Parte:



Geometria
Los objetos geométricos son la piedra angular de todos los objetos topológicos:


 * GEOM clase base de los objetos geométricos
 * LINE Una línea recta en 3D, definido por el punto de inicio y el punto final
 * CIRCLE Círculo o segmento de círculo definido por un punto centro y los puntos de inicio y final


 * ...... Y pronto mas cosas ;-)

Topologia
Los siguientes tipos de datos topológicos están disponibles:
 * COMPOUND Un grupo de cualquier tipo de objetos topológicos.
 * COMPSOLID Un sólido compuesto es un grupo de sólidos concetados por sus caras. Es una extensión de las nociones de WIRE y SHELL en el ámbito de los sólido.
 * SOLID Una región del espacio limitada por shells. Es tridimensional.
 * SHELL Un conjunto de caras conectadas por sus bordes. Una shell puede ser abierta o cerrada.
 * FACE En 2D es parte de un plano; en 3D es parte de una superficie. Su geometría está limitada por sus contornos. Es un ente bidimensional.
 * WIRE Un grupo de bordes conectados por sus vértices. Puede tener un contorno abierto o cerrado, dependiendo que que sus bordes estén o no conectados.
 * EDGE Un elemento topológico que corresponde a una curva limitada. Un borde está normalmente limitado por vértices. Es un ente unidimensional.
 * VERTEX Un elemento topológico que se corresponde con un punto. Tiene dimensión cero.
 * SHAPE Un concepto genérico que abarca todos los anteriores.

Breve descripción
Usted puede crear fácilmente objetos topológicos simples con los métodos "make..." del Módulo Parte:

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

Otros métodos make... disponibles:
 * makeBox(l,w,h,[p,d]) -- construye una caja ubicada en p y apuntando en la dirección d con las dimensiones (l, w, h). Por defecto p es el vector (0,0,0) y d es el vector (0,0,1)


 * makeCircle(radius,[p,d,angle1,angle2]) -- Hace un círculo con un radio dado. Por defecto p = Vector (0,0,0), d = Vector (0,0,1), angle1 = 0 y angle2 = 360


 * makeCompound(list) -- Crea un compound a partir de una lista de shapes
 * makeCone(radius1,radius2,height,[p,d,angle]) -- Hace un cono con un radio y altura dados. Por defecto p=Vector(0,0,0), d=Vector(0,0,1) y angle=360
 * makeCylinder(radius,height,[p,d,angle]) -- Hace un cilindro con un radio y altura dados. Por defecto p=Vector(0,0,0), d=Vector(0,0,1) y angle=360


 * makeLine((x1,y1,z1),(x2,y2,z2)) -- Hace un alinea entre 2 puntos
 * makePlane(length,width,[p,d]) -- Hace un plano con longitud y anchura dados. Por defecto p=Vector(0,0,0) y d=Vector(0,0,1)
 * makePolygon(list) -- Hace un polígono con una lista de puntos
 * makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Hace una esfera con un radio dado. Por defecto p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=90 y angle3=360
 * makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Hace un toro con sus radios dados. Por defecto p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=360 y angle3=360

explicaciones detalladas
Primero importe lo siguiente:

>>> import Part >>> from FreeCAD import Base

¿Como crear un vértice?
vertex es un punto creado en x=1,y=0,z=0 Dado un objeto vertex, se puede encontrar su posición así:

¿Como crear un borde?
Un borde no es otra cosa mas que una linea entre dos vértices: Nota: No se puede crear un borde pasandole dos vértices. Se puede determinar la longitud y el centro de un borde así:

¿Como crear un Wire?
Un wire se puede crear a partir de una lista de bordes, o bien de una lista de wires: Part.show(wire3) mostrará 4 líneas como un cuadrado:

Como crear a Face?
Sólo serán válidas caras creadas a partir de alambres cerrados En este ejemplo, wire3 es un alambre cerrado pero wire2 no es un alambre cerrado (véase más arriba)

Only faces will have an area, not wires nor edges. Sólo las caras tiene área. los alambres y los bordes no tienen area.

Como crear un circulo?
circle = Part.makeCircle(radius,[center,dir_normal,angle1,angle2]) -- Hace un círculo con radio dado

Por defecto, center=Vector(0,0,0), dir_normal=Vector(0,0,1), angle1=0 y angle2=360. Crear un círculo es tan fácil como esto: Si desea crear en cierta posición y con cierta dirección ccircle se creará a distancia 10 en el eje x desde el origen, y estará orientado hacia el eje x. Nota: makeCircle solo acepta Base.Vector para posición y normal, pero no admite tuplas. Tambien puede crear parte de un círculo dando su ángulo de inicio y fin, así: juntando arc1 y arc2 obtendremos un círculo. Los ángulos deberá indicarse en grados, si tiene radianes simplemente convertirlos según la fórmula: degrees = radians * 180/PI o usando el módulo Python de matemáticas (después de importarlo, obviamente): degrees = math.degrees(radians)

¿Como crear un arco por varios puntos?
Desafortunadamente no hay ninguna función makeArc pero tenemos la función Part.Arc crear un arco a lo largo de tres puntos. Básicamente se puede suponer como un arco de unión entre el punto de partida y el punto final, pasando por el punto medio. Part.Arc crea un objeto arco en el que .toShape tiene que ser llamado para obtener el objeto borde, como el creado normalmente por makeLine o makeCircle

Nota: Arc solo acepta puntos como Base.Vector. No acepta tuplas en ese lugar.

arc_edge es lo que queríamos conseguir, y podemos visualizar utilizando Part.show (arc_edge). Si desea una pequeña parte de un círculo como un arco, también es posible:

How to create a polygon or line along points?
A line along multiple points is nothing but creating a wire with multiple edges. makePolygon function takes a list of points and creates a wire along those points:

How to create a plane?
Plane is a flat surface, meaning a face in 2D makePlane(length,width,[start_pnt,dir_normal]) -- Make a plane By default start_pnt=Vector(0,0,0) and dir_normal=Vector(0,0,1). dir_normal=Vector(0,0,1) will create the plane facing z axis. dir_normal=Vector(1,0,0) will create the plane facing x axis: 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. Note: makePlane only accepts Base.Vector for start_pnt and dir_normal but not tuples

How to create 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)

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

How to create a Torus?
makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Make a torus with a given radii and angles. By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle1=360 and angle=360

consider 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, to create an arc 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 i.e half

How to make a box or cuboid?
makeBox(length,width,height,[pnt,dir]) -- Make a box located in pnt with the dimensions (length,width,height)

By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)

How to make a Sphere?
makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given radius. 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

How to make a Cylinder?
makeCylinder(radius,height,[pnt,dir,angle]) -- Make a cylinder with a given radius and height

By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360

How to make a Cone?
makeCone(radius1,radius2,height,[pnt,dir,angle]) -- Make a cone with given radii and height

By default pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360

How to cut one shape from other?
cut(...) Difference of this and a given topo shape.

How to get common between two shapes?
common(...) Intersection of this and a given topo shape.

How to fuse two shapes?
fuse(...) Union of this and a given topo shape.

How to section a solid with given shape?
section(...) Section of this with a given topo shape.

will return a intersection curve, a compound with edges

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 line 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 exactly one closed wire. 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. Part Vertexes are OCC shapes, but they have a Point attribute which returns a nice FreeCAD Vector.

Exploring Edges
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 anEdge = Part.makeBox(100,100,100).Edges[0] # make a box with 100mm edge length and get the first edge print anEdge.Length # get the length of the edge in mm (modeling unit) 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

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

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

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)

Load and Save
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. At the moment exporting is still not possible that way, but should be there soon.