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