Constructive Solid Geometry

Description

Union

Return a new CSG solid consisting of A and B

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
A.union(B)

+-------+            +-------+
|       |            |       |
|   A   |            |       |
|    +--+----+   =   |       +----+
+----+--+    |       +----+       |
     |   B   |            |       |
     |       |            |       |
     +-------+            +-------+

Subtract

Return a new CSG solid where B is subtracted from A

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
A.subtract(B)

+-------+            +-------+
|       |            |       |
|   A   |            |       |
|    +--+----+   =   |    +--+
+----+--+    |       +----+
     |   B   |
     |       |
     +-------+

Intersect

Return a new CSG solid where both A and B overlap

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
A.intersect(B)

+-------+
|       |
|   A   |
|    +--+----+   =   +--+
+----+--+    |       +--+
     |   B   |
     |       |
     +-------+

CSG Tree CSG Tree Image By User:Zottie - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=263170

Example

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import express from "express"
import path from "path"
import http from "http"

const port: number = 3000

class App {
    private server: http.Server
    private port: number

    constructor(port: number) {
        this.port = port
        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))
        app.use('/build/three.module.js', express.static(path.join(__dirname, '../../node_modules/three/build/three.module.js')))
        app.use('/jsm/controls/OrbitControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/OrbitControls.js')))
        app.use('/jsm/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js')))

        this.server = new http.Server(app);
    }

    public Start() {
        this.server.listen(this.port, () => {
            console.log(`Server listening on port ${this.port}.`)
        })
    }
}

new App(port).Start()

./src/client/utils/CSGMesh.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// ## License
// 
// Copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license.
// THREE.js rework by thrax
//
// # class CSG
// Holds a binary space partition tree representing a 3D solid. Two solids can
// be combined using the `union()`, `subtract()`, and `intersect()` methods.
//
// Differences Copyright 2020 Sean Bradley : https://sbcode.net/threejs/
// - Started with CSGMesh.js from https://github.com/manthrax/THREE-CSGMesh/blob/master/CSGMesh.js
// - Converted to TypeScript by adding type annotations to all variables
// - Converted var to const and let
// - More THREEJS integration (THREE r119)
// - Some Refactoring

import * as THREE from '/build/three.module.js'

class CSG {
    polygons: Polygon[]

    constructor() {
        this.polygons = [];
    }

    clone() {
        const csg = new CSG();
        csg.polygons = this.polygons.map(function (p) {
            return p.clone();
        });
        return csg;
    }

    toPolygons() {
        return this.polygons;
    }

    union(csg: CSG) {
        let a = new Node(this.clone().polygons);
        let b = new Node(csg.clone().polygons);
        a.clipTo(b);
        b.clipTo(a);
        b.invert();
        b.clipTo(a);
        b.invert();
        a.build(b.allPolygons());
        return CSG.fromPolygons(a.allPolygons());
    }

    subtract(csg: CSG) {
        let a = new Node(this.clone().polygons);
        let b = new Node(csg.clone().polygons);
        a.invert();
        a.clipTo(b);
        b.clipTo(a);
        b.invert();
        b.clipTo(a);
        b.invert();
        a.build(b.allPolygons());
        a.invert();
        return CSG.fromPolygons(a.allPolygons());
    }

    intersect(csg: CSG) {
        let a = new Node(this.clone().polygons);
        let b = new Node(csg.clone().polygons);
        a.invert();
        b.clipTo(a);
        b.invert();
        a.clipTo(b);
        b.clipTo(a);
        a.build(b.allPolygons());
        a.invert();
        return CSG.fromPolygons(a.allPolygons());
    }

    // Return a new CSG solid with solid and empty space switched. This solid is
    // not modified.
    inverse() {
        const csg = this.clone();
        csg.polygons.map(function (p) {
            p.flip();
        });
        return csg;
    }

    static fromPolygons = function (polygons: Polygon[]) {
        const csg = new CSG();
        csg.polygons = polygons;
        return csg;
    }

    static fromGeometry = function (geom: THREE.Geometry | THREE.BufferGeometry) {
        if ((geom as THREE.BufferGeometry).isBufferGeometry)
            geom = new THREE.Geometry().fromBufferGeometry(geom as THREE.BufferGeometry)
        const fs = (geom as THREE.Geometry).faces;
        const vs = (geom as THREE.Geometry).vertices;
        const polys = []
        const fm = ['a', 'b', 'c']
        for (let i = 0; i < fs.length; i++) {
            const f = fs[i];
            const vertices = []
            for (let j = 0; j < 3; j++) vertices.push(new Vertex(vs[f[fm[j]]], f.vertexNormals[j], (geom as any).faceVertexUvs[0][i][j]))
            polys.push(new Polygon(vertices))
        }
        return CSG.fromPolygons(polys)
    }
    private static _tmpm3 = new THREE.Matrix3();
    private static currentOp: string;
    private static sourceMesh: THREE.Mesh;
    private static currentPrim: CSG
    private static nextPrim: CSG
    private static doRemove: boolean

    static fromMesh = function (mesh: THREE.Mesh) {

        const csg = CSG.fromGeometry(mesh.geometry)
        CSG._tmpm3.getNormalMatrix(mesh.matrix);
        for (let i = 0; i < csg.polygons.length; i++) {
            let p = csg.polygons[i]
            for (let j = 0; j < p.vertices.length; j++) {
                let v = p.vertices[j]
                v.pos.applyMatrix4(mesh.matrix);
                v.normal.applyMatrix3(CSG._tmpm3);
            }
        }
        return csg;
    }

    static toMesh = function (csg: CSG, toMatrix: THREE.Matrix4) {
        const geom = new THREE.Geometry();
        const ps = csg.polygons;
        const vs = geom.vertices;
        const fvuv = geom.faceVertexUvs[0]
        for (let i = 0; i < ps.length; i++) {
            const p = ps[i]
            const pvs = p.vertices;
            const v0 = vs.length;
            const pvlen = pvs.length

            for (let j = 0; j < pvlen; j++)
                vs.push(new THREE.Vector3().copy(pvs[j].pos))

            for (let j = 3; j <= pvlen; j++) {
                const fc = new THREE.Face3(0, 0, 0);
                const fuv = []
                fvuv.push(fuv)
                const fnml = fc.vertexNormals;
                fc.a = v0;
                fc.b = v0 + j - 2;
                fc.c = v0 + j - 1;

                fnml.push(new THREE.Vector3().copy(pvs[0].normal))
                fnml.push(new THREE.Vector3().copy(pvs[j - 2].normal))
                fnml.push(new THREE.Vector3().copy(pvs[j - 1].normal))
                fuv.push(new THREE.Vector3().copy(pvs[0].uv))
                fuv.push(new THREE.Vector3().copy(pvs[j - 2].uv))
                fuv.push(new THREE.Vector3().copy(pvs[j - 1].uv))

                fc.normal = new THREE.Vector3().copy(p.plane.normal)
                geom.faces.push(fc)
            }
        }
        const inv = new THREE.Matrix4().getInverse(toMatrix);
        geom.applyMatrix4(inv);
        geom.verticesNeedUpdate = geom.elementsNeedUpdate = geom.normalsNeedUpdate = true;
        geom.computeBoundingSphere();
        geom.computeBoundingBox();
        const m = new THREE.Mesh(geom);
        m.matrix.copy(toMatrix);
        m.matrix.decompose(m.position, m.quaternion, m.scale)
        m.updateMatrixWorld();
        return m
    }


    static ieval = function (tokens: string | object | any[]) {
        if (typeof tokens === 'string')
            CSG.currentOp = tokens
        else if (tokens instanceof Array) {
            for (let i = 0; i < tokens.length; i++)CSG.ieval(tokens[i])
        } else if (tokens instanceof THREE.Mesh) {
            let op = CSG.currentOp;
            (tokens as THREE.Mesh).updateMatrix();
            (tokens as THREE.Mesh).updateMatrixWorld();
            if (!CSG.sourceMesh)
                CSG.currentPrim = CSG.fromMesh(CSG.sourceMesh = tokens)
            else {
                CSG.nextPrim = CSG.fromMesh(tokens)
                CSG.currentPrim = CSG.currentPrim[op](CSG.nextPrim)
            }
            if (CSG.doRemove) tokens.parent.remove(tokens)
        }//union,subtract,intersect,inverse
    }

    static eval = function (tokens: string | object | any[], doRemove: boolean) {//[['add',mesh,mesh,mesh,mesh],['sub',mesh,mesh,mesh,mesh]]
        CSG.currentOp = null;
        CSG.sourceMesh = null;
        CSG.doRemove = doRemove;
        CSG.ieval(tokens)
        const result = CSG.toMesh(CSG.currentPrim, CSG.sourceMesh.matrix);
        result.material = CSG.sourceMesh.material;
        result.castShadow = result.receiveShadow = true;
        return result;
    }
}

// Construct a CSG solid from a list of `Polygon` instances.


// # class Vector

// Represents a 3D vector.
// 
// Example usage:
// 
//     new CSG.Vector(1, 2, 3);
//     new CSG.Vector([1, 2, 3]);
//     new CSG.Vector({ x: 1, y: 2, z: 3 });

class Vector extends THREE.Vector3 {
    constructor(x: number | THREE.Vector3, y?: number, z?: number) {
        if (arguments.length == 3) {
            super((x as number), y, z)
        } else if (Array.isArray(x)) {
            super(x[0], x[1], x[2])
        } else if (x instanceof THREE.Vector3) {
            super()
            this.set((x as THREE.Vector3).x, (x as THREE.Vector3).y, (x as THREE.Vector3).z)
        }
        else
            throw "Invalid constructor to vector"
    }

    clone(): any {
        return new Vector(this.x, this.y, this.z);
    }
    negate() {
        return this.clone().multiplyScalar(-1)
    }
    plus(a: THREE.Vector3) {
        return this.clone().add(a);
    }
    minus(a: THREE.Vector3) {
        return this.clone().sub(a)
    }
    times(a: THREE.Vector3) {
        return this.clone().multiplyScalar(a)
    }
    dividedBy(a: number) {
        return this.clone().divideScalar(a)
    }
    lerp(a: Vector, t: number) {
        return this.plus(a.minus(this).times(t))
    }
    unit() {
        return this.dividedBy(this.length())
    }
    cross(a) {
        return THREE.Vector3.prototype.cross.call(this.clone(), a)
    }
}

// # class Vertex

// Represents a vertex of a polygon. Use your own vertex class instead of this
// one to provide additional features like texture coordinates and vertex
// colors. Custom vertex classes need to provide a `pos` property and `clone()`,
// `flip()`, and `interpolate()` methods that behave analogous to the ones
// defined by `CSG.Vertex`. This class provides `normal` so convenience
// functions like `CSG.sphere()` can return a smooth vertex normal, but `normal`
// is not used anywhere else.

class Vertex {

    pos: THREE.Vector3
    normal: THREE.Vector3
    uv: THREE.Vector3

    constructor(pos: THREE.Vector3, normal: THREE.Vector3, uv?: THREE.Vector3) {
        this.pos = new Vector(pos.x, pos.y, pos.z);
        this.normal = new Vector(normal.x, normal.y, normal.z);
        if (uv) this.uv = new Vector(uv.x, uv.y, uv.z);
    }


    clone() {
        return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
    }

    // Invert all orientation-specific data (e.g. vertex normal). Called when the
    // orientation of a polygon is flipped.
    flip() {
        this.normal = this.normal.negate();
    }

    // Create a new vertex between this vertex and `other` by linearly
    // interpolating all properties using a parameter of `t`. Subclasses should
    // override this to interpolate additional properties.
    interpolate(other: Vertex, t: number) {
        return new Vertex(this.pos.lerp(other.pos, t), this.normal.lerp(other.normal, t), this.uv.lerp(other.uv, t))
    }
}
// # class Plane

// Represents a plane in 3D space.

class Plane {
    normal: Vector
    w: number
    constructor(normal: Vector, w: number) {
        this.normal = normal
        this.w = w
    }

    clone() {
        return new Plane(this.normal.clone(), this.w)
    }

    flip() {
        this.normal = this.normal.negate()
        this.w = -this.w
    }

    // Split `polygon` by this plane if needed, then put the polygon or polygon
    // fragments in the appropriate lists. Coplanar polygons go into either
    // `coplanarFront` or `coplanarBack` depending on their orientation with
    // respect to this plane. Polygons in front or in back of this plane go into
    // either `front` or `back`.
    splitPolygon(polygon: Polygon, coplanarFront: Polygon[], coplanarBack: Polygon[], front: Polygon[], back: Polygon[]) {
        const COPLANAR = 0
        const FRONT = 1
        const BACK = 2
        const SPANNING = 3

        // Classify each point as well as the entire polygon into one of the above
        // four classes.
        let polygonType = 0
        const types = []
        for (let i = 0; i < polygon.vertices.length; i++) {
            const t = this.normal.dot(polygon.vertices[i].pos) - this.w
            const type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR
            polygonType |= type
            types.push(type)
        }

        // Put the polygon in the correct list, splitting it when necessary.
        switch (polygonType) {
            case COPLANAR:
                (this.normal.dot(polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon)
                break
            case FRONT:
                front.push(polygon)
                break
            case BACK:
                back.push(polygon)
                break
            case SPANNING:
                const f = []
                const b = []
                for (let i = 0; i < polygon.vertices.length; i++) {
                    const j = (i + 1) % polygon.vertices.length
                    const ti = types[i]
                    const tj = types[j]
                    const vi = polygon.vertices[i]
                    const vj = polygon.vertices[j]
                    if (ti != BACK)
                        f.push(vi)
                    if (ti != FRONT)
                        b.push(ti != BACK ? vi.clone() : vi)
                    if ((ti | tj) == SPANNING) {
                        const t = (this.w - this.normal.dot(vi.pos)) / this.normal.dot((vj.pos as Vector).minus(vi.pos))
                        const v = vi.interpolate(vj, t)
                        f.push(v)
                        b.push(v.clone())
                    }
                }
                if (f.length >= 3)
                    front.push(new Polygon(f, polygon.shared));
                if (b.length >= 3)
                    back.push(new Polygon(b, polygon.shared));
                break
        }
    }


    // `Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
    // point is on the plane.
    static EPSILON = 1e-5

    static fromPoints = function (a: Vector, b: Vector, c: Vector) {
        const n = b.minus(a).cross(c.minus(a)).unit()
        return new Plane(n, n.dot(a))
    }

}



// # class Polygon

// Represents a convex polygon. The vertices used to initialize a polygon must
// be coplanar and form a convex loop. They do not have to be `Vertex`
// instances but they must behave similarly (duck typing can be used for
// customization).
// 
// Each convex polygon has a `shared` property, which is shared between all
// polygons that are clones of each other or were split from the same polygon.
// This can be used to define per-polygon properties (such as surface color).

class Polygon {

    vertices: Vertex[]
    shared: object
    plane: Plane

    constructor(vertices: Vertex[], shared?: object) {
        this.vertices = vertices;
        this.shared = shared;
        this.plane = Plane.fromPoints(vertices[0].pos as Vector, vertices[1].pos as Vector, vertices[2].pos as Vector);
    }

    clone() {
        const vertices = this.vertices.map(function (v) {
            return v.clone();
        });
        return new Polygon(vertices, this.shared);
    }
    flip() {
        this.vertices.reverse().map(function (v) {
            v.flip();
        });
        this.plane.flip();
    }
}

// # class Node

// Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
// by picking a polygon to split along. That polygon (and all other coplanar
// polygons) are added directly to that node and the other polygons are added to
// the front and/or back subtrees. This is not a leafy BSP tree since there is
// no distinction between internal and leaf nodes.

class Node {
    plane: Plane
    front: Node
    back: Node
    polygons: Polygon[]

    constructor(polygons?: Polygon[]) {
        this.plane = null
        this.front = null
        this.back = null
        this.polygons = []
        if (polygons)
            this.build(polygons)
    }
    clone() {
        const node = new Node()
        node.plane = this.plane && this.plane.clone()
        node.front = this.front && this.front.clone()
        node.back = this.back && this.back.clone()
        node.polygons = this.polygons.map(function (p) {
            return p.clone()
        });
        return node
    }

    // Convert solid space to empty space and empty space to solid space.
    invert() {
        for (let i = 0; i < this.polygons.length; i++)
            this.polygons[i].flip()

        this.plane.flip()
        if (this.front)
            this.front.invert()
        if (this.back)
            this.back.invert()
        const temp = this.front
        this.front = this.back
        this.back = temp
    }

    // Recursively remove all polygons in `polygons` that are inside this BSP
    // tree.
    clipPolygons(polygons: Polygon[]) {
        if (!this.plane)
            return polygons.slice()
        let front = []
        let back = []
        for (let i = 0; i < polygons.length; i++) {
            this.plane.splitPolygon(polygons[i], front, back, front, back)
        }
        if (this.front)
            front = this.front.clipPolygons(front)
        if (this.back)
            back = this.back.clipPolygons(back)
        else
            back = []
        return front.concat(back)
    }

    // Remove all polygons in this BSP tree that are inside the other BSP tree
    // `bsp`.
    clipTo(bsp: Node) {
        this.polygons = bsp.clipPolygons(this.polygons);
        if (this.front)
            this.front.clipTo(bsp);
        if (this.back)
            this.back.clipTo(bsp);
    }

    // Return a list of all polygons in this BSP tree.
    allPolygons() {
        let polygons = this.polygons.slice();
        if (this.front)
            polygons = polygons.concat(this.front.allPolygons());
        if (this.back)
            polygons = polygons.concat(this.back.allPolygons());
        return polygons;
    }

    // Build a BSP tree out of `polygons`. When called on an existing tree, the
    // new polygons are filtered down to the bottom of the tree and become new
    // nodes there. Each set of polygons is partitioned using the first polygon
    // (no heuristic is used to pick a good split).
    build(polygons: Polygon[]) {
        if (!polygons.length)
            return;
        if (!this.plane)
            this.plane = polygons[0].plane.clone();
        let front = []
        let back = []
        for (let i = 0; i < polygons.length; i++) {
            this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back)
        }
        if (front.length) {
            if (!this.front)
                this.front = new Node()
            this.front.build(front)
        }
        if (back.length) {
            if (!this.back)
                this.back = new Node()
            this.back.build(back)
        }
    }
}

export default CSG

// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.union(B)
// 
//     +-------+            +-------+
//     |       |            |       |
//     |   A   |            |       |
//     |    +--+----+   =   |       +----+
//     +----+--+    |       +----+       |
//          |   B   |            |       |
//          |       |            |       |
//          +-------+            +-------+
// 
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.subtract(B)
// 
//     +-------+            +-------+
//     |       |            |       |
//     |   A   |            |       |
//     |    +--+----+   =   |    +--+
//     +----+--+    |       +----+
//          |   B   |
//          |       |
//          +-------+
// 
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.intersect(B)
// 
//     +-------+
//     |       |
//     |   A   |
//     |    +--+----+   =   +--+
//     +----+--+    |       +--+
//          |   B   |
//          |       |
//          +-------+
// 

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import Stats from '/jsm/libs/stats.module'
import CSG from './utils/CSGMesh.js'

const scene: THREE.Scene = new THREE.Scene()

var light1 = new THREE.SpotLight();
light1.position.set(2.5, 5, 5)
light1.angle = Math.PI / 4
light1.penumbra = 0.5
light1.castShadow = true;
light1.shadow.mapSize.width = 1024;
light1.shadow.mapSize.height = 1024;
light1.shadow.camera.near = 0.5;
light1.shadow.camera.far = 20
scene.add(light1);

var light2 = new THREE.SpotLight();
light2.position.set(-2.5, 5, 5)
light2.angle = Math.PI / 4
light2.penumbra = 0.5
light2.castShadow = true;
light2.shadow.mapSize.width = 1024;
light2.shadow.mapSize.height = 1024;
light2.shadow.camera.near = 0.5;
light2.shadow.camera.far = 20
scene.add(light2);

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.x = .5
camera.position.y = 2
camera.position.z = 2.5

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)

const material = new THREE.MeshPhongMaterial({ map: new THREE.TextureLoader().load('img/grid.png') })

{
    //create a cube and sphere and intersect them
    const cubeMesh = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshPhongMaterial({ color: 0xff0000 }));
    const sphereMesh = new THREE.Mesh(new THREE.SphereGeometry(1.45, 8, 8), new THREE.MeshPhongMaterial({ color: 0x0000ff }));
    const cylinderMesh1 = new THREE.Mesh(new THREE.CylinderGeometry(.85, .85, 2, 8, 1, false), new THREE.MeshPhongMaterial({ color: 0x00ff00 }));
    const cylinderMesh2 = new THREE.Mesh(new THREE.CylinderGeometry(.85, .85, 2, 8, 1, false), new THREE.MeshPhongMaterial({ color: 0x00ff00 }));
    const cylinderMesh3 = new THREE.Mesh(new THREE.CylinderGeometry(.85, .85, 2, 8, 1, false), new THREE.MeshPhongMaterial({ color: 0x00ff00 }));

    cubeMesh.position.set(-5, 0, -6)
    scene.add(cubeMesh)
    sphereMesh.position.set(-2, 0, -6)
    scene.add(sphereMesh)

    const cubeCSG = CSG.fromMesh(cubeMesh);
    const sphereCSG = CSG.fromMesh(sphereMesh);

    const cubeSphereIntersectCSG = cubeCSG.intersect(sphereCSG);
    const cubeSphereIntersectMesh = CSG.toMesh(cubeSphereIntersectCSG, new THREE.Matrix4());

    cubeSphereIntersectMesh.material = new THREE.MeshPhongMaterial({ color: 0xff00ff });
    cubeSphereIntersectMesh.position.set(-2.5, 0, -3)
    scene.add(cubeSphereIntersectMesh);



    //create 3 cylinders at different rotations and union them
    cylinderMesh1.position.set(1, 0, -6)
    scene.add(cylinderMesh1)
    cylinderMesh2.position.set(3, 0, -6)
    cylinderMesh2.geometry.rotateX(Math.PI / 2)
    scene.add(cylinderMesh2)
    cylinderMesh3.position.set(5, 0, -6)
    cylinderMesh3.geometry.rotateZ(Math.PI / 2)
    scene.add(cylinderMesh3)

    const cylinderCSG1 = CSG.fromMesh(cylinderMesh1);
    const cylinderCSG2 = CSG.fromMesh(cylinderMesh2);
    const cylinderCSG3 = CSG.fromMesh(cylinderMesh3);

    const cylindersUnionCSG = cylinderCSG1.union(cylinderCSG2.union(cylinderCSG3));
    const cylindersUnionMesh = CSG.toMesh(cylindersUnionCSG, new THREE.Matrix4());

    cylindersUnionMesh.material = new THREE.MeshPhongMaterial({ color: 0xffa500 });
    cylindersUnionMesh.position.set(2.5, 0, -3)
    scene.add(cylindersUnionMesh);



    //subtract the cylindersUnionCSG from the cubeSphereIntersectCSG
    const finalCSG = cubeSphereIntersectCSG.subtract(cylindersUnionCSG)
    const finalMesh = CSG.toMesh(finalCSG, new THREE.Matrix4());
    finalMesh.material = material;
    scene.add(finalMesh);

}

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

const stats = Stats()
document.body.appendChild(stats.dom)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    render()

    stats.update()
};

function render() {
    renderer.render(scene, camera)
}
animate();

Constructive Solid Geometry