Cannon.js Debug Renderer

Video Lecture

Cannon.js Debug Renderer Cannon.js Debug Renderer Cannon.js Debug Renderer

Description

We can use the CannonDebugRenderer to help visualize the shapes used in the Cannon.js physics world. The shapes will be rendered in the Three.js canvas as wire frames.

Start Scripts

./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
30
31
32
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')))
        app.use('/jsm/libs/dat.gui.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/dat.gui.module.js')))
        app.use('/jsm/loaders/OBJLoader', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/loaders/OBJLoader.js')))
        app.use('/cannon/cannon.min', express.static(path.join(__dirname, '../../node_modules/cannon/build/cannon.min.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/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
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
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import Stats from '/jsm/libs/stats.module'
import { GUI } from '/jsm/libs/dat.gui.module'
import '/cannon/cannon.min'
//import CannonDebugRenderer from './utils/cannonDebugRenderer.js'
//import { OBJLoader } from '/jsm/loaders/OBJLoader'

const scene: THREE.Scene = new THREE.Scene()
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)

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)

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(renderer.domElement)

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

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)
//world.broadphase = new CANNON.NaiveBroadphase() //
//world.solver.iterations = 10
//world.allowSleep = true

const normalMaterial: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial()
const phongMaterial: THREE.MeshPhongMaterial = new THREE.MeshPhongMaterial()

const cubeGeometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1)
const cubeMesh: THREE.Mesh = new THREE.Mesh(cubeGeometry, normalMaterial)
cubeMesh.position.x = -3
cubeMesh.position.y = 3
cubeMesh.castShadow = true
scene.add(cubeMesh)
const cubeShape = new CANNON.Box(new CANNON.Vec3(.5, .5, .5))
const cubeBody = new CANNON.Body({ mass: 1 });
cubeBody.addShape(cubeShape)
cubeBody.position.x = cubeMesh.position.x
cubeBody.position.y = cubeMesh.position.y
cubeBody.position.z = cubeMesh.position.z
world.addBody(cubeBody)

const sphereGeometry: THREE.SphereGeometry = new THREE.SphereGeometry()
const sphereMesh: THREE.Mesh = new THREE.Mesh(sphereGeometry, normalMaterial)
sphereMesh.position.x = -1
sphereMesh.position.y = 3
sphereMesh.castShadow = true
scene.add(sphereMesh)
const sphereShape = new CANNON.Sphere(1)
const sphereBody = new CANNON.Body({ mass: 1 });
sphereBody.addShape(sphereShape)
sphereBody.position.x = sphereMesh.position.x
sphereBody.position.y = sphereMesh.position.y
sphereBody.position.z = sphereMesh.position.z
world.addBody(sphereBody)

// const cylinderGeometry: THREE.CylinderGeometry = new THREE.CylinderGeometry(1, 1, 2, 8)
// const cylinderMesh: THREE.Mesh = new THREE.Mesh(cylinderGeometry, normalMaterial)
// cylinderMesh.position.x = 0
// cylinderMesh.position.y = 3
// cylinderMesh.castShadow = true
// scene.add(cylinderMesh)
// const cylinderShape = new CANNON.Cylinder(1, 1, 2, 8)
// const cylinderBody = new CANNON.Body({ mass: 1 });
// //const cylinderQuaternion = new CANNON.Quaternion()
// //cylinderQuaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Math.PI / 2)
// cylinderBody.addShape(cylinderShape) //, new CANNON.Vec3, cylinderQuaternion)
// cylinderBody.position.x = cylinderMesh.position.x
// cylinderBody.position.y = cylinderMesh.position.y
// cylinderBody.position.z = cylinderMesh.position.z
// world.addBody(cylinderBody)

const icosahedronGeometry: THREE.IcosahedronGeometry = new THREE.IcosahedronGeometry(1, 0)
const icosahedronMesh: THREE.Mesh = new THREE.Mesh(icosahedronGeometry, normalMaterial)
icosahedronMesh.position.x = 1
icosahedronMesh.position.y = 3
icosahedronMesh.castShadow = true
scene.add(icosahedronMesh)
// const icosahedronPoints = (<THREE.Geometry>icosahedronMesh.geometry).vertices.map(function (v) {
//     return new CANNON.Vec3(v.x, v.y, v.z)
// })
// const icosahedronFaces = (<THREE.Geometry>icosahedronMesh.geometry).faces.map(function (f) {
//     return [f.a, f.b, f.c]
// })
// const icosahedronShape = new CANNON.ConvexPolyhedron(icosahedronPoints, icosahedronFaces)
const icosahedronShape = CreateConvexPolyhedron(icosahedronMesh.geometry)
const icosahedronBody = new CANNON.Body({ mass: 1 });
icosahedronBody.addShape(icosahedronShape)
icosahedronBody.position.x = icosahedronMesh.position.x
icosahedronBody.position.y = icosahedronMesh.position.y
icosahedronBody.position.z = icosahedronMesh.position.z
world.addBody(icosahedronBody)

const torusKnotGeometry: THREE.TorusKnotGeometry = new THREE.TorusKnotGeometry()
const torusKnotMesh: THREE.Mesh = new THREE.Mesh(torusKnotGeometry, normalMaterial)
torusKnotMesh.position.x = 3
torusKnotMesh.position.y = 3
torusKnotMesh.castShadow = true
scene.add(torusKnotMesh)
const torusKnotShape = CreateTrimesh(<THREE.Geometry>torusKnotMesh.geometry)
const torusKnotBody = new CANNON.Body({ mass: 1 });
torusKnotBody.addShape(torusKnotShape)
torusKnotBody.position.x = torusKnotMesh.position.x
torusKnotBody.position.y = torusKnotMesh.position.y
torusKnotBody.position.z = torusKnotMesh.position.z
world.addBody(torusKnotBody)

// let monkeyMesh: THREE.Object3D
// let monkeyBody: CANNON.Body
// let monkeyLoaded: Boolean = false
// const objLoader: OBJLoader = new OBJLoader();
// objLoader.load(
//     'models/monkey.obj',
//     (object) => {
//         scene.add(object)
//         monkeyMesh = object.children[0];
//         (monkeyMesh as THREE.Mesh).material = normalMaterial
//         monkeyMesh.position.x = -2
//         monkeyMesh.position.y = 20
//         const monkeyShape = CreateTrimesh((monkeyMesh as THREE.Mesh).geometry)
//         monkeyBody = new CANNON.Body({ mass: 1 });
//         monkeyBody.addShape(monkeyShape)
//         // monkeyBody.addShape(cubeShape)
//         // monkeyBody.addShape(sphereShape)
//         // monkeyBody.addShape(cylinderShape)
//         // monkeyBody.addShape(icosahedronShape)
//         // monkeyBody.addShape(new CANNON.Plane())
//         // monkeyBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Math.PI / 2)
//         monkeyBody.position.x = monkeyMesh.position.x
//         monkeyBody.position.y = monkeyMesh.position.y
//         monkeyBody.position.z = monkeyMesh.position.z
//         world.addBody(monkeyBody)
//         monkeyLoaded = true
//     },
//     (xhr) => {
//         console.log((xhr.loaded / xhr.total * 100) + '% loaded');
//     },
//     (error) => {
//         console.log('An error happened');
//     }
// );

const planeGeometry: THREE.PlaneGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh: THREE.Mesh = new THREE.Mesh(planeGeometry, phongMaterial)
planeMesh.rotateX(-Math.PI / 2)
planeMesh.receiveShadow = true;
scene.add(planeMesh)
const planeShape = new CANNON.Plane()
const planeBody = new CANNON.Body({ mass: 0 })
planeBody.addShape(planeShape)
planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
world.addBody(planeBody)

function CreateTrimesh(geometry: THREE.Geometry | THREE.BufferGeometry): CANNON.Trimesh {
    if (!(geometry as THREE.BufferGeometry).attributes) {
        geometry = new THREE.BufferGeometry().fromGeometry(geometry as THREE.Geometry);
    }
    const vertices: number[] = <number[]>(geometry as THREE.BufferGeometry).attributes.position.array
    const indices: number[] = Object.keys(vertices).map(Number);
    return new CANNON.Trimesh(vertices, indices);
}

function CreateConvexPolyhedron(geometry: THREE.Geometry | THREE.BufferGeometry): CANNON.ConvexPolyhedron {
    if (!(geometry as THREE.Geometry).vertices) {
        geometry = new THREE.Geometry().fromBufferGeometry(geometry as THREE.BufferGeometry);
    }
    const points: CANNON.Vec3[] = (<THREE.Geometry>geometry).vertices.map(function (v) {
        return new CANNON.Vec3(v.x, v.y, v.z)
    })
    const faces: number[][] = (<THREE.Geometry>geometry).faces.map(function (f) {
        return [f.a, f.b, f.c]
    })
    return new CANNON.ConvexPolyhedron(points, faces);
}

camera.position.y = 4
camera.position.z = 4
controls.target.y = 2

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)

const gui = new GUI()
const physicsFolder = gui.addFolder("Physics")
physicsFolder.add(world.gravity, "x", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "y", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "z", -10.0, 10.0, 0.1)
physicsFolder.open()

const clock: THREE.Clock = new THREE.Clock()

//const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    let delta = clock.getDelta()
    if (delta > .1) delta = .1
    world.step(delta)
    //cannonDebugRenderer.update()

    // Copy coordinates from Cannon.js to Three.js
    cubeMesh.position.set(cubeBody.position.x, cubeBody.position.y, cubeBody.position.z);
    cubeMesh.quaternion.set(cubeBody.quaternion.x, cubeBody.quaternion.y, cubeBody.quaternion.z, cubeBody.quaternion.w);
    sphereMesh.position.set(sphereBody.position.x, sphereBody.position.y, sphereBody.position.z);
    sphereMesh.quaternion.set(sphereBody.quaternion.x, sphereBody.quaternion.y, sphereBody.quaternion.z, sphereBody.quaternion.w);
    //cylinderMesh.position.set(cylinderBody.position.x, cylinderBody.position.y, cylinderBody.position.z);
    //cylinderMesh.quaternion.set(cylinderBody.quaternion.x, cylinderBody.quaternion.y, cylinderBody.quaternion.z, cylinderBody.quaternion.w);
    icosahedronMesh.position.set(icosahedronBody.position.x, icosahedronBody.position.y, icosahedronBody.position.z);
    icosahedronMesh.quaternion.set(icosahedronBody.quaternion.x, icosahedronBody.quaternion.y, icosahedronBody.quaternion.z, icosahedronBody.quaternion.w);
    torusKnotMesh.position.set(torusKnotBody.position.x, torusKnotBody.position.y, torusKnotBody.position.z);
    torusKnotMesh.quaternion.set(torusKnotBody.quaternion.x, torusKnotBody.quaternion.y, torusKnotBody.quaternion.z, torusKnotBody.quaternion.w);
    // if (monkeyLoaded) {
    //     monkeyMesh.position.set(monkeyBody.position.x, monkeyBody.position.y, monkeyBody.position.z);
    //     monkeyMesh.quaternion.set(monkeyBody.quaternion.x, monkeyBody.quaternion.y, monkeyBody.quaternion.z, monkeyBody.quaternion.w);
    // }

    render()

    stats.update()
};

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

./src/client/utils/cannonDebugRenderer.ts

Create a new folder at ./src/client/utils and save this file cannonDebugRenderer.ts. Take note that the extension is .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
// MIT License
// Original file https://github.com/schteppe/cannon.js/blob/908aa1e954b54d05a43dd708584e882dfe30ae29/tools/threejs/CannonDebugRenderer.js CopyRight https://github.com/schteppe
// Differences Copyright 2020 Sean Bradley : https://sbcode.net/threejs/
// - Added import statements for THREE
// - Converted to a class with a default export,
// - Converted to TypeScript
// - Added cylinder geometry, particle geometry and material
// - Highlight faces that the CONVEXPOLYHEDRON thinks are pointing into the shape.

import * as THREE from "/build/three.module.js";

export default class CannonDebugRenderer {
  public scene: THREE.Scene;
  public world: CANNON.World;
  private _meshes: THREE.Mesh[] | THREE.Points[];
  private _material: THREE.MeshBasicMaterial;
  private _particleMaterial = new THREE.PointsMaterial();
  private _sphereGeometry: THREE.SphereGeometry;
  private _boxGeometry: THREE.BoxGeometry;
  private _planeGeometry: THREE.PlaneGeometry;
  private _cylinderGeometry: THREE.CylinderGeometry;
  private _particleGeometry: THREE.Geometry;

  private tmpVec0: CANNON.Vec3 = new CANNON.Vec3()
  private tmpVec1: CANNON.Vec3 = new CANNON.Vec3()
  private tmpVec2: CANNON.Vec3 = new CANNON.Vec3()
  private tmpQuat0: CANNON.Quaternion = new CANNON.Quaternion()

  constructor(scene: THREE.Scene, world: CANNON.World, options?: object) {
    options = options || {}

    this.scene = scene
    this.world = world

    this._meshes = new Array()

    this._material = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      wireframe: true
    });
    this._particleMaterial = new THREE.PointsMaterial({
      color: 0xff0000,
      size: 10,
      sizeAttenuation: false,
      depthTest: false
    });
    this._sphereGeometry = new THREE.SphereGeometry(1);
    this._boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    this._planeGeometry = new THREE.PlaneGeometry(10, 10, 10, 10);
    this._cylinderGeometry = new THREE.CylinderGeometry(1, 1, 10, 10);
    this._particleGeometry = new THREE.Geometry();
    this._particleGeometry.vertices.push(new THREE.Vector3(0, 0, 0));
  }

  public update() {
    const bodies: CANNON.Body[] = this.world.bodies;
    const meshes: THREE.Mesh[] | THREE.Points[] = this._meshes;
    const shapeWorldPosition: CANNON.Vec3 = this.tmpVec0;
    const shapeWorldQuaternion: CANNON.Quaternion = this.tmpQuat0;

    let meshIndex = 0;

    for (let i = 0; i !== bodies.length; i++) {
      const body = bodies[i];

      for (let j = 0; j !== body.shapes.length; j++) {
        let shape = body.shapes[j];

        this._updateMesh(meshIndex, body, shape);

        let mesh = meshes[meshIndex];

        if (mesh) {
          // Get world position
          body.quaternion.vmult(body.shapeOffsets[j], shapeWorldPosition);
          body.position.vadd(shapeWorldPosition, shapeWorldPosition);

          // Get world quaternion
          body.quaternion.mult(body.shapeOrientations[j], shapeWorldQuaternion);

          // Copy to meshes
          mesh.position.x = shapeWorldPosition.x;
          mesh.position.y = shapeWorldPosition.y;
          mesh.position.z = shapeWorldPosition.z;
          mesh.quaternion.x = shapeWorldQuaternion.x;
          mesh.quaternion.y = shapeWorldQuaternion.y;
          mesh.quaternion.z = shapeWorldQuaternion.z;
          mesh.quaternion.w = shapeWorldQuaternion.w;
        }

        meshIndex++;
      }
    }

    for (let i = meshIndex; i < meshes.length; i++) {
      const mesh: THREE.Mesh | THREE.Points = meshes[i];
      if (mesh) {
        this.scene.remove(mesh);
      }
    }

    meshes.length = meshIndex;
  }

  private _updateMesh(index: number, body: CANNON.Body, shape: CANNON.Shape) {
    let mesh = this._meshes[index];
    if (!this._typeMatch(mesh, shape)) {
      if (mesh) {
        this.scene.remove(mesh);
      }
      mesh = this._meshes[index] = this._createMesh(shape);
    }
    this._scaleMesh(mesh, shape);
  }

  private _typeMatch(
    mesh: THREE.Mesh | THREE.Points,
    shape: CANNON.Shape
  ): Boolean {
    if (!mesh) {
      return false;
    }
    const geo: THREE.Geometry | THREE.BufferGeometry = mesh.geometry;
    return (
      (geo instanceof THREE.SphereGeometry && shape instanceof CANNON.Sphere) ||
      (geo instanceof THREE.BoxGeometry && shape instanceof CANNON.Box) ||
      (geo instanceof THREE.PlaneGeometry && shape instanceof CANNON.Plane) ||
      (geo.id === shape.geometryId &&
        shape instanceof CANNON.ConvexPolyhedron) ||
      (geo.id === shape.geometryId && shape instanceof CANNON.Trimesh) ||
      (geo.id === shape.geometryId && shape instanceof CANNON.Heightfield)
    );
  }

  private _createMesh(shape: CANNON.Shape): THREE.Mesh | THREE.Points {
    let mesh: THREE.Mesh | THREE.Points = new THREE.Mesh()
    let geometry: THREE.Geometry
    let v0: CANNON.Vec3
    let v1: CANNON.Vec3
    let v2: CANNON.Vec3
    const material: THREE.MeshBasicMaterial = this._material;

    switch (shape.type) {
      case CANNON.Shape.types.SPHERE:
        mesh = new THREE.Mesh(this._sphereGeometry, material);
        break;

      case CANNON.Shape.types.BOX:
        mesh = new THREE.Mesh(this._boxGeometry, material);
        break;

      case CANNON.Shape.types.PLANE:
        mesh = new THREE.Mesh(this._planeGeometry, material);
        break;

      case CANNON.Shape.types.CYLINDER:
        mesh = new THREE.Mesh(this._cylinderGeometry, material);
        break;

      case CANNON.Shape.types.PARTICLE:
        mesh = new THREE.Points(this._particleGeometry, this._particleMaterial);
        break;

      case CANNON.Shape.types.CONVEXPOLYHEDRON:
        // Create mesh
        geometry = new THREE.Geometry();

        // Add vertices
        for (
          let i = 0;
          i < (shape as CANNON.ConvexPolyhedron).vertices.length;
          i++
        ) {
          const v = (shape as CANNON.ConvexPolyhedron).vertices[i];
          geometry.vertices.push(new THREE.Vector3(v.x, v.y, v.z));
        }

        for (
          let i = 0;
          i < (shape as CANNON.ConvexPolyhedron).faces.length;
          i++
        ) {
          const face = (shape as CANNON.ConvexPolyhedron).faces[i];

          // add triangles
          const a = face[0];
          for (let j = 1; j < face.length - 1; j++) {
            const b = face[j];
            const c = face[j + 1];
            geometry.faces.push(new THREE.Face3(a, b, c));
          }
        }
        geometry.computeBoundingSphere();
        geometry.computeFaceNormals();

        mesh = new THREE.Mesh(geometry, material);
        shape.geometryId = geometry.id;

        //highlight faces that the CONVEXPOLYHEDRON thinks are pointing into the shape.
        geometry.faces.forEach(f => {
          const n = f.normal;
          n.negate();
          f.normal = n;
          const v1 = geometry.vertices[f.a];
          if (n.dot(v1) > 0) {
            const v2 = geometry.vertices[f.b];
            const v3 = geometry.vertices[f.c];

            const p = new THREE.Vector3();
            p.x = (v1.x + v2.x + v3.x) / 3;
            p.y = (v1.y + v2.y + v3.y) / 3;
            p.z = (v1.z + v2.z + v3.z) / 3;

            const g = new THREE.Geometry();
            g.vertices.push(v1, v2, v3);
            g.faces.push(new THREE.Face3(0, 1, 2));
            g.computeFaceNormals();
            const m = new THREE.Mesh(
              g,
              new THREE.MeshBasicMaterial({ color: 0xff0000 })
            );
            mesh.add(m);
          }
        });
        break;

      case CANNON.Shape.types.TRIMESH:
        geometry = new THREE.Geometry();
        v0 = this.tmpVec0;
        v1 = this.tmpVec1;
        v2 = this.tmpVec2;
        for (let i = 0; i < (shape as CANNON.Trimesh).indices.length / 3; i++) {
          (shape as CANNON.Trimesh).getTriangleVertices(i, v0, v1, v2);
          geometry.vertices.push(
            new THREE.Vector3(v0.x, v0.y, v0.z),
            new THREE.Vector3(v1.x, v1.y, v1.z),
            new THREE.Vector3(v2.x, v2.y, v2.z)
          );
          let j = geometry.vertices.length - 3;
          geometry.faces.push(new THREE.Face3(j, j + 1, j + 2));
        }
        geometry.computeBoundingSphere();
        geometry.computeFaceNormals();
        mesh = new THREE.Mesh(geometry, material);
        shape.geometryId = geometry.id;
        break;

      case CANNON.Shape.types.HEIGHTFIELD:
        geometry = new THREE.Geometry();

        v0 = this.tmpVec0;
        v1 = this.tmpVec1;
        v2 = this.tmpVec2;
        for (
          let xi = 0;
          xi < (shape as CANNON.Heightfield).data.length - 1;
          xi++
        ) {
          for (
            let yi = 0;
            yi < (shape as CANNON.Heightfield).data[xi].length - 1;
            yi++
          ) {
            for (let k = 0; k < 2; k++) {
              (shape as CANNON.Heightfield).getConvexTrianglePillar(
                xi,
                yi,
                k === 0
              );
              v0.copy((shape as CANNON.Heightfield).pillarConvex.vertices[0]);
              v1.copy((shape as CANNON.Heightfield).pillarConvex.vertices[1]);
              v2.copy((shape as CANNON.Heightfield).pillarConvex.vertices[2]);
              v0.vadd((shape as CANNON.Heightfield).pillarOffset, v0);
              v1.vadd((shape as CANNON.Heightfield).pillarOffset, v1);
              v2.vadd((shape as CANNON.Heightfield).pillarOffset, v2);
              geometry.vertices.push(
                new THREE.Vector3(v0.x, v0.y, v0.z),
                new THREE.Vector3(v1.x, v1.y, v1.z),
                new THREE.Vector3(v2.x, v2.y, v2.z)
              );
              const i = geometry.vertices.length - 3;
              geometry.faces.push(new THREE.Face3(i, i + 1, i + 2));
            }
          }
        }
        geometry.computeBoundingSphere();
        geometry.computeFaceNormals();
        mesh = new THREE.Mesh(geometry, material);
        shape.geometryId = geometry.id;
        break;
    }

    if (mesh) {
      this.scene.add(mesh);
    }

    return mesh;
  }

  private _scaleMesh(mesh: THREE.Mesh | THREE.Points, shape: CANNON.Shape) {
    switch (shape.type) {
      case CANNON.Shape.types.SPHERE:
        const radius = (shape as CANNON.Sphere).radius;
        mesh.scale.set(radius, radius, radius);
        break;

      case CANNON.Shape.types.BOX:
        const halfExtents: CANNON.Vec3 = (shape as CANNON.Box).halfExtents;
        mesh.scale.copy(
          new THREE.Vector3(halfExtents.x, halfExtents.y, halfExtents.z)
        );
        mesh.scale.multiplyScalar(2);
        break;

      case CANNON.Shape.types.CONVEXPOLYHEDRON:
        mesh.scale.set(1, 1, 1);
        break;

      case CANNON.Shape.types.TRIMESH:
        const scale: CANNON.Vec3 = (shape as CANNON.Trimesh).scale;
        mesh.scale.copy(new THREE.Vector3(scale.x, scale.y, scale.z));
        break;

      case CANNON.Shape.types.HEIGHTFIELD:
        mesh.scale.set(1, 1, 1);
        break;
    }
  }
}

Final Script

./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
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
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import Stats from '/jsm/libs/stats.module'
import { GUI } from '/jsm/libs/dat.gui.module'
import '/cannon/cannon.min'
import CannonDebugRenderer from './utils/cannonDebugRenderer.js'
import { OBJLoader } from '/jsm/loaders/OBJLoader'

const scene: THREE.Scene = new THREE.Scene()
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)

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)

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(renderer.domElement)

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

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)
//world.broadphase = new CANNON.NaiveBroadphase() //
//world.solver.iterations = 10
//world.allowSleep = true

const normalMaterial: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial()
const phongMaterial: THREE.MeshPhongMaterial = new THREE.MeshPhongMaterial()

const cubeGeometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1)
const cubeMesh: THREE.Mesh = new THREE.Mesh(cubeGeometry, normalMaterial)
cubeMesh.position.x = -4
cubeMesh.position.y = 3
cubeMesh.castShadow = true
scene.add(cubeMesh)
const cubeShape = new CANNON.Box(new CANNON.Vec3(.5, .5, .5))
const cubeBody = new CANNON.Body({ mass: 1 });
cubeBody.addShape(cubeShape)
cubeBody.position.x = cubeMesh.position.x
cubeBody.position.y = cubeMesh.position.y
cubeBody.position.z = cubeMesh.position.z
world.addBody(cubeBody)

const sphereGeometry: THREE.SphereGeometry = new THREE.SphereGeometry()
const sphereMesh: THREE.Mesh = new THREE.Mesh(sphereGeometry, normalMaterial)
sphereMesh.position.x = -2
sphereMesh.position.y = 3
sphereMesh.castShadow = true
scene.add(sphereMesh)
const sphereShape = new CANNON.Sphere(1)
const sphereBody = new CANNON.Body({ mass: 1 });
sphereBody.addShape(sphereShape)
sphereBody.position.x = sphereMesh.position.x
sphereBody.position.y = sphereMesh.position.y
sphereBody.position.z = sphereMesh.position.z
world.addBody(sphereBody)

const cylinderGeometry: THREE.CylinderGeometry = new THREE.CylinderGeometry(1, 1, 2, 8)
const cylinderMesh: THREE.Mesh = new THREE.Mesh(cylinderGeometry, normalMaterial)
cylinderMesh.position.x = 0
cylinderMesh.position.y = 3
cylinderMesh.castShadow = true
scene.add(cylinderMesh)
const cylinderShape = new CANNON.Cylinder(1, 1, 2, 8)
const cylinderBody = new CANNON.Body({ mass: 1 });
const cylinderQuaternion = new CANNON.Quaternion()
cylinderQuaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Math.PI / 2)
cylinderBody.addShape(cylinderShape, new CANNON.Vec3, cylinderQuaternion)
cylinderBody.position.x = cylinderMesh.position.x
cylinderBody.position.y = cylinderMesh.position.y
cylinderBody.position.z = cylinderMesh.position.z
world.addBody(cylinderBody)

const icosahedronGeometry: THREE.IcosahedronGeometry = new THREE.IcosahedronGeometry(1, 0)
const icosahedronMesh: THREE.Mesh = new THREE.Mesh(icosahedronGeometry, normalMaterial)
icosahedronMesh.position.x = 2
icosahedronMesh.position.y = 3
icosahedronMesh.castShadow = true
scene.add(icosahedronMesh)
const icosahedronShape = CreateConvexPolyhedron(icosahedronMesh.geometry)
const icosahedronBody = new CANNON.Body({ mass: 1 });
icosahedronBody.addShape(icosahedronShape)
icosahedronBody.position.x = icosahedronMesh.position.x
icosahedronBody.position.y = icosahedronMesh.position.y
icosahedronBody.position.z = icosahedronMesh.position.z
world.addBody(icosahedronBody)

const torusKnotGeometry: THREE.TorusKnotGeometry = new THREE.TorusKnotGeometry()
const torusKnotMesh: THREE.Mesh = new THREE.Mesh(torusKnotGeometry, normalMaterial)
torusKnotMesh.position.x = 4
torusKnotMesh.position.y = 3
torusKnotMesh.castShadow = true
scene.add(torusKnotMesh)
const torusKnotShape = CreateTrimesh(<THREE.Geometry>torusKnotMesh.geometry)
const torusKnotBody = new CANNON.Body({ mass: 1 });
torusKnotBody.addShape(torusKnotShape)
torusKnotBody.position.x = torusKnotMesh.position.x
torusKnotBody.position.y = torusKnotMesh.position.y
torusKnotBody.position.z = torusKnotMesh.position.z
world.addBody(torusKnotBody)

let monkeyMesh: THREE.Object3D
let monkeyBody: CANNON.Body
let monkeyLoaded: Boolean = false
const objLoader: OBJLoader = new OBJLoader();
objLoader.load(
    'models/monkey.obj',
    (object) => {
        scene.add(object)
        monkeyMesh = object.children[0];
        (monkeyMesh as THREE.Mesh).material = normalMaterial
        monkeyMesh.position.x = 0
        monkeyMesh.position.y = 20
        //const monkeyShape = CreateTrimesh((monkeyMesh as THREE.Mesh).geometry)
        monkeyBody = new CANNON.Body({ mass: 1 });
        //monkeyBody.addShape(monkeyShape)
        //monkeyBody.addShape(cubeShape)
        // monkeyBody.addShape(sphereShape)
        // monkeyBody.addShape(cylinderShape)
        monkeyBody.addShape(icosahedronShape)
        // monkeyBody.addShape(new CANNON.Plane())
        // monkeyBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Math.PI / 2)
        monkeyBody.position.x = monkeyMesh.position.x
        monkeyBody.position.y = monkeyMesh.position.y
        monkeyBody.position.z = monkeyMesh.position.z
        world.addBody(monkeyBody)
        monkeyLoaded = true
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    },
    (error) => {
        console.log('An error happened');
    }
);

const planeGeometry: THREE.PlaneGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh: THREE.Mesh = new THREE.Mesh(planeGeometry, phongMaterial)
planeMesh.rotateX(-Math.PI / 2)
planeMesh.receiveShadow = true;
scene.add(planeMesh)
const planeShape = new CANNON.Plane()
const planeBody = new CANNON.Body({ mass: 0 })
planeBody.addShape(planeShape)
planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
world.addBody(planeBody)

function CreateTrimesh(geometry: THREE.Geometry | THREE.BufferGeometry): CANNON.Trimesh {
    if (!(geometry as THREE.BufferGeometry).attributes) {
        geometry = new THREE.BufferGeometry().fromGeometry(geometry as THREE.Geometry);
    }
    const vertices: number[] = <number[]>(geometry as THREE.BufferGeometry).attributes.position.array
    const indices: number[] = Object.keys(vertices).map(Number);
    return new CANNON.Trimesh(vertices, indices);
}

function CreateConvexPolyhedron(geometry: THREE.Geometry | THREE.BufferGeometry): CANNON.ConvexPolyhedron {
    if (!(geometry as THREE.Geometry).vertices) {
        geometry = new THREE.Geometry().fromBufferGeometry(geometry as THREE.BufferGeometry);
    }
    const points: CANNON.Vec3[] = (<THREE.Geometry>geometry).vertices.map(function (v) {
        return new CANNON.Vec3(v.x, v.y, v.z)
    })
    const faces: number[][] = (<THREE.Geometry>geometry).faces.map(function (f) {
        return [f.a, f.b, f.c]
    })
    return new CANNON.ConvexPolyhedron(points, faces);
}

camera.position.y = 4
camera.position.z = 4
controls.target.y = 2

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)

const gui = new GUI()
const physicsFolder = gui.addFolder("Physics")
physicsFolder.add(world.gravity, "x", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "y", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "z", -10.0, 10.0, 0.1)
physicsFolder.open()

const clock: THREE.Clock = new THREE.Clock()

const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    let delta = clock.getDelta()
    if (delta > .1) delta = .1
    world.step(delta)
    cannonDebugRenderer.update()

    // Copy coordinates from Cannon.js to Three.js
    cubeMesh.position.set(cubeBody.position.x, cubeBody.position.y, cubeBody.position.z);
    cubeMesh.quaternion.set(cubeBody.quaternion.x, cubeBody.quaternion.y, cubeBody.quaternion.z, cubeBody.quaternion.w);
    sphereMesh.position.set(sphereBody.position.x, sphereBody.position.y, sphereBody.position.z);
    sphereMesh.quaternion.set(sphereBody.quaternion.x, sphereBody.quaternion.y, sphereBody.quaternion.z, sphereBody.quaternion.w);
    cylinderMesh.position.set(cylinderBody.position.x, cylinderBody.position.y, cylinderBody.position.z);
    cylinderMesh.quaternion.set(cylinderBody.quaternion.x, cylinderBody.quaternion.y, cylinderBody.quaternion.z, cylinderBody.quaternion.w);
    icosahedronMesh.position.set(icosahedronBody.position.x, icosahedronBody.position.y, icosahedronBody.position.z);
    icosahedronMesh.quaternion.set(icosahedronBody.quaternion.x, icosahedronBody.quaternion.y, icosahedronBody.quaternion.z, icosahedronBody.quaternion.w);
    torusKnotMesh.position.set(torusKnotBody.position.x, torusKnotBody.position.y, torusKnotBody.position.z);
    torusKnotMesh.quaternion.set(torusKnotBody.quaternion.x, torusKnotBody.quaternion.y, torusKnotBody.quaternion.z, torusKnotBody.quaternion.w);
    if (monkeyLoaded) {
        monkeyMesh.position.set(monkeyBody.position.x, monkeyBody.position.y, monkeyBody.position.z);
        monkeyMesh.quaternion.set(monkeyBody.quaternion.x, monkeyBody.quaternion.y, monkeyBody.quaternion.z, monkeyBody.quaternion.w);
    }

    render()

    stats.update()
};

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

Supported Cannon.js Shape Collisions

TypeScript Module Resolution