Topological data scripting/zh-cn

本页描述了几种利用python来创建与修改零件形状（Part shapes）的方法. 如果您是python新手，请在阅读本页之前，先去浏览python脚本与如何在FreeCAD中运行python脚本.

概述
我们将在本文中向您解释如何直接用FreeCAD的Python解释器来控制零件模块，或者从任意外部脚本来实现这一点. 关于拓扑数据脚本的基本描述位于零件模块的概念介绍. 如果您需要了解关于FreeCAD中python脚本工作原理的更多信息，请一定阅读脚本一节与FreeCAD脚本基础页面.

类图
这是零件模块中最关键类的 统一建模语言（Unified Modeling Language (UML)）概述：

几何图形
这些几何图形对象是一切拓扑对象的基石：
 * Geom 几何图形对象的基类
 * Line 3D空间中的直线段，由起始点与终点定义而成
 * Circle 由中心点、起始点与终点定义的圆形或部分圆环段（circle segment）
 * ...... 以及后续更多的几何图形

拓扑
FreeCAD中有下列可用的拓扑数据类型：
 * 复合（Compound）对象 一组任意类型的拓扑对象.
 * 组合实体（Compsolid） 一个复合实体是一组由其面连接起来的实体. 它会将连线（WIRE）与壳（SHELL）扩展为实体.
 * 实体（Solid） 由壳界定的部分空间. 实体是3D对象.
 * 壳（Shell） 一组由其边连接起来的面. 一个壳可以是开放或闭合的.
 * 面（Face） 在2D空间中，它是部分平面；而在3D空间中，它是部分表面. 面的几何图形由轮廓来约束（调整）. 面是2D对象.
 * 连线（Wire） 一组由其顶点连接起来的边. 连线可以是开放或闭合的轮廓，这取决于其中的边是否互连.
 * 边（Edge） 一种对应于约束曲线的拓扑元素. 一条边通常受其顶点限制. 边是一种1D对象.
 * 顶点（Vertex） 一种对应于点的拓扑元素. 顶点是零维对象.
 * 几何形状（Shape） 一种涵盖上述所有对象的通称.

简易示例 ：创建简单拓扑结构


现在，我们将通过构造简单的几何图形来创建对应的拓扑. 就用我们在图中看到的零件为例，它由4个顶点，2个半圆以及2条线段构成.

创建几何图形
首先，我们必须创建此连线中的不同几何图形部分. 而且，还要小心处理几何图形中位于相同位置的不同顶点. 否则，我们随后可能无法将这些几何图形连接为一个拓扑结构.

因此，我们先来创建其中的点：

弧


为了创建圆周上的弧，我们要做一个辅助点，并通过圆周上的3个点来创建对应的弧：

线段


众所周知，两点定一线段：

请注意：在FreeCAD 0.16版中使用的是Part.Line，而对于FreeCAD 0.17版则必须使用Part.LineSegment

合而为一
最后一步就是将上述基本几何元素放在一起，并烘焙出一个拓扑形状：

制作一个外框
现在令连线在同一方向上挤压成型，构造一个实际的3D图形：

创建基本的几何形状
您可以利用零件模块中的"make..."方法来轻松地创建一个基础的拓扑对象.

其他可用的make...方法： 请参考Part API页来查阅零件模块中的完整可用方法列表.
 * makeBox(l,w,h): 在点p（？）处创建一个维数为(l,w,h)且指向方向d（？）的立方体
 * makeCircle(radius): 以指定的半径创建一个圆形
 * makeCone(radius1,radius2,height): 以指定的两个半径与高度创建一个圆锥体（圆台）
 * makeCylinder(radius,height): 以指定的半径与高度创建一个圆柱体
 * makeLine((x1,y1,z1),(x2,y2,z2)): 根据两点创建一条线段
 * makePlane(length,width): 利用指定的长度与宽度创建一个平面
 * makePolygon(list): 根据指定的点集创建一个多边形
 * makeSphere(radius): 利用指定的半径创建一个球体
 * makeTorus(radius1,radius2): 利用指定的两个半径创建一个圆环体

导入所需的模块
首先，我们需要导入零件（Part）模块，继而通过python使用其中提供的内容. 另外，我们也将从FreeCAD模块中导入基础（Base）模块：

创建一个向量
在构建几何图形的过程中， 向量 是提供最关键信息的对象类型之一. 向量属性中通常都有3个数字（但并非总是如此）：即直角坐标系中的3种坐标分量：x、y、z. 您可以按下列方式来创建一个向量：

我们刚刚在x=3, y=2, z=0坐标处创建了一个向量. 在零件模块中，到处都能看到向量的身影. 构建零件形状的过程中，也会用到另一种名为顶点的点表示法，它是一种向量的简易容器. 您可像下面那样来访问一个点的向量：

创建一条边
一条边不过是具有两个顶点的线段：

请注意，您也可以通过输入两个向量来创建一条边：

您能通过下列方式来查看一条边的长度与中点：

将图形显示在屏幕上
到目前为止，我们已经创建了一个边对象，但是它却并没有出现在屏幕上. 这是因为：只有在您告诉FreeCAD要呈现什么内容之后，它才会显示出对应的3D场景. 为此，我们要通过下列简单函数来实现这一点：

此show函数在我们当前的FreeCAD文档中创建了一个对象，并为之赋予此前创建的"edge"几何形状. 每当需要在屏幕上显示您所创建的对象们时，使用此函数即可.

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:

Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved:

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)

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

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

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

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

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

Creating an Arc along points
Unfortunately there is no makeArc function, but we have the Part.Arc function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's .toShape function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine.

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

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

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

Creating a Bézier curve
Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve from a series of FreeCAD.Vector points. (Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0.)

Creating a Plane
A Plane is simply a flat rectangular surface. The method used to create one is makePlane(length,width,[start_pnt,dir_normal]). By default start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Using dir_normal = Vector(0,0,1) will create the plane facing in the positive z axis direction, while dir_normal = Vector(1,0,0) will create the plane facing in the positive x axis direction:

BoundBox is a cuboid enclosing the plane with a diagonal starting at (3,0,0) and ending at (5,0,2). Here the BoundBox thickness along the y axis is zero, since our shape is totally flat.

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

Creating an ellipse
There are several ways to create an ellipse:

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

Creates 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, located in the plane defined by Center and the normal (0,0,1)

In the above code we have passed S1, S2 and center. Similar to Arc, Ellipse creates an ellipse object but not edge, so we need to convert it into an edge using toShape for display.

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

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

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

The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle 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.

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

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 three numbers, so these two lines do the same thing:

Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: transformShape and transformGeometry. The difference is that with the first one, you are sure that no deformations will occur (see "scaling a shape" below). We can apply our transformation like this:

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 differently. 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 two 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 curve composed of 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 show it in the viewer.

Now select some faces or edges. With this script you can iterate over 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 in the OpenCasCade Technology Tutorial is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The complete script below is also included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the python interpreter by typing:

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 three points, and two line segments, made of two points.

Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. Three edges (edges can be straight or curved), then a wire made of those three edges.

So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what we did and glue both halves together. We first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our wire with that transformation matrix applied to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges.

Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we?

At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a cylinder.

The fuse operation, which in other applications is sometimes called a union, is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed.

Then, we return our Part solid as the result of our function.

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

Box pierced
Here is a complete example of building a pierced box.

The construction is done one side at a time; when the cube is finished, it is hollowed out by cutting a cylinder through it.

Loading and Saving
There are several ways to save your work in the Part module. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL.

Saving a shape to a file is easy. There are exportBrep, exportIges, exportStl and exportStep methods available for all shape objects. So, doing:

will save our box into a STEP file. To load a BREP, IGES or STEP file:

To convert an .stp file to an .igs file:

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