Skip to content

Examples : RNG

Description

Demonstrates using physics container and compound shapes.

<>

This example demonstrates,

  • Using Cannon.js as the Physics engine
  • Creating a container physics objects with other objects rolling around inside.
  • Creating CANNON.Trimeshes from loaded geometries to be used a physics bodies.
  • Demonstrating the OBJLoader and traversing the loaded geometries.

Code

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

const scene = new THREE.Scene()

new RGBELoader().load(
    'img/kloppenheim_06_puresky_1k.hdr',
    function (texture) {
        texture.mapping = THREE.EquirectangularReflectionMapping
        scene.environment = texture
    }
)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
camera.position.set(-10, 4, 14)

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

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

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

const railMaterial = new THREE.MeshPhysicalMaterial()
railMaterial.color = new THREE.Color('#ffffff')
railMaterial.roughness = 0
railMaterial.metalness = 1
railMaterial.clearcoat = 1
railMaterial.clearcoatRoughness = 1

const inverseSphereMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xffffff,
    metalness: 0,
    roughness: 0.35,
    transmission: 1.0,
    clearcoat: 1.0,
    clearcoatRoughness: 0.35,
    ior: 1.05,
    thickness: 5,
})

const ballMaterial = [
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/1-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/2-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/3-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/4-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/5-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/6-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/7-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/8-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/9-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
    new THREE.MeshPhysicalMaterial({
        map: new THREE.TextureLoader().load('img/10-ball.jpg'),
        roughness: 0.88,
        metalness: 1.0,
        clearcoat: 0.3,
        clearcoatRoughness: 0.15,
    }),
]

const positions = [
    [-2, 3, 0],
    [0, 3, 0],
    [2, 3, 0],
    [0, 3, -2],
    [0, 3, 2],
    [-2, 6, 0],
    [0.5, 8, 0.5],
    [2, 6, 0],
    [0, 6, -2],
    [0, 6, 2],
]
const sphereMesh: THREE.Mesh[] = new Array()
const sphereBody: CANNON.Body[] = new Array()
for (let i = 0; i < 10; i++) {
    const sphereGeometry = new THREE.SphereGeometry(1, 16, 16)
    sphereMesh.push(new THREE.Mesh(sphereGeometry, ballMaterial[i]))
    sphereMesh[i].position.x = positions[i][0]
    sphereMesh[i].position.y = positions[i][1]
    sphereMesh[i].position.z = positions[i][2]
    scene.add(sphereMesh[i])
    const sphereShape = new CANNON.Sphere(1)
    sphereBody.push(new CANNON.Body({ mass: 1 }))
    sphereBody[i].addShape(sphereShape)
    sphereBody[i].position.x = sphereMesh[i].position.x
    sphereBody[i].position.y = sphereMesh[i].position.y
    sphereBody[i].position.z = sphereMesh[i].position.z
    world.addBody(sphereBody[i])
}

let inverseSphere: THREE.Object3D
let inverseSphereBody: CANNON.Body
let innerRail: THREE.Object3D
let outerRail: THREE.Object3D
let modelLoaded = false

const objLoader = new OBJLoader()
objLoader.load(
    'models/inverseSphere4.obj',
    (object) => {
        object.traverse(function (child) {
            if ((child as THREE.Mesh).isMesh) {
                if (child.name.startsWith('sphere')) {
                    inverseSphere = child
                    ;(inverseSphere as THREE.Mesh).material =
                        inverseSphereMaterial
                    inverseSphere.position.x = 0
                    inverseSphere.position.y = 5

                    const constraintBody = new CANNON.Body({ mass: 0 })
                    constraintBody.addShape(new CANNON.Sphere(0.01))
                    constraintBody.position.set(0, 5, 0)
                    world.addBody(constraintBody)

                    const shape = CannonUtils.CreateTrimesh(
                        (inverseSphere as THREE.Mesh).geometry
                    )
                    inverseSphereBody = new CANNON.Body({ mass: 100 })
                    inverseSphereBody.addShape(shape)
                    inverseSphereBody.position.x = inverseSphere.position.x
                    inverseSphereBody.position.y = inverseSphere.position.y
                    inverseSphereBody.position.z = inverseSphere.position.z
                    world.addBody(inverseSphereBody)

                    const c = new CANNON.PointToPointConstraint(
                        constraintBody,
                        new CANNON.Vec3(0, 0, 0),
                        inverseSphereBody,
                        new CANNON.Vec3(0, 0, 0)
                    )
                    world.addConstraint(c)
                } else if (child.name.startsWith('outerRail_')) {
                    outerRail = child
                    ;(outerRail as THREE.Mesh).material = railMaterial
                    outerRail.position.y = 5

                    const outerRailShape = CannonUtils.CreateTrimesh(
                        (outerRail as THREE.Mesh).geometry
                    )

                    const outerRailBody = new CANNON.Body({ mass: 0 })
                    outerRailBody.addShape(outerRailShape)
                    outerRailBody.position.set(0, 5, 0)
                    world.addBody(outerRailBody)
                } else if (child.name.startsWith('innerRail_')) {
                    innerRail = child
                    ;(innerRail as THREE.Mesh).material = railMaterial
                    innerRail.position.y = 5

                    const innerRailShape = CannonUtils.CreateTrimesh(
                        (innerRail as THREE.Mesh).geometry
                    )
                    inverseSphereBody.addShape(innerRailShape)
                }
            }
        })
        scene.add(inverseSphere)
        scene.add(outerRail)
        scene.add(innerRail)
        modelLoaded = true
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log(error)
    }
)

const planeGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh = new THREE.Mesh(
    planeGeometry,
    new THREE.MeshStandardMaterial()
)
planeMesh.rotateX(-Math.PI / 2)
scene.add(planeMesh)

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 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)
const inverseSphereMaterialFolder = gui.addFolder('InverseSphereMaterial')
inverseSphereMaterialFolder.add(inverseSphereMaterial, 'roughness', 0, 1, 0.01)
inverseSphereMaterialFolder.add(inverseSphereMaterial, 'metalness', 0, 1, 0.01)
inverseSphereMaterialFolder.add(inverseSphereMaterial, 'clearcoat', 0, 1, 0.01)
inverseSphereMaterialFolder.add(
    inverseSphereMaterial,
    'clearcoatRoughness',
    0,
    1,
    0.01
)
inverseSphereMaterialFolder.add(
    inverseSphereMaterial,
    'transmission',
    0,
    1,
    0.01
)
inverseSphereMaterialFolder.add(inverseSphereMaterial, 'ior', 1, 2.4, 0.01)
inverseSphereMaterialFolder.add(inverseSphereMaterial, 'thickness', 0, 10, 0.01)
inverseSphereMaterialFolder.open()
const railMaterialFolder = gui.addFolder('RailMaterial')
railMaterialFolder.add(railMaterial, 'roughness', 0.0, 1.0, 0.01)
railMaterialFolder.add(railMaterial, 'metalness', 0, 1, 0.01)
railMaterialFolder.add(railMaterial, 'clearcoat', 0, 1, 0.01)
railMaterialFolder.add(railMaterial, 'clearcoatRoughness', 0, 1, 0.01)

const clock = new THREE.Clock()
let delta

function animate() {
    requestAnimationFrame(animate)

    controls.update()
    delta = clock.getDelta() * 2
    if (delta > 0.1) delta = 0.1
    world.step(delta)

    for (let i = 0; i < 10; i++) {
        sphereMesh[i].position.set(
            sphereBody[i].position.x,
            sphereBody[i].position.y,
            sphereBody[i].position.z
        )
        sphereMesh[i].quaternion.set(
            sphereBody[i].quaternion.x,
            sphereBody[i].quaternion.y,
            sphereBody[i].quaternion.z,
            sphereBody[i].quaternion.w
        )
    }

    if (modelLoaded) {
        inverseSphereBody.angularVelocity.set(0, 0, -0.5)
        inverseSphere.position.set(
            inverseSphereBody.position.x,
            inverseSphereBody.position.y,
            inverseSphereBody.position.z
        )
        inverseSphere.quaternion.set(
            inverseSphereBody.quaternion.x,
            inverseSphereBody.quaternion.y,
            inverseSphereBody.quaternion.z,
            inverseSphereBody.quaternion.w
        )
        innerRail.position.set(
            inverseSphereBody.position.x,
            inverseSphereBody.position.y,
            inverseSphereBody.position.z
        )
        innerRail.quaternion.set(
            inverseSphereBody.quaternion.x,
            inverseSphereBody.quaternion.y,
            inverseSphereBody.quaternion.z,
            inverseSphereBody.quaternion.w
        )
    }

    render()

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

animate()

Comments