Boolean Operations on Meshes

Contents
[ ]

Boolean Operations on Meshes

Aspose.3D for .NET lets you apply boolean operations on meshes through the BooleanOperator class. The supported operation kinds are defined by the BooleanOperation enum:

  • Add — union of two meshes
  • Intersect — the shared volume of two meshes
  • Sub — the first mesh minus the second mesh

Each operand of a boolean operation can be an instance of Node, any entity that implements IMeshConvertible (like Mesh), or a HalfSpace. For two plain meshes the Mesh.DoBoolean static method applies the operation directly, accepting a transformation matrix for each operand.

Union of Two Overlapping Meshes

This code example calculates the union of two overlapping box meshes:

// Create two overlapping box meshes
var a = new Box(1, 1, 1).ToMesh();
var b = new Box(1, 1, 1).ToMesh();
// Translate the second box by (0.25, 0, 0) so the two boxes overlap
var transform = new Matrix4(
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0.25, 0, 0, 1);
// Union of the two boxes
var union = Mesh.DoBoolean(BooleanOperation.Add, a, transform, b, null);
Console.WriteLine("The union mesh has {0} polygons", union.PolygonCount);

Cut a Mesh with a Half Space

A HalfSpace represents an infinite space divided by a plane, defined by its Normal and a Position on the plane. Cutting a mesh with a half space keeps the portion of the mesh on the positive side of the plane — the side the normal points to. Use the BooleanOperation.Sub operation with a HalfSpace operand:

// Create a scene with a box mesh
var scene = new Scene();
var boxNode = scene.RootNode.CreateChildNode("box", new Box(2, 2, 2).ToMesh());
// Define a half space whose plane passes through (0, 0, 0.5)
// and whose normal points to +Z
var halfSpace = new HalfSpace(new Vector3(0, 0, 1), new Vector3(0, 0, 0.5));
// Cut the box, this keeps the part of the box above z = 0.5
var op = new BooleanOperator();
op.Operator = BooleanOperation.Sub;
op.First = BooleanOperand.Of(boxNode);
op.Second = BooleanOperand.Of(halfSpace);
Mesh cut = op.ToMesh();
Console.WriteLine("The cut mesh has {0} polygons", cut.PolygonCount);