csg.js

Source code: http://github.com/evanw/csg.js/
Documentation: http://evanw.github.com/csg.js/docs/

Introduction

Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean operations like union and intersection to combine 3D solids. This library implements CSG operations on meshes elegantly and concisely using BSP trees, and is meant to serve as an easily understandable implementation of the algorithm. All edge cases involving overlapping coplanar polygons in both solids are correctly handled.

Example usage:

var cube = CSG.cube();
var sphere = CSG.sphere({ radius: 1.3 });
var polygons = cube.subtract(sphere).toPolygons();

Operations

This library provides three CSG operations: union, subtract, and intersect. The operations are rendered below using lightgl.js and can be rotated by dragging the mouse if your browser supports WebGL.

a
b
a.union(b)
a.subtract(b)
a.intersect(b)

The solids a and b above were generated with the following code:

var a = CSG.cube({ center: [-0.25, -0.25, -0.25] });
var b = CSG.sphere({ radius: 1.3, center: [0.25, 0.25, 0.25] });

Combined CSG Example

Below is a solid constructed from a combination of operations:

a
b
c
d
e
a.intersect(b).subtract(c.union(d).union(e))

The solids above were generated with the following code:

var a = CSG.cube();
var b = CSG.sphere({ radius: 1.35, stacks: 12 });
var c = CSG.cylinder({ radius: 0.7, start: [-1, 0, 0], end: [1, 0, 0] });
var d = CSG.cylinder({ radius: 0.7, start: [0, -1, 0], end: [0, 1, 0] });
var e = CSG.cylinder({ radius: 0.7, start: [0, 0, -1], end: [0, 0, 1] });

Try it!

Edit the code below to construct your own solids. A browser with WebGL is required to view the results. The setColor(r, g, b) function sets the color of the solid using values between 0 and 1 (just for display, not part of csg.js):