ConvexObjectBreaker

Description

In this example, I use the ConvexObjectBreaker class from the Threejs misc folder to shatter some existing meshes. I shoot a ball at a mesh, and if a collision occurred, I pass the Mesh, collision coordinates and normal into the ConvexObjectBreaker prepareBreakableObject and subdivideByImpact methods. This will shard the mesh into many smaller meshes. I can remove the original mesh and add the new smaller meshes to the scene.

In this example, I also use it in conjunction with Cannonjs. Each mesh shard also has new ConvexPolyhedron calculated from the new mesh and added to the physics world.

Note that ConvexPolyhedrons are cpu intensive to calculate physics properties for, so this works best when the meshes are simple primitives with few vertices.

In more detail, with each ball I shoot, I register a collide event listener. When a collision occurs it will pass in a CANNON.ICollisionEvent. The information I require for this about the body that was collided with, and its contact properties.

With the CANNON.Body, I retrieve some custom user data which I can use to link this body with a mesh and how many times this mesh has been split into shards. With the CANNON.ICollisionEvent, I sum bj.position and rj and then convert it to a local mesh position which then gives the collision location from the perspective of the object that was hit.

1
const poi = bodies[contactId].pointToLocalFrame((contact.bj.position as CANNON.Vec3).vadd(contact.rj))

CANNON.ICollisionEvent

Property Description
contact.bi is the first participating body
contact.bj is the second participating body
contact.ri is the world-oriented vector that goes from .bi position to contact point
contact.rj is the world-oriented vector that goes from .bj position to contact point
contact.ni is the world-oriented contact normal, pointing out of .bi

With the collision location and normal now calculated, I can then pass this into the ConvexObjectBreaker.subdivideByImpact method. Note that when you hit the object at the top, or the bottom, the sharding is relative to the position striked, while the shards still appear random. This method returns an array of new Meshes that I can use to add to the scene, and calculate physics bodies for.

When creating a Mesh that can be subdivided, first pass it into the ConvexObjectBreaker.prepareBreakableObject method. Then it can subdivided using the ConvexObjectBreaker.subdivideByImpact. Note that new meshes that are created from a sub division don't need to be re passed into the ConvexObjectBreaker.prepareBreakableObject method.

Start Code

./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
33
34
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/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js')))
        app.use('/cannon/cannon.min', express.static(path.join(__dirname, '../../node_modules/cannon/build/cannon.min.js')))
        app.use('/jsm/controls/PointerLockControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/PointerLockControls.js')))
        app.use('/jsm/misc/ConvexObjectBreaker', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/misc/ConvexObjectBreaker.js')))
        app.use('/jsm/objects/Reflector', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/objects/Reflector.js')))

        app.use('/jsm/', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/')))

        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
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
import * as THREE from '/build/three.module.js'
import { PointerLockControls } from '/jsm/controls/PointerLockControls'
import Stats from '/jsm/libs/stats.module'
import '/cannon/cannon.min'
import CannonUtils from './utils/cannonUtils.js'
import { ConvexObjectBreaker } from '/jsm/misc/ConvexObjectBreaker';
import { Reflector } from '/jsm/objects/Reflector'

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

const envTexture = new THREE.CubeTextureLoader().load(["img/px.png", "img/nx.png", "img/py.png", "img/ny.png", "img/pz.png", "img/nz.png"])
envTexture.mapping = THREE.CubeReflectionMapping
scene.environment = envTexture

var walls = [
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/px.png'),
        side: THREE.BackSide
    }),
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/nx.png'),
        side: THREE.BackSide
    }),
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/py.png'),
        side: THREE.BackSide
    }),
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/ny.png'),
        side: THREE.BackSide
    }),
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/pz.png'),
        side: THREE.BackSide
    }),
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('img/nz.png'),
        side: THREE.BackSide
    })
];
const room = new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200, 1, 1, 1), walls);
scene.add(room);

var light1 = new THREE.DirectionalLight();
light1.position.set(20, 20, 20)
light1.intensity = 2
scene.add(light1);

var light2 = new THREE.DirectionalLight();
light2.position.set(-20, 20, 20)
light1.intensity = 1
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({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const menuPanel = document.getElementById('menuPanel') as HTMLDivElement;
const startButton = document.getElementById('startButton') as HTMLButtonElement;
startButton.addEventListener('click', function () {
    controls.lock();
}, false);

const controls = new PointerLockControls(camera, renderer.domElement)
controls.addEventListener('lock', () => menuPanel.style.display = 'none');
controls.addEventListener('unlock', () => menuPanel.style.display = 'block');

camera.position.y = 1
camera.position.z = 2

const onKeyDown = function (event: KeyboardEvent) {
    switch (event.keyCode) {
        case 87: // w
            controls.moveForward(.25)
            break;
        case 65: // a
            controls.moveRight(-.25)
            break;
        case 83: // s
            controls.moveForward(-.25)
            break;
        case 68: // d
            controls.moveRight(.25)
            break;
    }
};
document.addEventListener('keydown', onKeyDown, false);

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)

const material: THREE.MeshPhysicalMaterial = new THREE.MeshPhysicalMaterial({
    clearcoat: 1.0,
    clearcoatRoughness: 0,
    clearcoatMap: null,
    clearcoatRoughnessMap: null,
    metalness: 0.5,
    roughness: 0.0,
    color: 'white',
    transmission: 0.4,
    opacity: 1,
    transparent: true,
    side: THREE.DoubleSide,
})

const meshes: { [id: string]: THREE.Mesh } = {}
const bodies: { [id: string]: CANNON.Body } = {}
let meshId = 0;

const groundMirror = new Reflector(new THREE.PlaneBufferGeometry(500, 500), {
    color: new THREE.Color(0x222222),
    clipBias: 0.003,
    textureWidth: window.innerWidth * window.devicePixelRatio,
    textureHeight: window.innerHeight * window.devicePixelRatio
});
groundMirror.position.y = -.05
groundMirror.rotateX(- Math.PI / 2);
scene.add(groundMirror);

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)

const convexObjectBreaker = new ConvexObjectBreaker();

for (let i = 0; i < 20; i++) {
    const size = { x: (Math.random() * 4) + 2, y: (Math.random() * 10) + 5, z: (Math.random() * 4) + 2 }
    const geo: THREE.BoxBufferGeometry = new THREE.BoxBufferGeometry(size.x, size.y, size.z)
    const cube = new THREE.Mesh(geo, material)

    cube.position.x = (Math.random() * 50) - 25
    cube.position.y = (size.y / 2) + .1
    cube.position.z = (Math.random() * 50) - 25

    scene.add(cube)
    meshes[meshId] = cube
    convexObjectBreaker.prepareBreakableObject(meshes[meshId], 1, new THREE.Vector3(), new THREE.Vector3(), true)

    const cubeShape = new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2));
    const cubeBody = new CANNON.Body({ mass: 1 });
    (cubeBody as any).userData = { splitCount: 0, id: meshId }
    cubeBody.addShape(cubeShape);
    cubeBody.position.x = cube.position.x
    cubeBody.position.y = cube.position.y
    cubeBody.position.z = cube.position.z

    world.addBody(cubeBody);
    bodies[meshId] = cubeBody

    meshId++
}

const bullets: { [id: string]: THREE.Mesh } = {}
const bulletBodies: { [id: string]: CANNON.Body } = {}
let bulletId = 0

const bulletMaterial = new THREE.MeshPhysicalMaterial({
    map: new THREE.TextureLoader().load("img/marble.png"),
    clearcoat: 1.0,
    clearcoatRoughness: 0,
    clearcoatMap: null,
    clearcoatRoughnessMap: null,
    metalness: 0.4,
    roughness: 0.3,
    color: 'white',
})
document.addEventListener('click', onClick, false);
function onClick(e: Event) {
    if (controls.isLocked) {
        const bullet = new THREE.Mesh(new THREE.SphereGeometry(1, 16, 16), bulletMaterial)
        bullet.position.copy(camera.position)
        scene.add(bullet)
        bullets[bulletId] = bullet

        const bulletShape = new CANNON.Sphere(1);
        const bulletBody = new CANNON.Body({ mass: 1 });
        bulletBody.addShape(bulletShape);
        bulletBody.position.x = camera.position.x;
        bulletBody.position.y = camera.position.y;
        bulletBody.position.z = camera.position.z;

        world.addBody(bulletBody);
        bulletBodies[bulletId] = bulletBody

        bulletBody.addEventListener("collide", (e: CANNON.ICollisionEvent) => {
            if ((e.body as any).userData) {
                if ((e.body as any).userData.splitCount < 2) {
                    splitObject((e.body as any).userData, e.contact)
                }
            }
        })
        const v = new THREE.Vector3(0, 0, -1);
        v.applyQuaternion(camera.quaternion);
        v.multiplyScalar(50)
        bulletBody.velocity.set(v.x, v.y, v.z)
        bulletBody.angularVelocity.set((Math.random() * 10) + 1, (Math.random() * 10) + 1, (Math.random() * 10) + 1)

        bulletId++

        //remove old bullets
        while (Object.keys(bullets).length > 5) {
            scene.remove(bullets[bulletId - 6])
            delete bullets[bulletId - 6]
            world.remove(bulletBodies[bulletId - 6])
            delete bulletBodies[bulletId - 6]
        }
    }
};

function splitObject(userData: any, contact: CANNON.ContactEquation) {
    const contactId = userData.id
    if (meshes[contactId]) {
        const poi = bodies[contactId].pointToLocalFrame((contact.bj.position as CANNON.Vec3).vadd(contact.rj))
        const n = new THREE.Vector3(contact.ni.x, contact.ni.y, contact.ni.z).negate()
        const shards = convexObjectBreaker.subdivideByImpact(meshes[contactId], new THREE.Vector3(poi.x, poi.y, poi.z), n, 1, 0);

        //let pos: THREE.Vector3 = new THREE.Vector3().copy(meshes[contactId].position)
        //let quat: THREE.Quaternion = new THREE.Quaternion().copy(meshes[contactId].quaternion)

        scene.remove(meshes[contactId])
        delete meshes[contactId]
        world.remove(bodies[contactId])
        delete bodies[contactId]

        shards.forEach((d: THREE.Mesh) => {
            const nextId = meshId++

            //d.position.copy(pos)
            //d.quaternion.copy(quat)

            scene.add(d)
            meshes[nextId] = d

            d.geometry.scale(.99, .99, .99)
            const shape = CannonUtils.CreateConvexPolyhedron(d.geometry)

            const body = new CANNON.Body({ mass: 1 });
            body.addShape(shape);
            (body as any).userData = { splitCount: userData.splitCount + 1, id: nextId }
            body.position.x = d.position.x
            body.position.y = d.position.y
            body.position.z = d.position.z
            body.quaternion.x = d.quaternion.x
            body.quaternion.y = d.quaternion.y
            body.quaternion.z = d.quaternion.z
            body.quaternion.w = d.quaternion.w
            world.addBody(body)
            bodies[nextId] = body

        })
    }
}

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

var animate = function () {
    requestAnimationFrame(animate)

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

    Object.keys(meshes).forEach((m) => {
        meshes[m].position.set(bodies[m].position.x, bodies[m].position.y, bodies[m].position.z);
        meshes[m].quaternion.set(bodies[m].quaternion.x, bodies[m].quaternion.y, bodies[m].quaternion.z, bodies[m].quaternion.w);
    })

    Object.keys(bullets).forEach((b) => {
        bullets[b].position.set(bulletBodies[b].position.x, bulletBodies[b].position.y, bulletBodies[b].position.z);
        bullets[b].quaternion.set(bulletBodies[b].quaternion.x, bulletBodies[b].quaternion.y, bulletBodies[b].quaternion.z, bulletBodies[b].quaternion.w);
    })

    render()

    stats.update()
};

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