Skip to content

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 ConvexObjectBreakers 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 Cannon. 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.

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 Scripts

./dist/client/index.html

 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
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>
            Three.js TypeScript Tutorials by Sean Bradley :
            https://sbcode.net/threejs
        </title>
        <style>
            body {
                overflow: hidden;
                margin: 0px;
            }

            #menuPanel {
                position: absolute;
                background-color: rgba(255, 255, 255, 0.5);
                top: 0px;
                left: 0px;
                width: 100%;
                height: 100%;
            }

            #startButton {
                height: 50px;
                width: 200px;
                margin: -25px -100px;
                position: relative;
                top: 50%;
                left: 50%;
                font-size: 32px;
            }
        </style>
    </head>

    <body>
        <div id="menuPanel">
            <button id="startButton">Click to Start</button>
        </div>
        <script type="module" src="bundle.js"></script>
    </body>
</html>

./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
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
import * as THREE from 'three'
import { PointerLockControls } from 'three/examples/jsm/controls/PointerLockControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import * as CANNON from 'cannon-es'
import CannonUtils from './utils/cannonUtils'
import { ConvexGeometry } from 'three/examples/jsm/geometries/ConvexGeometry'
import { ConvexObjectBreaker } from 'three/examples/jsm/misc/ConvexObjectBreaker'
import { Reflector } from 'three/examples/jsm/objects/Reflector'

const scene = new THREE.Scene()

const light1 = new THREE.DirectionalLight()
light1.position.set(20, 20, 20)
scene.add(light1)

const light2 = new THREE.DirectionalLight()
light2.position.set(-20, 20, 20)
scene.add(light2)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)

const renderer = 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.key) {
        case 'w':
            controls.moveForward(0.25)
            break
        case 'a':
            controls.moveRight(-0.25)
            break
        case 's':
            controls.moveForward(-0.25)
            break
        case 'd':
            controls.moveRight(0.25)
            break
    }
}
document.addEventListener('keydown', onKeyDown, false)

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)
//;(world.solver as CANNON.GSSolver).iterations = 20
//world.allowSleep = true

const material = new THREE.MeshStandardMaterial({
    //color: 0xa2ffb8,
    color: 0xffffff,
    //reflectivity: 0.15,
    metalness: 1.0,
    roughness: 0.25,
    transparent: true,
    opacity: 0.75,
    //transmission: 1.0,
    side: THREE.DoubleSide,
    //clearcoat: 1.0,
    //clearcoatRoughness: 0.35,
})

const pmremGenerator = new THREE.PMREMGenerator(renderer)
const envTexture = new THREE.TextureLoader().load(
    'img/pano-equirectangular.jpg',
    () => {
        material.envMap = pmremGenerator.fromEquirectangular(envTexture).texture
    }
)

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

const groundMirror = new Reflector(new THREE.PlaneGeometry(1024, 1024), {
    color: new THREE.Color(0x222222),
    clipBias: 0.003,
    textureWidth: window.innerWidth * window.devicePixelRatio,
    textureHeight: window.innerHeight * window.devicePixelRatio,
})
groundMirror.position.y = -0.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.BoxGeometry = new THREE.BoxGeometry(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 + 0.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() {
    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: any) => {
            if (e.body.userData) {
                if (e.body.userData.splitCount < 2) {
                    splitObject(e.body.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.removeBody(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
        )

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

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

            scene.add(d)
            meshes[nextId] = d as THREE.Mesh
            ;(d as THREE.Mesh).geometry.scale(0.99, 0.99, 0.99)
            const shape = gemoetryToShape((d as THREE.Mesh).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
        })
    }
}

function gemoetryToShape(geometry: THREE.BufferGeometry) {
    const position = (geometry.attributes.position as THREE.BufferAttribute)
        .array
    const points: THREE.Vector3[] = []
    for (let i = 0; i < position.length; i += 3) {
        points.push(
            new THREE.Vector3(position[i], position[i + 1], position[i + 2])
        )
    }
    const convexHull = new ConvexGeometry(points)
    const shape = CannonUtils.CreateConvexPolyhedron(convexHull)
    return shape
}

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

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

const options = {
    side: {
        FrontSide: THREE.FrontSide,
        BackSide: THREE.BackSide,
        DoubleSide: THREE.DoubleSide,
    },
}

const clock = new THREE.Clock()
let delta

function animate() {
    requestAnimationFrame(animate)

    delta = clock.getDelta()
    if (delta > 0.1) delta = 0.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()

Comments