CSG.js

Source code: http://github.com/code4fukui/CSG.js/
Documentation: http://code4fukui.github.io/CSG.js/tests/
forked from: evanw/csg.js

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:

import { CSG } from "https://code4fukui.github.io/CSG.js/CSG.js";

const cube = CSG.cube();
const sphere = CSG.sphere({ radius: 1.3 });
const 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:

const a = CSG.cube({ center: [-0.25, -0.25, -0.25] });
const 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:

const a = CSG.cube();
const b = CSG.sphere({ radius: 1.35, stacks: 12 });
const c = CSG.cylinder({ radius: 0.7, start: [-1, 0, 0], end: [1, 0, 0] });
const d = CSG.cylinder({ radius: 0.7, start: [0, -1, 0], end: [0, 1, 0] });
const 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):