Skip to content

ConvexPolyhedrons and Compound Shapes

Video Lecture

ConvexPolyhedrons and Compound Shapes ConvexPolyhedrons and Compound Shapes ConvexPolyhedrons and Compound Shapes

Description

In this video I will demonstrate several different methods of creating collision boundaries, also sometimes called collision meshes, using various ConvexPolyhedrons and Compound Shapes. I will also compare the performance and differences between them.

When positioning the parts of a compound shape, you can use a 3d graphics tool to help estimate the positioning. It is is important to know though, that if you use Blender, then be aware that Blender, by default, uses a different coordinate system. In Blender, Z is UP, and the Y axis is used for Near/Far and it is also negative compared to Threejs. So you will need to swap around the coordinates for Y and Z and negate the new Z.

To position an object from the perspective of a default Threejs camera looking down the Z axis, with UP axis [0,1,0], see table for conversion.

Axis Threejs Blender
Up/Down Y / -Y Z / -Z
Left/Right -X / X -X / X
Near/Far Z / -Z -Y / Y

Eg, If the 3D coordinates in Blender are [1,2,3], then in Threejs, the equivalent is [1,3,-2]

Start Scripts

./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
// If using Relative Import References
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 CannonUtils from './utils/cannonUtils.js'
import { OBJLoader } from '/jsm/loaders/OBJLoader'

// If using Module Specifiers
// import * as THREE from 'three'
// import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
// import Stats from 'three/examples/jsm/libs/stats.module'
// import {GUI} from 'three/examples/jsm/libs/dat.gui.module'
// import * as CANNON from 'cannon'
// import CannonDebugRenderer from './utils/cannonDebugRenderer'
// import CannonUtils from './utils/cannonUtils'
// import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'

const 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 = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)

const renderer = 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 = new THREE.MeshNormalMaterial()
const phongMaterial = new THREE.MeshPhongMaterial()

let monkeyMeshes: THREE.Object3D[] = new Array()
let monkeyBodies: CANNON.Body[] = new Array()
let monkeyLoaded: Boolean = false

const objLoader: OBJLoader = new OBJLoader()
objLoader.load(
    'models/monkey.obj',
    //'models/monkeyPhysics.obj',
    (object) => {
        //scene.add(object)

        const monkeyMesh = object.children[0]
        ;(monkeyMesh as THREE.Mesh).material = normalMaterial

        // let monkeyMesh: THREE.Object3D
        // let monkeyCollisionMesh: THREE.Object3D
        // object.traverse(function (child) {
        //     console.log(child.name)
        //     if (child.name === "Suzanne") {
        //         monkeyMesh = child;
        //         (monkeyMesh as THREE.Mesh).material = normalMaterial
        //     } else if (child.name.startsWith("physics")) {
        //         monkeyCollisionMesh = child;
        //     }
        // })

        for (let i = 0; i < 10; i++) {
            const monkeyMeshClone = monkeyMesh.clone()
            monkeyMeshClone.position.x = Math.floor(Math.random() * 10) - 5
            monkeyMeshClone.position.z = Math.floor(Math.random() * 10) - 5
            monkeyMeshClone.position.y = 5 + i
            scene.add(monkeyMeshClone)
            monkeyMeshes.push(monkeyMeshClone)

            const monkeyShape = CannonUtils.CreateTrimesh(
                (monkeyMesh as THREE.Mesh).geometry
            )
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron(new THREE.IcosahedronGeometry(1))
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron((monkeyMesh as THREE.Mesh).geometry)
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron((monkeyCollisionMesh as THREE.Mesh).geometry)
            const monkeyBody = new CANNON.Body({ mass: 1 })
            monkeyBody.addShape(monkeyShape)
            // monkeyBody.addShape(new CANNON.Sphere(.8), new CANNON.Vec3(0, .2, 0))// head,
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(0, -.97, 0.46))// chin,
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(-1.36, .29, -0.5)) //left ear
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(1.36, .29, -0.5)) //right ear
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(0, .56, -0.85)) //head top
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(0, .98, -0.07)) //forehead top
            monkeyBody.position.x = monkeyMeshClone.position.x
            monkeyBody.position.y = monkeyMeshClone.position.y
            monkeyBody.position.z = monkeyMeshClone.position.z
            world.addBody(monkeyBody)
            monkeyBodies.push(monkeyBody)
        }

        monkeyLoaded = true
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log('An error happened')
    }
)

const planeGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh = 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)

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 = new THREE.Clock()

const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

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

    // Copy coordinates from Cannon.js to Three.js
    if (monkeyLoaded) {
        monkeyMeshes.forEach((m, i) => {
            m.position.set(
                monkeyBodies[i].position.x,
                monkeyBodies[i].position.y,
                monkeyBodies[i].position.z
            )
            m.quaternion.set(
                monkeyBodies[i].quaternion.x,
                monkeyBodies[i].quaternion.y,
                monkeyBodies[i].quaternion.z,
                monkeyBodies[i].quaternion.w
            )
        })
    }

    render()

    stats.update()
}

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

./src/client/utils/cannonUtils.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
//MIT License
//Copyright (c) 2020-2021 Sean Bradley
import * as THREE from 'three'
import * as CANNON from 'cannon'

interface Face3 {
    a: number
    b: number
    c: number
    normals: THREE.Vector3[]
}

class CannonUtils {
    public static CreateTrimesh(
        geometry: THREE.BufferGeometry
    ): CANNON.Trimesh {
        const vertices: number[] = <number[]>geometry.attributes.position.array
        const indices: number[] = Object.keys(vertices).map(Number)
        return new CANNON.Trimesh(vertices, indices)
    }

    public static CreateConvexPolyhedron(
        geometry: THREE.BufferGeometry
    ): CANNON.ConvexPolyhedron {
        const position = geometry.attributes.position
        const normal = geometry.attributes.normal
        const vertices: THREE.Vector3[] = []
        for (let i = 0; i < position.count; i++) {
            vertices.push(new THREE.Vector3().fromBufferAttribute(position, i))
        }
        const faces: Face3[] = []
        for (let i = 0; i < position.count; i += 3) {
            const vertexNormals =
                normal === undefined
                    ? []
                    : [
                          new THREE.Vector3().fromBufferAttribute(normal, i),
                          new THREE.Vector3().fromBufferAttribute(
                              normal,
                              i + 1
                          ),
                          new THREE.Vector3().fromBufferAttribute(normal, i + 2)
                      ]
            const face: Face3 = {
                a: i,
                b: i + 1,
                c: i + 2,
                normals: vertexNormals
            }
            faces.push(face)
        }

        const verticesMap: { [key: string]: number } = {}
        const points: CANNON.Vec3[] = []
        const changes: number[] = []
        for (let i = 0, il = vertices.length; i < il; i++) {
            const v = vertices[i]
            const key =
                Math.round(v.x * 100) +
                '_' +
                Math.round(v.y * 100) +
                '_' +
                Math.round(v.z * 100)
            if (verticesMap[key] === undefined) {
                verticesMap[key] = i
                points.push(
                    new CANNON.Vec3(vertices[i].x, vertices[i].y, vertices[i].z)
                )
                changes[i] = points.length - 1
            } else {
                changes[i] = changes[verticesMap[key]]
            }
        }

        const faceIdsToRemove = []
        for (let i = 0, il = faces.length; i < il; i++) {
            const face = faces[i]
            face.a = changes[face.a]
            face.b = changes[face.b]
            face.c = changes[face.c]
            const indices = [face.a, face.b, face.c]
            for (let n = 0; n < 3; n++) {
                if (indices[n] === indices[(n + 1) % 3]) {
                    faceIdsToRemove.push(i)
                    break
                }
            }
        }

        for (let i = faceIdsToRemove.length - 1; i >= 0; i--) {
            const idx = faceIdsToRemove[i]
            faces.splice(idx, 1)
        }

        const cannonFaces: number[][] = faces.map(function (f) {
            return [f.a, f.b, f.c]
        })

        return new CANNON.ConvexPolyhedron(points, cannonFaces)
    }

    public static offsetCenterOfMass(
        body: CANNON.Body,
        centreOfMass: CANNON.Vec3
    ): void {
        body.shapeOffsets.forEach(function (offset) {
            centreOfMass.vadd(offset, centreOfMass)
        })
        centreOfMass.scale(1 / body.shapes.length, centreOfMass)
        body.shapeOffsets.forEach(function (offset) {
            offset.vsub(centreOfMass, offset)
        })
        const worldCenterOfMass = new CANNON.Vec3()
        body.vectorToWorldFrame(centreOfMass, worldCenterOfMass)
        body.position.vadd(worldCenterOfMass, body.position)
    }
}

export default CannonUtils

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

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

const 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)

const 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 = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
camera.position.set(0, 3, 6)

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

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.target.y = 0.5

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 = new THREE.MeshNormalMaterial()
const phongMaterial = new THREE.MeshPhongMaterial()

const monkeyMeshes: THREE.Object3D[] = []
const monkeyBodies: CANNON.Body[] = []
let monkeyLoaded = false

const objLoader: OBJLoader = new OBJLoader()
objLoader.load(
    'models/monkey.obj',
    //'models/monkeyPhysics.obj',
    (object) => {
        //scene.add(object)

        const monkeyMesh = object.children[0]
        ;(monkeyMesh as THREE.Mesh).material = normalMaterial
        ;(<THREE.MeshNormalMaterial>(
            (<THREE.Mesh>monkeyMesh).material
        )).flatShading = true

        // let monkeyMesh: THREE.Object3D
        // let monkeyCollisionMesh: THREE.Object3D
        // object.traverse(function (child) {
        //     console.log(child.name)
        //     if (child.name === "Suzanne") {
        //         monkeyMesh = child;
        //         (monkeyMesh as THREE.Mesh).material = normalMaterial
        //     } else if (child.name.startsWith("physics")) {
        //         monkeyCollisionMesh = child;
        //     }
        // })

        for (let i = 0; i < 200; i++) {
            const monkeyMeshClone = monkeyMesh.clone()
            monkeyMeshClone.position.x = Math.floor(Math.random() * 10) - 5
            monkeyMeshClone.position.z = Math.floor(Math.random() * 10) - 5
            monkeyMeshClone.position.y = 5 + i
            scene.add(monkeyMeshClone)
            monkeyMeshes.push(monkeyMeshClone)

            //const monkeyShape = CannonUtils.CreateTrimesh((monkeyMesh as THREE.Mesh).geometry)
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron(new THREE.IcosahedronGeometry(1))
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron((monkeyMesh as THREE.Mesh).geometry)
            //const monkeyShape = CannonUtils.CreateConvexPolyhedron((monkeyCollisionMesh as THREE.Mesh).geometry)
            const monkeyBody = new CANNON.Body({ mass: 1 })
            //monkeyBody.addShape(monkeyShape)
            monkeyBody.addShape(
                new CANNON.Sphere(0.8),
                new CANNON.Vec3(0, 0.2, 0)
            ) // head,
            monkeyBody.addShape(
                new CANNON.Sphere(0.05),
                new CANNON.Vec3(0, -0.97, 0.46)
            ) // chin,
            monkeyBody.addShape(
                new CANNON.Sphere(0.05),
                new CANNON.Vec3(-1.36, 0.29, -0.5)
            ) //left ear
            monkeyBody.addShape(
                new CANNON.Sphere(0.05),
                new CANNON.Vec3(1.36, 0.29, -0.5)
            ) //right ear
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(0, .56, -0.85)) //head top
            // monkeyBody.addShape(new CANNON.Sphere(.05), new CANNON.Vec3(0, .98, -0.07)) //forehead top
            monkeyBody.addShape(
                new CANNON.Sphere(0.05),
                new CANNON.Vec3(-0.32, 0.75, 0.73)
            ) //left eyebrow top
            monkeyBody.position.x = monkeyMeshClone.position.x
            monkeyBody.position.y = monkeyMeshClone.position.y
            monkeyBody.position.z = monkeyMeshClone.position.z
            world.addBody(monkeyBody)
            monkeyBodies.push(monkeyBody)
        }

        monkeyLoaded = true
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log('An error happened')
    }
)

const planeGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh = 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)

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 = new THREE.Clock()
let delta

const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

function animate() {
    requestAnimationFrame(animate)

    controls.update()

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

    // Copy coordinates from Cannon.js to Three.js
    if (monkeyLoaded) {
        monkeyMeshes.forEach((m, i) => {
            m.position.set(
                monkeyBodies[i].position.x,
                monkeyBodies[i].position.y,
                monkeyBodies[i].position.z
            )
            m.quaternion.set(
                monkeyBodies[i].quaternion.x,
                monkeyBodies[i].quaternion.y,
                monkeyBodies[i].quaternion.z,
                monkeyBodies[i].quaternion.w
            )
        })
    }

    render()

    stats.update()
}

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

animate()