-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.js
475 lines (388 loc) · 14.5 KB
/
engine.js
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import * as THREE from 'three';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
import * as CANNON from 'CANNON';
import { CSM } from 'three/addons/csm/CSM.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
export class Engine {
constructor() {
this.FrameRateLimit = -1;
this.lastFrameTime = 0;
this.scene = new THREE.Scene();
this.camera = null;
this.csm = null;
this.renderer = new THREE.WebGLRenderer();
this.gameObjects = [];
this.frameCount = 0;
this.currentFPS = 0;
this.physicsWorld = new CANNON.World({
gravity: new CANNON.Vec3(0, -9.82, 0)
});
this.clock = new THREE.Clock();
this.composer = new EffectComposer(this.renderer);
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
}
getGameObjectByBody(physicsBody) {
for (const obj of this.gameObjects) {
if (obj.physicsBody && obj.physicsBody.id === physicsBody.id) {
return obj;
}
}
return null;
}
startRendering() {
if (this.camera && !this.renderPass) {
this.renderPass = new RenderPass(this.scene, this.camera);
this.composer.addPass(this.renderPass);
this.moveRenderPass(this.composer, this.composer.passes.length - 1)
}
}
moveRenderPass(composer, passIndex) {
// Ensure passIndex is within bounds
if (passIndex < 0 || passIndex >= composer.passes.length) {
console.error("Invalid pass index");
return;
}
// Remove the render pass from its current position
const removedPass = composer.passes.splice(passIndex, 1)[0];
// Add the render pass to the start of the array
composer.passes.unshift(removedPass);
}
async start() {
setInterval(async () => {
await this.fixedUpdate();
await this.program.fixedUpdate();
}, 1000 / 60);
setInterval(async () => {
await this.update();
}, 1000 / this.FrameRateLimit);
}
async fixedUpdate() {
const updatePromises = this.gameObjects.map(gameObject => gameObject.fixedUpdate());
await Promise.all(updatePromises);
if (this.physicsWorld == null) return;
this.physicsWorld.step(1/60);
}
async update() {
const currentTime = Date.now();
const deltaTime = (currentTime - this.lastFrameTime) / 1000;
this.lastFrameTime = currentTime;
this.calculateFPS(deltaTime);
if (this.camera) {
if (this.csm) {
this.csm.update(this.camera.matrix);
}
if(!this.listener){
this.listener = new THREE.AudioListener();
this.camera.add( this.listener );
}
}
// Update game logic here
const updatePromises = this.gameObjects.map(gameObject => gameObject.update(deltaTime));
await Promise.all(updatePromises);
await this.program.update(deltaTime);
this.renderScene();
}
calculateFPS(deltaTime) {
const elapsedSeconds = deltaTime * this.frameCount;
if (elapsedSeconds >= 1) { // Calculate FPS every 1 second
const fps = Math.round(this.frameCount / elapsedSeconds);
this.currentFPS = fps;
this.frameCount = 0; // Reset frame count
}
this.frameCount++;
}
renderScene() {
if (this.camera != null) {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
if (this.renderPass) {
this.composer.render();
this.composer.setSize(window.innerWidth, window.innerHeight);
}
else {
this.startRendering();
}
}
}
addGameObject(gameObject) {
gameObject.engine = this;
this.gameObjects.push(gameObject);
gameObject.start();
}
async loadMesh(url) {
try {
if (url.includes("obj")) {
const loader = new OBJLoader();
const object = await new Promise((resolve, reject) => {
loader.load(
url,
resolve,
undefined,
reject
);
});
return object;
}
else{
const loader = new FBXLoader();
const object = await new Promise((resolve, reject) => {
loader.load(
url,
resolve,
undefined,
reject
);
});
return object;
}
} catch (error) {
console.error(`Error loading mesh: ${error}`);
return null;
}
}
async loadShader(url) {
let shader = await (await fetch(url)).text();
return shader;
}
async loadTexture(url) {
return new Promise((resolve, reject) => {
const loader = new THREE.TextureLoader();
loader.load(
url,
texture => {
resolve(texture);
},
undefined,
err => {
console.error('An error occurred while loading the main texture. Loading fallback texture...', err);
// Attempt to load the fallback texture
loader.load(
"./Textures/Required/None.png",
fallbackTexture => {
resolve(fallbackTexture);
},
undefined,
err => {
console.error('An error occurred while loading the fallback texture.', err);
reject(err); // Reject the promise if the fallback texture also fails to load
}
);
}
);
});
}
}
//Main Components
export class GameObject {
constructor() {
this.position = { x: 0, y: 0, z: 0 };
this.rotation = { x: 0, y: 0, z: 0 };
this.scale = { x: 1, y: 1, z: 1 };
this.components = [];
this.physicsBody = null;
this.hasstarted = false;
}
initPhysicsBody(physicsWorld, shape, restitution = 0.5, friction = 1, mass = 0) {
const { x, y, z } = this.position;
const { x: rotx, y: roty, z: rotz } = this.rotation;
const material = new CANNON.Material();
material.friction = friction;
material.restitution = restitution;
const initialQuaternion = new CANNON.Quaternion();
initialQuaternion.setFromEuler(rotx, roty, rotz, "XYZ");
const body = new CANNON.Body({
mass: mass,
position: new CANNON.Vec3(x, y, z),
shape: shape,
material: material,
quaternion: initialQuaternion
});
this.physicsBody = body;
physicsWorld.addBody(body);
}
destroy() {
for (let i = 0; i < this.components.length; i++) {
const component = this.components[i];
if (component.onDestroy) {
component.onDestroy();
}
component.engine = null;
component.gameObject = null;
const index = this.components.indexOf(component);
if (index !== -1) {
this.components.splice(index, 1);
i--;
}
}
if (this.physicsBody && this.physicsBody.world) {
this.physicsBody.world.removeBody(this.physicsBody);
this.physicsBody = null;
}
const index = this.engine.gameObjects.indexOf(this);
if (index !== -1) {
this.engine.gameObjects.splice(index, 1);
}
this.hasStarted = false;
}
setPosition(x, y, z) {
this.position.x = x;
this.position.y = y;
this.position.z = z;
if (this.physicsBody) {
this.physicsBody.x = x;
this.physicsBody.y = y;
this.physicsBody.z = z;
}
}
setRotation(x, y, z) {
if (!this.physicsBody) {
this.rotation.x = x;
this.rotation.y = y;
this.rotation.z = z;
}
else {
const initialQuaternion = new CANNON.Quaternion();
initialQuaternion.setFromEuler(x, y, z, "XYZ");
this.physicsBody.quaternion = initialQuaternion;
}
}
rotateLocalX(angle) {
if (!this.physicsBody) {
const currentRotationQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(this.rotation.x, this.rotation.y, this.rotation.z, 'XYZ'));
const localXRotationQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), angle);
const newRotationQuaternion = currentRotationQuaternion.multiply(localXRotationQuaternion);
const euler = new THREE.Euler().setFromQuaternion(newRotationQuaternion);
this.rotation.x = euler.x;
this.rotation.y = euler.y;
this.rotation.z = euler.z;
} else {
const rotationQuaternion = new CANNON.Quaternion().setFromEuler(angle, 0, 0, 'XYZ');
this.physicsBody.quaternion = rotationQuaternion.mult(this.physicsBody.quaternion);
}
}
rotateLocalY(angle) {
if (!this.physicsBody) {
const currentRotationQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(this.rotation.x, this.rotation.y, this.rotation.z, 'XYZ'));
const localYRotationQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
const newRotationQuaternion = currentRotationQuaternion.multiply(localYRotationQuaternion);
const euler = new THREE.Euler().setFromQuaternion(newRotationQuaternion);
this.rotation.x = euler.x;
this.rotation.y = euler.y;
this.rotation.z = euler.z;
} else {
const rotationQuaternion = new CANNON.Quaternion().setFromEuler(0, angle, 0, 'XYZ');
this.physicsBody.quaternion = rotationQuaternion.mult(this.physicsBody.quaternion);
}
}
rotateLocalZ(angle) {
if (!this.physicsBody) {
const currentRotationQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(this.rotation.x, this.rotation.y, this.rotation.z, 'XYZ'));
const localZRotationQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), angle);
const newRotationQuaternion = currentRotationQuaternion.multiply(localZRotationQuaternion);
const euler = new THREE.Euler().setFromQuaternion(newRotationQuaternion);
this.rotation.x = euler.x;
this.rotation.y = euler.y;
this.rotation.z = euler.z;
} else {
const rotationQuaternion = new CANNON.Quaternion().setFromEuler(0, 0, angle, 'XYZ');
this.physicsBody.quaternion = rotationQuaternion.mult(this.physicsBody.quaternion);
}
}
setScale(x, y, z) {
this.scale.x = x;
this.scale.y = y;
this.scale.z = z;
}
updatePhysics(deltaTime) {
if (this.physicsBody) {
this.position = this.physicsBody.position.clone();
var rot = new CANNON.Vec3();
const { x, y, z, w } = this.physicsBody.quaternion.clone();
rot = new THREE.Euler().setFromQuaternion(new THREE.Quaternion(x, y, z, w), "XYZ");
this.rotation = { x: rot.x, y: rot.y, z: rot.z }
}
}
async update(deltaTime) {
this.updatePhysics(deltaTime);
const promises = this.components.map(async (component) => {
if (component.update) {
return component.update(deltaTime);
}
});
await Promise.all(promises);
}
async fixedUpdate() {
const promises = this.components.map(async (component) => {
if (component.fixedUpdate) {
return component.fixedUpdate();
}
});
await Promise.all(promises);
}
addComponent(component) {
this.components.push(component);
if (this.engine) {
component.engine = this.engine;
component.gameObject = this;
try {
component.start();
} catch {
}
}
}
start() {
this.components.forEach(component => {
component.engine = this.engine;
component.gameObject = this;
if (component.start) {
component.start();
}
});
}
removeComponent(component) {
const index = this.components.indexOf(component);
if (index !== -1) {
this.components.splice(index, 1);
}
}
getComponent(type) {
return this.components.find(component => component instanceof type);
}
}
export class MeshComponent {
constructor(geometry, materials, castShadows, recieveShadows) {
this.materials = materials;
this.mesh = geometry;
this.castShadows = castShadows;
this.recieveShadows = recieveShadows;
}
onDestroy() {
this.engine.scene.remove(this.mesh);
}
start() {
let index = 0;
this.mesh.traverse((child) => {
if (child instanceof THREE.Mesh && this.materials[index]) {
child.material = this.materials[index];
child.receiveShadow = this.recieveShadows;
child.castShadow = this.castShadows;
index++;
}
});
this.engine.scene.add(this.mesh);
}
update(deltaTime) {
if (this.gameObject) {
const { position, rotation, scale } = this.gameObject;
if (this.mesh) {
this.mesh.position.set(position.x, position.y, position.z);
this.mesh.rotation.set(rotation.x, rotation.y, rotation.z);
this.mesh.scale.set(scale.x, scale.y, scale.z);
}
}
}
}