Deferred boundary evaluation of complex CSG models

Deferred boundary evaluation of complex CSG models

Advances in Engineering Software 85 (2015) 51–60 Contents lists available at ScienceDirect Advances in Engineering Software journal homepage: www.el...

1MB Sizes 1 Downloads 51 Views

Advances in Engineering Software 85 (2015) 51–60

Contents lists available at ScienceDirect

Advances in Engineering Software journal homepage: www.elsevier.com/locate/advengsoft

Deferred boundary evaluation of complex CSG models C.J. Ogayar-Anguita ⇑, Á.L. García-Fernández, F.R. Feito-Higueruela, R.J. Segura-Sánchez Department of Computer Science, University of Jaén, EPS Jaén, 23071, Spain

a r t i c l e

i n f o

Article history: Received 2 January 2015 Received in revised form 12 February 2015 Accepted 1 March 2015 Available online 21 March 2015 Keywords: Constructive solid geometry Boolean operations Triangular meshes Boundary representations Geometric algorithms Computer-aided design

a b s t r a c t In this paper we present a deferred method for evaluating a complete CSG tree based on triangulated solids. It allows the exact evaluation of the surface of the entire model in a single step, using regularized Boolean classifications. The overall performance with this approach is better than with the classical method, which incrementally evaluates a CSG tree with single Boolean operations. The deferred algorithm does not use any intermediate result for the nodes of the CSG tree. It uses a very simple data structure and an octree that speeds up spatial queries for the entire CSG tree. The algorithm intensively uses multitasking and is ready for working with very complex CSG expressions, including the application of an out-of-core based approach. Ó 2015 Elsevier Ltd. All rights reserved.

1. Introduction Constructive Solid Geometry (CSG) is an essential tool used in geometric modeling for the creation of complex models. It is based on a set-theoretic Boolean expression of primitive solid objects [7] of a typically very simple structure. The Boolean operations, such as union, intersection, difference, and symmetric difference, are applied to the boundary of 3D objects in the same way as with other sets. This is one of the most intuitive ways to create objects. The construction process is incremental and hierarchical. By using CSG, we can obtain very complex solids. A CSG representation consists of a sequence of Boolean operations on graphical primitives. It is stored as a tree. The leaf nodes contain the primitives, and each inner node represents a Boolean operation. Every node also stores a geometric transformation, which allows performing translations, rotations, and scaling as well as non-rigid transformations. This form of 3D modeling has been used extensively in fields such as industrial engineering (CAD/CAM), Virtual Reality, and Computer Graphics [2,11]. In this paper we present a method for evaluating CSG trees based on polygonal meshes, specifically triangulated meshes. The triangle mesh is the most versatile polyhedral representation among B-Rep representations [15]. This boundary representation scheme has multiple applications, and it is used in CAD, Virtual Reality and videogames to represent polyhedral solids, mostly ⇑ Corresponding author. E-mail addresses: [email protected] (C.J. Ogayar-Anguita), [email protected] (Á.L. García-Fernández), [email protected] (F.R. Feito-Higueruela), [email protected] (R.J. Segura-Sánchez). http://dx.doi.org/10.1016/j.advengsoft.2015.03.003 0965-9978/Ó 2015 Elsevier Ltd. All rights reserved.

due to its simplicity. It can represent almost any object with a given level of detail. Moreover, it can be directly processed with graphics hardware. Pure CSG and B-Rep representations have different advantages and disadvantages. A CSG solid is always closed and encloses a volume, which is desirable in CAD environments. However, the rendering is typically carried out by ray tracing, which is a highly time-consuming process. There are systems that perform real-time ray tracing, but in general they are slower (even the GPU based methods) than the standard rasterization performed by OpenGL/ DirectX with B-Reps primitives. On the other hand, B-Reps models (and thus triangle meshes) can be easily rendered. Nonetheless, a B-Rep has to fulfill strong geometric and topological requirements in order to correctly represent a solid [7]. For this reason, Boolean operations, and thus CSG evaluations, are far more difficult to perform properly on triangle meshes. In consequence, solid modelers tend to combine both solid representations in order to take advantage of the strengths of each one. Our method computes the evaluation of a CSG tree based on triangulated solids. The representation of the tree is given by a script which contains commands for describing all the primitives, their rigid transformations and the Boolean operations between them. However, solid design is an interactive process in most of the cases. This means that the user performs operations one by one, including corrections and modifications. This interactive process is usually assisted by command stacks, which include Boolean operations and geometric transformations. Also, undo and redo commands are used. This list of interactive commands can be represented by a tree, and can be internally used to build a CSG tree. But generally speaking, a script has much higher scope for

52

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

describing all the data needed. Therefore, our method is tested with scripts, because the interactive scenario is rather a concatenation of independent Boolean operations. Our algorithm is designed to evaluate the entire tree in a single step in order to improve the performance. The evaluation of a CSG tree in a single step has several advantages. Because no intermediate results are stored, several intermediate calculations are simplified and compacted, resulting in a more robust algorithm. With B-Rep, the topology of the result of a Boolean operation between two solids must be checked and corrected in order to ensure that is a valid solid representation. With a complex CSG tree, this can present a severe performance penalty. With a one-step approach the topological corrections are carried out only once (for the final result). 2. Previous work The creation and evaluation of CSG trees has been an active research topic for years. Usually a solid modeler uses the CSG to B-Rep conversion as the last step in editing solids, while different rendering methods are used for the editing stage itself. In this regard, the last research efforts are concentrated on visualization and rendering algorithms [4,5,24]. This is due to the need of low response times on CAD systems. As the CSG to B-Rep conversion is considered as an intrinsically slow process, a large number of recent papers are focused on the visualization of the result, or on obtaining an approximate evaluation in order to achieve realtime edition. However, the correctness of the CSG to B-Rep conversion is also important, because there are applications that do need an exact result instead of an approximation, such as architectural design, industrial design, CAE, machining and prototyping, among others. In these cases, the quality of the result is critical from the beginning, and an approximate rendering/evaluation is not enough for some purposes. Nevertheless, a hybrid approach could use a GPU-based method for the rendering and an exact method for the final evaluation. Our work is centered on the evaluation step, so we propose an optimized algorithm for the CSG to B-Rep conversion, particularly by using triangle meshes. Other representations for 3D objects, such as volumetric structures, curved surfaces or complex nonmanifold B-Reps, require different solutions. Most research works have focused on isolated Boolean operations. By using these methods, the evaluation of a CSG tree is performed by a succession of Boolean operations between the solids stored on the leaf nodes. Boolean operators and geometric transformations are stored on inner nodes. The binary tree that represents the CSG expression is traversed in post-order. For each inner node, a Boolean operation is carried out. With regarding simple Boolean operations between solids, there are many approaches that have been proposed. However, since this problem is very complex, not every method is suitable for all situations. The representation scheme determines the algorithm to be used. Some methods compute Boolean operations directly on the input elements, such as faces, edges and vertices [9,13,23,31]. These algorithms tend to suffer from robustness problems, because they are based on a rather complex data structure that complicates the topology management, and ultimately leads to a large number of special cases of geometric operations. Other systems avoid these drawbacks by converting the polygonal meshes into volumetric representations. After resolving the Boolean operation with voxels in a straightforward manner, the polygonal result is extracted from the volumetric result. However, a volumetric representation has a limited precision, and the loss of geometric features is unavoidable. Typical methods use a Marching Cubes algorithm to extract features from the volumetric result [10,17]. There are other frameworks that give

approximate results. This is because the performance is critical in modern CAD systems [32], and the amount of data to be processed can be very large. The approximations can be made at different levels, such as arithmetic [26] surface definition and representation [1,19,20,28,29,32] or by using direct rendering using the GPU [4,24]. Some of these methods propose the use of hybrid techniques which use voxels at a coarser level and geometry below the voxel resolution [19,27]. However, the extraction of features can be problematic sometimes or they are resolved with a complex approach. Other hybrid methods propose the use of a volumetric representation only at the intersections zones [29]. There are other systems that can calculate a B-Rep model from a pure BSP solid representation [30]. However, in most cases those systems do not provide exact results in order to maximize the performance. Moreover, they tend to suffer from additional issues and special cases, and some of them are very difficult to adapt to the use of extended/exact precision arithmetic (if needed). Approximate methods can be desirable in some applications such as collision detections, biomedical analysis or videogames. However, there are applications that do need an exact result instead of an approximation, such as architectural design, industrial design, CAE, machining and prototyping, among others. Our method is designed for these applications. Our proposal for evaluating regularized Boolean operations on triangulated meshes is based on a classical approach for B-Reps. We focus on triangle intersection and tessellation. As stated in our previous work [3], we demonstrate that this approach is faster than other popular methods when working with triangular meshes. In this work, we extend the classic Boolean operation method presented in that previous work [3] in order to adapt it to the evaluation of the entire CSG tree in one step. This has a number of advantages: intermediate results that introduce precision errors are avoided at each step, so it also increases robustness; more performance is obtained, because much of the computations associated with inner nodes are not needed; the method is robust and provides accurate results. The following sections present the background and the details of the algorithm. Finally, the implementation and the results are analyzed.

3. Background CSG is a representation scheme that allows the construction of complex solids using simple primitives [7]. The classical approach is based on the use of standard primitives, which are defined by some geometrical properties. Thus, cylinders, cones, boxes, spheres and other simple objects are instantiated to build new and more complex solids. Primitives are usually represented by their frontier (boundary), in a parametric or implicit form. Implicit representations are ideal for ray tracing, therefore they are preferred for direct rendering. On the other hand, a parametric representation allows to directly generate points on the surface, which is useful for any CAD application. However, there are situations that require building a CSG tree based directly on polygonal meshes. Classical methods for evaluating a CSG tree can be very inefficient in those cases. This is because polygonal meshes are usually based on implicit or parametric surfaces. If a mesh contains a high number of polygons, most operations can be too slow, like the point-in-solid test. For these cases, an optimized method must be used. Our method performs the evaluation of a CSG tree based on triangulated solids. The conversion from CSG to B-Rep is performed directly, because the input primitives are represented by their boundary and the entire process operates with boundary data (triangles in both cases). When using B-Rep models, most CAD systems perform the evaluation of a CSG in an incremental manner, that is, node by

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

node. The tree is traversed in post-order. Each inner node has a Boolean operator, and its operands are specified at its two children nodes. Therefore, each result is taken as an input of the Boolean operation on its parent node. At each node, a geometric transformation is also taken into account. This process leads to a succession of isolated Boolean operations that produces a series of intermediate results. All Boolean operations are regularized, that is, only the closure of the interior of the result is taken [22]. Although an incremental process can have some benefits, a large number of intermediate results can lead to an accumulation of geometrical errors or extra topological corrections. This is because the more operations to be performed, the more errors can be produced and accumulated into the final result of the CSG evaluation. As we demonstrate in this work, all these factors have an impact on the performance. The proposed method is designed to evaluate the entire tree in one step, therefore avoiding the aforementioned issues. The algorithm presented here is based on a classical approach for B-Rep models [9,14,21,31]. We focus on triangle intersection and tessellation. At first, each solid is intersected with the rest of the solids. We use triangle meshes for representing the solids, therefore each mesh is conveniently tessellated so that every triangle is totally inside, outside or on the boundary of the other meshes. From now on, we refer to a mesh tessellation as the tessellation of the triangles of that mesh. The tessellated meshes are stored at the leaf nodes, alongside their original meshes. Then, the resulting triangles are classified, and after that, the resulting solid is built. This is performed by selecting the triangles from all the solids that are included in the set specified by the CSG expression stored on the tree. From now on, we use the terms solid and mesh indiscriminately to refer to a 3D object and its corresponding mesh. This is because in our work all the solids to be considered are represented by a triangulated mesh. The evaluation of a CSG tree is a process that presents several issues that must be taken into account. Numerical stability and memory consumption are the main problems, although the performance can be also an issue. Typical CAD systems operate on a data structure derived from a winged-edge, and the intersections are calculated per edge. Also, they typically use binary space partitions (BSPs) in order to test intersections between geometric primitives or to perform spatial classification of points. These are some reasons why Boolean operations and CSG evaluations tend to be are slow, unstable and error prone. Our system has been designed to avoid these issues. One of the aforementioned issues is robustness [3]. Geometric computation software tends to fail due to complex data structures and a large number of special cases of geometric operations. As stated by Hoffmann [8], there are several layers in geometric computation software. These layers range from very simple computations (vector addition, inner product, etc.) to higher level operations like face–face intersection, topology management, and ultimately complex operations such as Boolean operations between meshes, and of course, the evaluation of a CSG tree. Lower levels must be absolutely reliable. The main problem is the numerical precision. Exact arithmetic can be used, but at the expense of a noticeable performance loss. The higher-level computations (like triangle–triangle intersections) present other robustness issues that must be handled with care, most of them due to special or degenerate cases. Another cause of robustness problems is topology management [3]. CAD systems are among geometric software packages with the highest complexity. Classical approaches use a winged-edge based structure for representing polyhedral solids [31]. The more sophisticated and informative the data structures, the less reliable the resulting code tend to be [8]. For a complete winged-edge structure or similar, an inconsistency in the adjacency data is a source of

53

severe failure for the CSG evaluation algorithm. Our method works with 2-manifold meshes connected at the vertices, which are known as indexed face sets. It does not maintain explicit information about edges as only vertices and triangles are stored. Therefore, the consistency of the structure is straightforward to maintain. This simplification reduces the robustness problem, although some additional topological tests have to be performed during the evaluation (e.g., check for isolated vertices). Moreover, this method does not perform any domain transformation, such as using volumetric elements, or any feature simplification. 4. The proposed method In this section we explain the details of the proposed algorithm. The goal is to evaluate a complete CSG tree based on an expression given by the user. This expression contains a hierarchical description of instantiation of solids, Boolean operations and geometric transformations. We have developed an API that allows the user to define the CSG tree at a source code level. This API communicates with the core of the software, therefore is the natural way to program at a low level. However, for the sake of flexibility, we also have developed a high-level tool for achieving the same task. Using the ECMAScript language we have created another API that allows to build and to evaluate CSG trees. This little programming interface allows the user to load meshes, create new instances and manage the tree by creating Boolean operations and setting geometrical transformations for each node. Additionally it allows configuring the system and launching the evaluation of the tree. The evaluation can be performed node per node (the classical approach) or can be deferred (our proposed method). It must be noted that all solids must be instanced before inserting them into the CSG tree, that is, using them in a Boolean operation. There can be more than one instance of the same solid, and each instance will be tessellated during the evaluation in a unique manner. For building very complex solids and structures, it is recommended to follow a modular approach and a divide and conquer method. It is convenient to have a stock of previously modeled pieces (e.g., bolts, gears, pipe sections, etc.), which greatly depends on the field of application. These pieces can be modeled with CSG using standard primitives like spheres or cylinders, but it is more convenient to evaluate and store them on secondary memory for a later use as a primitive with a higher level CSG. 4.1. Preprocessing steps Our method works optimally with 2-manifold meshes connected at the vertices, which are known as indexed face sets. In this way, there is an indexed list of vertices and a list of triangles which reference each vertex using its index. This is one of the simplest forms for representing a triangle mesh, and allows us to share the vertices among neighboring triangles. It does not maintain explicit information about edges, only about vertices and triangles. The reason for this is to maintain the consistency of the structure in a straightforward manner. Another layer of topological information is stored for each mesh, which is the connectivity information between faces. This information is the link between triangles and determines the neighbors of each face of the mesh. This allows performing a fast topological query in order to establish groups of triangles that define a zone of the surface with the same classification status, as we explain later. In order to correctly perform the intersection process, all the instances of the solids must be positioned with respect to the same coordinate system. There is a geometric transformation in every node of the tree, which is specified by a matrix. All of these

54

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

transformations are accumulated from top to bottom. By carrying this step out, the leaf nodes have the required geometric transformations defined in the hierarchy, and the solids can be directly positioned in respect to the global coordinate system. At this point, the solids are referred to the same coordinate system, and the intersection between them can be performed correctly. We can also define the bounding box of the CSG tree as the union of the bounding boxes from all the solids in their final position. A CSG tree can store a high number of nodes and instances of solids. The geometric intersection between every pair of distinct instances must be calculated. However, this process can be omitted when their Boolean intersection is the empty set, that is, they do not collide in space or none of them is included into the other. It must be noted that two solids can be completely separated from each other in the space, and even so can be joined in a Boolean union. The result would be a solid with two bodies, and no further calculations would be needed for completing the Boolean operation. In order to discard all possible intersections between solids, a broad-phase collision detection is used. We use axis-aligned boxes for a fast test (later, more exhaustive tests are performed). The boxes are adjusted to each solid in the global coordinate system as at this point all the solids are positioned with respect to the global coordinate system. 4.2. Octree construction A key aspect of the algorithm is the use of an octree. This structure accelerates the spatial queries needed during the evaluation of the CSG tree. It also divides the data set into subsets that can be distributed among several threads or nodes in a cluster. It is also possible to treat a part of the mesh while the rest is stored on secondary memory. This allows us to use an out-of-core approach for working with complex CSG trees based on solids with a huge amount of triangles (e.g., from 3D scanned data). However, this variation of the algorithm is left for future work. The octree includes all the solids of the tree, that is, the root node defines an axis-aligned bounding box of the entire tree. It stores in each leaf node the identifiers of the triangles of each mesh that intersect the volume represented by the axis-aligned bounding box of that node. If a triangle intersects several nodes, its identifier will be stored in each node. The construction of the octree is performed incrementally. At first, it is constructed to include only those triangles which are directly involved in the intersection of the meshes. Thus, a node from the octree is divided only if it contains triangles from more than one mesh. This way of working accelerates the construction and the traversal of the octree for some parts of the CSG evaluation. Also, the memory requirements are lower. But later, depending on the topology and the position of the solids, the point-in-solid test may be needed. For this, the octree must be completed in order to include all of the triangles from the meshes, including those that are not involved in the intersections between meshes. The octree can be configured in order to achieve a good balance between the building time of the structure and the performance of the spatial queries used in the algorithm. The memory usage of the octree is also affected by this configuration. In general, building the structure requires O(n log(n)) for n triangles. The subdivision of the octree is performed using all available computation units, which are logical CPU cores for the simplest hardware configuration. The octree is involved in almost every step of the evaluation of the CSG tree. However, two major spatial queries are specially affected: the triangle–triangle intersection test and the point-insolid test. The evaluation of a CSG based on triangle meshes implies a large amount of intersection tests between all the primitives of the CSG tree. Naturally, the number of tests to be performed depends on the number of primitives (meshes) and their

topological complexity, which is determined by the number of triangles. In most of the cases, the number of tests is extremely high. Previously we mentioned a method for discarding intersections between solids by using bounding boxes. At a polygon level, we use the octree in order to discard the majority of intersections between triangles. 4.3. Trimming and classification of primitives Once the meshes are positioned at their final position and the octree is built, the trimming step can be carried out. Each solid must be intersected with the rest of the solids. In order to achieve this, an intersection table is calculated. This table reflects the intersections between meshes. At first, bounding volumes are used to discard intersections between meshes. Then, the leaf nodes of the octree are checked. For each leaf node, a list of triangles from each mesh is stored. Therefore, it is straightforward to check whether two meshes collide at the space delimited by that leaf node. The next step is to check the intersections between triangles from different meshes that are present at that node. A naive approach to resolve this process would be to iterate through all the leaf nodes and perform the triangle–triangle intersection test with all the triangles referenced by each node. However, a triangle can be referenced by more than one leaf node, and therefore there would be redundancies in computing the intersections. Our approach to resolve this process consists of extending the intersection table. For each triangle of each mesh, a set of possible intersections is included. Actually, these possible intersections describe the coincidence of the triangle and other triangles from other meshes at the same node of the octree. The intersections are calculated later by the triangle–triangle intersection algorithm. This way, we can process all the intersections of a given triangle in a single pass. This is very important for using our optimized triangle trimmer, which is based on a constrained Delaunay triangulator. We provide more information about this topic later. We used the method presented in [16] for the triangle–triangle intersection test (for checking whether two triangles intersect or not). For the computation of the intersection points we use a variant of the method presented in [25]. Once the triangle–triangle intersections have been computed, each triangle is conveniently tessellated so that every new triangle is totally inside, outside or on the boundary of the other meshes. The goal is to obtain for each mesh a resultant set of triangles that meets the following condition: no triangle set can intersect with a triangle from other solid. The new meshes are stored at the leaf nodes, alongside their original meshes. Both are used for completing the evaluation of the CSG. The triangles of a tessellated mesh are adapted to the intersection zone with the other solids [21]. With each triangle–triangle intersection new vertices must be introduced into the B-Rep structure. This applies for all the meshes during the intersection process. These new vertices logically belong to the frontiers of more than one mesh, and they are the base for the new triangulations. Each triangle affected by an intersection must be decomposed (tessellated) into new triangles (and vertices). As noted earlier, all the intersections for a triangle are calculated in a single pass, by using the information stored in the global intersection table. This process is carried out for every triangle that is intersected. Once the intersection points have been determined, we will proceed to insert them in the list of vertices of the triangle to be tessellated. However, if an intersection point coincides with any of the vertices of a triangle (original vertices) it must not be added to the list of triangle vertices in order to avoid repetitions. In this case, a reference is used. Also, if an intersection point is situated on an edge, the two triangles that share that edge must also share the vertex. As our data structure does not store information about

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

edges, a vertex welding process must be carried out for neighboring triangles. The tessellation of a triangle is performed in a single step by using a constrained Delaunay triangulator. The input of the triangulator consists of the original vertices of the triangle and the new vertices obtained as the result of all the intersections with other triangles. Also, the intersection between two coplanar triangles can produce several edges. Those edges are passed to the triangulator as constraints, in order to ensure that they will belong to the resulting triangulation. Also, those very edges can intersect between them, and in turn can generate new vertices. The Delaunay triangulation has several advantages over other triangulation methods. The triangles are as equi-angular as possible, so the potential numerical precision problems are reduced when the result contains long and thin triangles. Moreover, the order of processing the points does not alter the triangulation. At this point, all the meshes are conveniently tessellated so that every triangle from every mesh is totally inside, outside or on the boundary of the other meshes. This allows us to classify each triangle using only a single point located on it using a point-in-solid test. However, when a triangle is intersected by the surface of other mesh, we can calculate the common edges that belong to both meshes. We refer to these common segments as intersection lines. It should be noted that this process must be repeated for each pair of intersecting meshes of the CSG tree. By using the intersection lines, we can also calculate neighboring information between triangles from different meshes. Thus, an intersection zone is the set of triangles which have at least an edge belonging to an intersection line. Each intersection line has an associated intersection zone, which includes triangles from both tessellations. This information allows us to classify every triangle that belongs to the intersection zone in a straightforward manner, because it has neighbors from the other mesh that define the position and orientation of the intersecting surface. Nevertheless, there can be triangles from a solid that are not divided during the intersection and tessellation process. They are located together in groups, and are normally surrounded by the triangles involved in the tessellation. Using the neighboring information of the triangles, we can build groups of them that will be separated only by the intersection lines using a flooding algorithm. Those groups represent parts of the surface that can be classified as a whole, typically by using neighboring intersection lines. Without that information, in order to test whether a triangle from a mesh is inside, outside or on the boundary of another mesh, a point-in-solid test is carried out using the barycenter of the triangle (this is explained later). There are configurations that do not allow classifying some parts of the surface of a mesh directly. If there is an isolated part of a mesh (a body) that does not intersect with other mesh, its inclusion state with respect to that other mesh cannot be determined without additional information. This also can be true for an entire mesh. If mesh A does not intersect mesh B, we cannot establish whether A is inside B or B is inside A. This problem only makes sense if their bounding volumes intersect or they share some node of the octree, because otherwise both meshes are classified as outside the other mesh, because they do not interfere. Every triangle, part of a surface or isolated body that cannot be classified using a direct contact with the other solid, must be classified using a point-in-solid test. For a group of connected triangles that is delimited by one or more intersection lines, a single point from that part of the surface is used to classify the entire part with a point-in-solid test. The barycenter of any of those triangles can be used. This is because that group of triangles is totally inside, outside or on the surface of the other solid. Several approaches can be used to perform the point-in-solid test [18]. As the number of tests to be performed in this work is rather low, we use the Jordan Curve Theorem [6]. This method

55

computes a ray–surface intersection test. The origin of the ray is the point that is to be tested for inclusion, and the direction is (usually) random. The ray can intersect the surface of the solid at several points (or none). The parity of the number of intersections indicates if the point is inside or outside the surface. It has some special cases; the most notably is when the point lies on the surface. The surface itself is represented by a triangle mesh. Thus, the point-in-solid test must perform a ray–triangle intersection test for all the triangles of the mesh. The octree is especially useful for this task, because it is desirable to perform as few ray–triangle intersections as possible. However, the octree previously calculated does not include all the triangles from the meshes, only those are near the intersection zones. In order to use the octree with the Jordan-based point-in-solid test, it must be completed to include all the triangles. The octree implementation used in our tests can be calculated in two phases in an incremental manner. This optimization allows an important performance gain and less memory usage when the CSG evaluation does not require any point-insolid test. 4.4. Deferred evaluation As presented before, most CAD systems perform the evaluation of a CSG in a sequential manner, node by node. Each result is taken as input for the Boolean operation in the parent node. At each inner node the corresponding Boolean operation is performed and the result is stored. This result is taken at the parent node as an operand of another Boolean operation. The process finishes at the root node, which stores the final result. With this approach, a succession of isolated Boolean operations that produces intermediate results is carried out. We also mentioned before the drawbacks of this approach. Our method performs a deferred evaluation of the entire CSG tree. At this point the meshes instanced in the CSG tree are tessellated so that every triangle from each solid is completely outside, completely inside or on the boundary of the other solids. Now the final result is built by selecting the appropriate set of triangles that meets several conditions [12]. These triangles are selected from all the tessellated meshes that are stored at the leaf nodes of the tree. The mentioned conditions are given by the CSG expression, and rely on the definition of regularized Boolean operations for triangle meshes. Next, the definition of regularized Boolean operation for triangle meshes is presented [22,3]. This is the base for a CSG evaluation, which concatenates several Boolean operations (and their conditions) by traversing the CSG tree in post-order. Let TA be the set of triangles from the tessellation of the mesh A, and TB the set of triangles from the tessellation of the mesh B. Let T1 be a set of triangles with their normals inverted and n(t) the normal vector of the triangle t. Let W be a set (universe) and T a topology on W (the collection of all open subsets of W). In the topological space (W, T) a subset X of W is a closed (regular) set if it equals the closure of its interior: X = kiX. Therefore we define the following sets of triangles that meet the conditions of each Boolean operation.  Regularized union, {A [ ⁄B}: {TA out B} [ {TB out A} [ {TA on B/n(ti) = n(tj); ti 2 TA, tj 2 TB}.  Regularized intersection, {A \ ⁄B}: {TA in B} [ {TB in A} [ {TA on B/n(ti) = n(tj); ti 2 TA, tj 2 TB}.  Regularized difference, {A  ⁄B}: {TA out B} [ {(TB in A)1} [ {TA on B/n(ti) – n(tj); ti 2 TA, tj 2 TB}.  Regularized symmetric difference, {A b ⁄B}: {TA out B} [ {(TA in B)1} [ {TB out A} [ {(TB in A)1}. It is equivalent to (A  ⁄B) [ (B  ⁄A). The previous conditions are sufficient for a single Boolean operation. However, the evaluation of a CSG tree typically implies

56

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

more than one operation. Moreover, as our method is based on deferred evaluation, the selection of the final set of triangles must fulfill all the conditions specified by the CSG expression. Because of this, the definitions of the Boolean operations must be modified in order to take the interior of the solids into account. When performing a Boolean operation between two meshes, all the triangles to be classified belong to the surface of these meshes. There are no triangles located at the interior or the exterior of both meshes. However, when evaluating a CSG expression, the triangles from a third mesh located at another branch of the tree can fall totally inside or outside the boundaries of the two first meshes. For example, the CSG expression (A [ ⁄B) \ ⁄C establishes that all the triangles from C must be classified with respect to A, B and indirectly A [ ⁄B. Any triangle from C can lie in or out A without being part of the surface of B and vice versa. We now define the sets of triangles that meet the conditions of each Boolean operation. The conditions for each Boolean operation in the CSG tree are expanded in this manner: Let TC be the set of triangles from the tessellation of the mesh C stored at another branch of the tree than meshes A and B. We define the classification of the set TC in the space delimited by each type of Boolean operation with operands A and B. This classification is used with higher-level Boolean operations. The following sets are expressed in an expanded form in order to maximize readability and comprehension.  Regularized union: {TC 2 Boundary (A [ ⁄B)}: {{TC on {{TC on B} \ {TC out A}} [ {{TC on A} \ {TC on ti 2 TC, tu 2 TA, tv 2 TB}. {TC 2 Interior (A [ ⁄B)}: {TC in A} [ {TC {TC in B}} [ {{TC on B} \ {TC in A}} [ {{TC on n(tv); tu 2 TA, tv 2 TB}.

A} \ {TC out B}} [ B}/n(ti) = n(tu) = n(tv); in B} [ {{TC on A} \ A} \ {TC on B}/n(tu) –

 Regularized intersection: {TC 2 Boundary (A \ ⁄B)}: {{TC on A} \ {TC in B}} [ {{TC on B} \ {TC in A}} [ {{TC on A} \ {TC on B}/n(ti) = n(tu) = n(tv); ti 2 TC, tu 2 TA, tv 2 TB}. {TC 2 Interior (A \ ⁄B)}: {{TC in A} \ {TC in B}}.  Regularized difference: {TC 2 Boundary (A  ⁄B)}: {{TC on A} \ {TC out B}} [ {({TC on B} \ {TC in A})1} [ {{TC on A} \ {TC on B}/n(ti) = n(tu) – n(tv); tu 2 TA, tv 2 TB}. {TC 2 Interior (A  ⁄B)}: {{TC in A} \ {TC out B}}.  Regularized symmetric difference: {TC 2 Boundary (A b ⁄B)}: {{TC on A} \ {TC out B}} [ {({TC on B} \ {TC in A})1} [ {{TC on B} \ {TC out A}} [ {({TC on A} \ {TC in B})1}. {TC 2 Interior (A b ⁄B)}: {{TC in A} \ {TC out B}} [ {{TC in B} \ {TC out A}}. The evaluation of the CSG tree is performed using a deferred approach. The last step of the algorithm consists of selecting the triangles that meet the conditions of the CSG expression. This very expression establishes the set of triangles that compose the resulting mesh. The triangles are selected from the tessellated versions of the meshes stored at the leaf nodes. At this point, all the triangles are already classified, so every triangle of every mesh has a state of inclusion with respect all the other meshes. Next, all meshes are processed. For each one, every triangle is tested with the CSG expression. The tree is traversed in post-order, and for each inner node the conditions of the corresponding Boolean operation are applied to each triangle. Actually, an upward

propagation of the state of inclusion of each triangle is performed. This state is taken as an operand at each node, and the Boolean operation specified in that node changes the state accordingly. A given triangle is classified as inside, outside or on the frontier of the region of the space delimited by the partial expression of the CSG defined in each node. The conditions presented above are used, differentiating between the boundary and the interior of that very space. All this process is done in parallel using all available CPU cores. The resulting solid will be obtained by copying the triangles that are classified as part of the frontier of the expression defined at the root node of the CSG tree. Fig. 2 shows the result of the evaluation of a CSG expression using the deferred approach. Any triangle that is classified as inside of the resulting solid is ignored, because the goal is to obtain only the closure of the interior. It must be noted that the inclusion of a triangle in the interior of a mesh or a CSG subexpression is important for the conditions applied at the inner nodes. The result of the evaluation must not include lower-dimensional structures like loose triangles or non closed bodies, although depending on the input it can still produce a non-manifold result. These loose vertices and triangles are eliminated after the evaluation using a topology verification test, hence resulting in the closure of the interior of the final mesh. With the deferred evaluation of the CSG tree, this process is performed only once at the end, because no intermediate data is stored for each Boolean operation. Moreover, as we have presented before, it is important to keep all lower-dimensional elements during the evaluation of the tree, even in the interior of the solid defined by an intermediate expression. These elements can be part of the final result after several additional evaluations at higher-level nodes. Because of the data structure used for this algorithm, there should not be any isolated element (vertex or triangle) resulting from a Boolean operation. However, arithmetic precision issues can arise with the intersection and tessellation of very small or stretched triangles, especially when not using extended precision. In order to solve these cases, a straightforward connectivity check is performed on each triangle of the resulting mesh. As we stated above, only space-filling volumes are allowed (closed bodies with a finite boundary). Thus, any triangle with less than three neighbors will be removed from the mesh. Previously to this step a vertex welding process must be carried out for neighboring triangles. This is because the resulting mesh is composed of triangles coming from different meshes. Therefore the vertices of the neighboring triangles are duplicated at the topology level. They occupy the same position in space but are separated in the data structure. They are actually the very same vertices and should be welded together. Needless to say, if this step is not performed, the topology test for eliminating isolated triangles would erase part of the resulting mesh. 4.5. Final steps At this point, the resulting mesh is closed and correct. However, there is an additional optimization step. During the required tessellation triangles are divided by the intersections with other solids. Each triangle is decomposed into several that will be completely inside, outside or on the surface of the other solids. Depending on the CSG expression, it may happen that for a given original triangle (prior to the tessellation) all its derived triangles (after the tessellation) are included into the final mesh. In this case, the topology is correct, but the triangulation is not optimal, that is, the amount of triangles is higher than necessary. The surface represented by the resulting boundary is the same as if the original triangle would not have been subdivided by the tessellation process. This extra tessellation is noticeable when viewing the resulting solid in wire frame mode. In order to eliminate this undesired side

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

57

effect we perform a process of detriangulation. This process replaces a set of triangles with the corresponding original triangle when possible. At the tessellation step, an intersected triangle is divided into a set of smaller triangles whose union is the first triangle. It may occur that that set is completely included in the final mesh by the CSG evaluation (this depends on the CSG expression). Then, there is no need to keep all the fragments instead the original triangle. Fig. 1 shows an example in 2D. The detriangulation is very fast, because during the tessellation the new triangles are linked with their original triangles and vice versa. Therefore it is straightforward to know if all fragments from an original triangle have been classified as part of the CSG model frontier. Due to this process, the polygonal complexity of the resulting solid is reduced without altering the topology of the surface.

5. Results and discussion We have tested our proposed algorithm with several CSG expressions. They have different complexity, that is, a different number of primitives and also a different number of triangles in each mesh. We have compared the deferred approach with the classical method to evaluate the CSG trees. In [3] we presented a comparison of the performance of several methods for performing isolated Boolean operations. We demonstrated that our approach is faster than most of the classical solutions when working with triangular meshes. The method presented in [3] is used to evaluate the CSG trees with the classical approach, that is, for incrementally evaluating each CSG tree with isolated Boolean operations. All of the algorithms have been entirely written using C++ and OpenMP. The implementations take advantage of all CPU cores at most stages of the algorithm. All of the tests have been carried out with an IntelÒ Core™ i7 CPU at 3.50 GHz with 8 cores and 16 Gb of memory. The software was compiled in 64 bits mode. Several parameters can be adjusted in order to get optimal results. Floating point precision is very important for maintaining the robustness of the method. In the tests we have used double precision arithmetic, which provide correct results while having a good performance. For operating with very complex meshes the extended/exact precision arithmetic could be needed, but at

Fig. 2. The result of the evaluation of the CSG model ‘ventilated brake disk’ using the deferred approach. In contrast to the classical approach, the triangles are better distributed as a consequence of the one-step tessellation.

the expense of the performance. However, in our tests double precision was enough to get correct results. All of the meshes have a 2manifold representation with a configurable polygon complexity (most of the primitives are generated parametrically). Also, the octree can be configured in order to achieve a good balance between the building time of the structure and the performance of the spatial queries. Although the amount of memory used by the structure is important, our priority is to maximize performance. With a depth for the octree of 8–10 the performance of the CSG evaluation is very good, keeping a reasonably low time for the calculation of the structure. The main goal of the tests is to compare our new approach with the classic. But as most systems perform the evaluation of a CSG expression by calculating each Boolean operation separately, the inclusion of those systems in the comparative study of this work would be pointless, because we already presented a complete revision of Boolean operations in [3]. Table 1 shows the results of the tests. There are several CSG expressions with different number of nodes and Boolean operations. Some of them are mechanical pieces, while others are simple solids with a large number of Boolean operations applied to them (an stress test). We take into

Fig. 1. An example of the proposed method in 2D. (a) The objects involved in the CSG evaluation. (b) The one-step tessellation of the objects. (c) The difference between A and C. The underlying triangulation of B is also presented. (d) The final result for the expression BU(A–C). The triangles from B can be reunited into the original triangles, simplifying the resulting triangulation. (e) The produced T-junctions are eliminated with a Delaunay re-triangulation for ensuring topological correctness. (f) The final result.

58

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

Table 1 Results for the evaluation of several CSG expressions (incrementally ordered by the evaluation time of the classic approach). The configuration of the octrees is the same for all the solids (max. depth = 9, max. triangles/node prior to subdivision = 20). The times are given in seconds and include the construction of the octrees.

Total nodes Boolean operations Intermediate meshes Source triangles (total) Created triangles (total) Final triangles Total memory usage by meshes Peak memory usage by meshes Number of octrees Total memory usage by octrees Peak memory usage by octrees Total time (s)

Coupling piece

Beveled gear

Classic

Classic

19 9 8 16292 9454 5663 14.56 Mb 3.43 Mb 9 5.31 Mb 1.11 Mb 0.319

Deferred

0 15223 5449 7.60 Mb 1 1.60 Mb 0.270

89 44 43 6016 11569 5716 43.48 Mb 2.46 Mb 44 5.85 Mb 0.26 Mb 1.573

Spur gear Deferred

0 23469 5435 5.18 Mb 1 9.72 Mb 1.303

account the number of triangles of the meshes and the number of triangles of the final result. The configuration of the octrees is also important. For the deferred algorithm only an octree is used, while the classical approach used as many octrees as Boolean operations. The memory consumption is a key consequence of the configuration. It is affected by the octrees and the amount of tessellated meshes that coexist at a given moment, which determines the peak value of memory usage. As can be observed, the time for the evaluation of a CSG expression depends on both the number of primitives and the topological complexity of the meshes. However, another factor is critical: the overlapping between solids. The more intersections are produced between solids, the more tessellations of triangles are calculated. This also has a direct impact on the classification of the tessellated meshes. A CSG tree composed of solids that scarcely intersect between them is faster to evaluate than another tree composed of solids that overlap intensely. The number of intersections between triangles differs in both cases, and also the number of tessellations and classifications of triangles. As can be seen in Table 1, there are several differences between the deferred evaluation and the classical method (apart from the performance). The deferred evaluation performs more triangle tessellations. This is due to the fact that all the meshes are intersected with each other. With the classic method, two meshes are intersected only if both of them are operands of the same Boolean operation, that is, they are located at the same node of the CSG tree. One of the main benefits of the deferred evaluation is that once the intersections have been performed, the CSG expression can be modified without needing to recalculate the intersections between meshes. The only

Classic 111 55 54 7992 32436 13663 157.47 Mb 5.82 Mb 55 302.74 Mb 8.31 Mb 5.514

Cylinder with 200 random perforations Deferred

0 43968 10193 9.60 Mb 1 2.84 Mb 2.309

Classic 401 200 199 12864 90651 33362 936.02 Mb 14.24 Mb 200 102.56 Mb 2.10 Mb 51.496

Deferred

0 102934 29685 19.17 Mb 1 29.34 Mb 22.711

Ventilated brake disk Classic 359 179 178 13694 195545 95753 2.39 Gb 40.60 Mb 179 104.08 Mb 1.40 Mb 132.78

Deferred

0 111935 88492 25.24 Mb 1 4.38 Mb 16.42

condition for this to be possible is to not change the position of the instances of the solids in the space. The tessellation of the meshes allows us to evaluate any possible CSG expression with the same spatial configuration with almost no extra calculation time. This is particularly useful during the interactive edition and execution of a script that defines a CSG tree. An incremental edition of the script results in an incremental update of the CSG tree. The part of the tree that does not change supposes a great amount of intersections and tessellations that do not need to be recalculated. Moreover, we can calculate the evaluation of a part of the CSG expression almost directly. Once all the meshes are tessellated and classified, the evaluation of an expression that includes any combination of those meshes is as straightforward as the evaluation of the entire CSG tree. This allows us to calculate any partial result or subtree with almost no additional computing cost. On the other hand, the number of triangles of the resulting mesh is lower with the deferred approach. This is due to the detriangulation process carried out as the last step of the evaluation, which was explained in previous sections. This way, the polygonal complexity of the resulting solid is reduced without altering the topology of the surface. Although the main benefit is to reduce the amount of triangles, the quality of the result is visually better, because there are no unnecessary divisions of the triangles. This does not happen with the classic method, where a triangle can be divided several times due to a succession of Boolean operations. Fig. 3 shows an example. A possible solution is to perform a postprocessing step on the resulting triangulation for uniting adjacent triangles whenever possible. However, this step is not straightforward to implement efficiently, and it must be performed for every

Fig. 3. The evaluation of the CSG expression {(((Box-Sphere1)  Sphere2)  Sphere3)  Sphere4}. (a) Using the classic approach (752 triangles). (b) Using the deferred approach (636 triangles).

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

59

Fig. 4. Some of the solids created in the tests. (a) Coupling piece. (b) Beveled gear. (c) Spur gear. (d) Ventilated brake disk.

Fig. 5. The setup of the model ‘spur gear’. Each primitive of the tree is drawn with a different color. (For interpretation of the references to colour in this figure legend, the reader is referred to the web version of this article.)

isolated Boolean operation of the CSG tree. This supposes a severe performance penalty. Generally speaking, the deferred method uses more memory than the classic method. The peak memory usage for the classic method is lower in all cases. However, this is only true as long as the detriangulation process is not performed with the classic algorithm. But if this is the case, the critical parameter is the total memory dedicated to store the meshes and their tessellations. As can be seen in Table 1, the value for this parameter is much higher than the memory used by the deferred method. Although the deferred evaluation uses more memory than the classical incremental evaluation, its performance is better. When evaluating a simple CSG expression this difference tends to be minimal. However, with a more complex CSG the deferred method clearly outperforms the classic algorithm. There are several factors that determine this difference. With the classical approach, there are many octrees that share the same space. If we draw every octree used along the evaluation of the CSG tree, we note that the same space is included in many nodes from different octrees, which even overlap. This is optimized in the deferred method by using only one octree. All the meshes are contained in the same octree, and the division of the space has no redundancies. Of course this also affects the computing time. Thus, a unique octree is faster to build than a succession of minor octrees that overlap. For the tests we have used a depth of 9 and a minimum of 20 triangles per node to perform node subdivision. These values were used for both the deferred method and the classic one. Fig. 4 shows some solids built for the tests. Fig. 5 shows a more detailed example.

6. Conclusions In this paper we have presented an efficient method for evaluating a complete CSG tree based on triangulated solids. It performs the exact evaluation of the surface of a CSG tree in a single

step, using a deferred regularized Boolean classification. The overall performance with this approach is better than with the classical method, which incrementally evaluates a CSG tree with isolated Boolean operations. The deferred method also allows us to calculate any partial result of the CSG expression with almost no extra computation time. It generates better triangulations for the result than the classic method, and also performs the topological corrections only once at the end. Acknowledgments This work has been partially supported by the Ministerio de Ciencia e Innovación and the European Union (via ERDF funds) through the research projects TIN2011-25259 and TIN201458218-R, and by the University of Jaén through the research project UJA2013/08/35 sponsored by Caja Rural de Jaén. References [1] Adams B, Dutré P. Interactive Boolean operations on surfelbounded solids. ACM Trans Graph 2003;22(3):651–6. [2] de Berg M, van Kreveld M, Overmars M, Schwarzkopf O. Computational geometry. Berlin: Springer; 1997. [3] Feito FR, Ogayar CJ, Segura RJ, Rivero ML. Fast and accurate evaluation of regularized Boolean operations on triangulated solids. Comput Aided Des 2013;45:705–16. [4] Hable J, Rossignac J. Blister: GPU-based rendering of Boolean combinations of free-form triangulated shapes. In: Proceedings of Siggraph’05; 2005. p. 1024– 31. [5] Hable J, Rossignac J. CST: constructive solid trimming for rendering BReps and CSG. IEEE Trans Vis Comput Graph 2007;13(5):1004–14. [6] Hales TH. The Jordan curve theorem, formally and informally. Am Math Mon 2007;114(10):882–94. [7] Hoffmann CM. Geometric and solid modeling. An introduction. Morgan Kauffmann Publishing; 1989. [8] Hoffmann CM. Robustness in geometric computations. JCISE 2001;1:143–56. [9] Hubbard PM. Constructive solid geometry for triangulated polyhedra. Tech report CS-90-07. Brown CS; 1990. [10] Kobbelt LP, Botsch M, Schwanecke U, Seidel H-P. Feature sensitive surface extraction from volume data. In: SIGGRAPH ’01 proceedings; 2001.

60

C.J. Ogayar-Anguita et al. / Advances in Engineering Software 85 (2015) 51–60

[11] Krishnan S, Manocha D, Gopi M, Culver T, Keyser J. Boole: a boundary evaluation system for Boolean combinations of sculptured solids. Int J Comput Geom Appl 2001;11(1):105–44. [12] Kuratowski K, Mostowski A. Set theory. Amsterdam: North-Holland; 1976. [13] Laidlaw DH, Trumbore WB, Hughes JF. Constructive solid geometry for polyhedral objects. SIGGRAPH Proc 1986;20(4):161–70. [14] Mäntylä M, Tammine M. Localized set operations for solid modelling. Comput Graph 1983;17(3). [15] Mäntylä M. An introduction to solid modeling computer. Rockville, Maryland: Science Press; 1988. [16] Möller T. A fast triangle-triangle intersection test. J Graph Tools 1997;2:25–30. [17] Newman TS, Yi H. A survey of the marching cubes algorithm. Comput Graph 2006;30(5):854–79. [18] Ogayar CJ, Segura RJ, Feito FR. Point in solid strategies. Comput Graph 2005;29(4). [19] Pavic´ D, Campen M, Kobbelt L. Hybrid Booleans. Comput Graph Forum 2010;29:75–87. [20] Pfister H, Zwicker M, van Baar J, Gross M. Surfels: surface elements as rendering primitives. In: SIGGRAPH ’00; 2000. p. 335–42. [21] Pilz M, Kamel HA. Creation and boundary evaluation of CSG models. Eng Comput 1989;5:105–18. [22] Requicha AAG, Tilove RB. Mathematical foundations of constructive solid geometry. General topology of regular closed sets, Tech. Memo. 27, Production automation project. Univ Rochester, Rochester, NY; March 1978.

[23] Requicha AAG, Voelcker HB. Boolean operations in solid modeling: boundary evaluation and merging algorithms. IEEE Proc 1985;73(1):30–44. [24] Romero F, Velho L, Henrique de Figuereido L. Scalable GPU rendering of CSG models. Comput Graph 2008;32(5):526–39. [25] Schneider PJ, Eberly DH. Geometric tools for computer graphics. Morgan Kaufmann; 2002. [26] Smith JM, Dodgson NA. A topologically robust algorithm for Boolean operations on polyhedral shapes using approximate arithmetic. Comput Aided Des 2007;39(2). [27] Varadhan G, Krishnan S, Zhang L, Manocha D. Reliable implicit surface polygonization using visibility mapping. Symp Geom Process 2006:211–21. [28] Wang CCL, Leung YS, Chen Y. Solid modeling of polyhedral objects by layered depth-normal images on the GPU. Comput Aided Des 2010;42(6):535–44. [29] Wang CCL. Approximate Boolean operations on large polyhedral solids with partial mesh reconstruction. IEEE Trans Visual Comput Graph 2010;17(6): 836–49. [30] Wang CCL, Manocha D. Efficient boundary extraction of BSP solids based on clipping operations. IEEE Trans Visual Comput Graph 2013;19(1):16–29. [31] Yamaguchi F, Tokieda T. A unified algorithm for Boolean shape operations. IEEE Comput Graph Appl 1984;4(6). [32] Zhao H, Wang CC, Chen Y, Jin X. Parallel and efficient Boolean on polygonal solids. Vis Comput 2011;27(6–8).