-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
GameEntity.js
644 lines (457 loc) · 14.4 KB
/
GameEntity.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
import { Vector3 } from '../math/Vector3.js';
import { Quaternion } from '../math/Quaternion.js';
import { Matrix4 } from '../math/Matrix4.js';
import { Logger } from './Logger.js';
import { MathUtils } from '../math/MathUtils.js';
const targetRotation = new Quaternion();
const targetDirection = new Vector3();
const positionWorld = new Vector3();
const quaternionWorld = new Quaternion();
/**
* Base class for all game entities.
*
* @author {@link https://github.com/Mugen87|Mugen87}
*/
class GameEntity {
/**
* Constructs a new game entity.
*/
constructor() {
/**
* The name of this game entity.
* @type {String}
*/
this.name = '';
/**
* Whether this game entity is active or not.
* @type {Boolean}
* @default true
*/
this.active = true;
/**
* The child entities of this game entity.
* @type {Array<GameEntity>}
*/
this.children = new Array();
/**
* A reference to the parent entity of this game entity.
* Automatically set when added to a {@link GameEntity}.
* @type {GameEntity}
* @default null
* @readonly
*/
this.parent = null;
/**
* A list of neighbors of this game entity.
* @type {Array<GameEntity>}
* @readonly
*/
this.neighbors = new Array();
/**
* Game entities within this radius are considered as neighbors of this entity.
* @type {Number}
* @default 1
*/
this.neighborhoodRadius = 1;
/**
* Whether the neighborhood of this game entity is updated or not.
* @type {Boolean}
* @default false
*/
this.updateNeighborhood = false;
/**
* The position of this game entity.
* @type {Vector3}
*/
this.position = new Vector3();
/**
* The rotation of this game entity.
* @type {Quaternion}
*/
this.rotation = new Quaternion();
/**
* The scaling of this game entity.
* @type {Vector3}
*/
this.scale = new Vector3( 1, 1, 1 );
/**
* The default forward vector of this game entity.
* @type {Vector3}
* @default (0,0,1)
*/
this.forward = new Vector3( 0, 0, 1 );
/**
* The default up vector of this game entity.
* @type {Vector3}
* @default (0,1,0)
*/
this.up = new Vector3( 0, 1, 0 );
/**
* The bounding radius of this game entity in world units.
* @type {Number}
* @default 0
*/
this.boundingRadius = 0;
/**
* The maximum turn rate of this game entity in radians per seconds.
* @type {Number}
* @default π
*/
this.maxTurnRate = Math.PI;
/**
* Whether the entity can activate a trigger or not.
* @type {Boolean}
* @default true
*/
this.canActivateTrigger = true;
/**
* A reference to the entity manager of this game entity.
* Automatically set when added to an {@link EntityManager}.
* @type {EntityManager}
* @default null
* @readonly
*/
this.manager = null;
// private properties
// local transformation matrix. no part of the public API due to caching
this._localMatrix = new Matrix4();
// internal world matrix reference (only accessible via a getter)
this._worldMatrix = new Matrix4();
// per-entity cache in order to avoid unnecessary matrix calculations
this._cache = {
position: new Vector3(),
rotation: new Quaternion(),
scale: new Vector3( 1, 1, 1 )
};
// render component
this._renderComponent = null;
this._renderComponentCallback = null;
// flag to indicate whether the entity was updated by its manager at least once or not
this._started = false;
//
this._uuid = null;
// if set to true, it means the world matrix requires a recomputation
this._worldMatrixDirty = false;
}
/**
* A transformation matrix representing the world space of this game entity.
* @type {Matrix4}
* @readonly
*/
get worldMatrix() {
this._updateWorldMatrix();
return this._worldMatrix;
}
/**
* Unique ID, primarily used in context of serialization/deserialization.
* @type {String}
* @readonly
*/
get uuid() {
if ( this._uuid === null ) {
this._uuid = MathUtils.generateUUID();
}
return this._uuid;
}
/**
* Executed when this game entity is updated for the first time by its {@link EntityManager}.
*
* @return {GameEntity} A reference to this game entity.
*/
start() {}
/**
* Updates the internal state of this game entity. Normally called by {@link EntityManager#update}
* in each simulation step.
*
* @param {Number} delta - The time delta.
* @return {GameEntity} A reference to this game entity.
*/
update( /* delta */ ) {}
/**
* Adds a game entity as a child to this game entity.
*
* @param {GameEntity} entity - The game entity to add.
* @return {GameEntity} A reference to this game entity.
*/
add( entity ) {
if ( entity.parent !== null ) {
entity.parent.remove( entity );
}
this.children.push( entity );
entity.parent = this;
return this;
}
/**
* Removes a game entity as a child from this game entity.
*
* @param {GameEntity} entity - The game entity to remove.
* @return {GameEntity} A reference to this game entity.
*/
remove( entity ) {
const index = this.children.indexOf( entity );
this.children.splice( index, 1 );
entity.parent = null;
return this;
}
/**
* Computes the current direction (forward) vector of this game entity
* and stores the result in the given vector.
*
* @param {Vector3} result - The direction vector of this game entity.
* @return {Vector3} The direction vector of this game entity.
*/
getDirection( result ) {
return result.copy( this.forward ).applyRotation( this.rotation ).normalize();
}
/**
* Directly rotates the entity so it faces the given target position.
*
* @param {Vector3} target - The target position.
* @return {GameEntity} A reference to this game entity.
*/
lookAt( target ) {
const parent = this.parent;
if ( parent !== null ) {
this.getWorldPosition( positionWorld );
targetDirection.subVectors( target, positionWorld ).normalize();
this.rotation.lookAt( this.forward, targetDirection, this.up );
quaternionWorld.extractRotationFromMatrix( parent.worldMatrix ).inverse();
this.rotation.premultiply( quaternionWorld );
} else {
targetDirection.subVectors( target, this.position ).normalize();
this.rotation.lookAt( this.forward, targetDirection, this.up );
}
return this;
}
/**
* Given a target position, this method rotates the entity by an amount not
* greater than {@link GameEntity#maxTurnRate} until it directly faces the target.
*
* @param {Vector3} target - The target position.
* @param {Number} delta - The time delta.
* @param {Number} tolerance - A tolerance value in radians to tweak the result
* when a game entity is considered to face a target.
* @return {Boolean} Whether the entity is faced to the target or not.
*/
rotateTo( target, delta, tolerance = 0.0001 ) {
const parent = this.parent;
if ( parent !== null ) {
this.getWorldPosition( positionWorld );
targetDirection.subVectors( target, positionWorld ).normalize();
targetRotation.lookAt( this.forward, targetDirection, this.up );
quaternionWorld.extractRotationFromMatrix( parent.worldMatrix ).inverse();
targetRotation.premultiply( quaternionWorld );
} else {
targetDirection.subVectors( target, this.position ).normalize();
targetRotation.lookAt( this.forward, targetDirection, this.up );
}
return this.rotation.rotateTo( targetRotation, this.maxTurnRate * delta, tolerance );
}
/**
* Computes the current direction (forward) vector of this game entity
* in world space and stores the result in the given vector.
*
* @param {Vector3} result - The direction vector of this game entity in world space.
* @return {Vector3} The direction vector of this game entity in world space.
*/
getWorldDirection( result ) {
quaternionWorld.extractRotationFromMatrix( this.worldMatrix );
return result.copy( this.forward ).applyRotation( quaternionWorld ).normalize();
}
/**
* Computes the current position of this game entity in world space and
* stores the result in the given vector.
*
* @param {Vector3} result - The position of this game entity in world space.
* @return {Vector3} The position of this game entity in world space.
*/
getWorldPosition( result ) {
return result.extractPositionFromMatrix( this.worldMatrix );
}
/**
* Sets a renderable component of a 3D engine with a sync callback for this game entity.
*
* @param {Object} renderComponent - A renderable component of a 3D engine.
* @param {Function} callback - A callback that can be used to sync this game entity with the renderable component.
* @return {GameEntity} A reference to this game entity.
*/
setRenderComponent( renderComponent, callback ) {
this._renderComponent = renderComponent;
this._renderComponentCallback = callback;
return this;
}
/**
* Holds the implementation for the message handling of this game entity.
*
* @param {Telegram} telegram - The telegram with the message data.
* @return {Boolean} Whether the message was processed or not.
*/
handleMessage() {
return false;
}
/**
* Holds the implementation for the line of sight test of this game entity.
* This method is used by {@link Vision#visible} in order to determine whether
* this game entity blocks the given line of sight or not. Implement this method
* when your game entity acts as an obstacle.
*
* @param {Ray} ray - The ray that represents the line of sight.
* @param {Vector3} intersectionPoint - The intersection point.
* @return {Vector3} The intersection point.
*/
lineOfSightTest() {
return null;
}
/**
* Sends a message with the given data to the specified receiver.
*
* @param {GameEntity} receiver - The receiver.
* @param {String} message - The actual message.
* @param {Number} delay - A time value in millisecond used to delay the message dispatching.
* @param {Object} data - An object for custom data.
* @return {GameEntity} A reference to this game entity.
*/
sendMessage( receiver, message, delay = 0, data = null ) {
if ( this.manager !== null ) {
this.manager.sendMessage( this, receiver, message, delay, data );
} else {
Logger.error( 'YUKA.GameEntity: The game entity must be added to a manager in order to send a message.' );
}
return this;
}
/**
* Transforms this instance into a JSON object.
*
* @return {Object} The JSON object.
*/
toJSON() {
return {
type: this.constructor.name,
uuid: this.uuid,
name: this.name,
active: this.active,
children: entitiesToIds( this.children ),
parent: ( this.parent !== null ) ? this.parent.uuid : null,
neighbors: entitiesToIds( this.neighbors ),
neighborhoodRadius: this.neighborhoodRadius,
updateNeighborhood: this.updateNeighborhood,
position: this.position.toArray( new Array() ),
rotation: this.rotation.toArray( new Array() ),
scale: this.scale.toArray( new Array() ),
forward: this.forward.toArray( new Array() ),
up: this.up.toArray( new Array() ),
boundingRadius: this.boundingRadius,
maxTurnRate: this.maxTurnRate,
canActivateTrigger: this.canActivateTrigger,
worldMatrix: this.worldMatrix.toArray( new Array() ),
_localMatrix: this._localMatrix.toArray( new Array() ),
_cache: {
position: this._cache.position.toArray( new Array() ),
rotation: this._cache.rotation.toArray( new Array() ),
scale: this._cache.scale.toArray( new Array() ),
},
_started: this._started
};
}
/**
* Restores this instance from the given JSON object.
*
* @param {Object} json - The JSON object.
* @return {GameEntity} A reference to this game entity.
*/
fromJSON( json ) {
this.name = json.name;
this.active = json.active;
this.neighborhoodRadius = json.neighborhoodRadius;
this.updateNeighborhood = json.updateNeighborhood;
this.position.fromArray( json.position );
this.rotation.fromArray( json.rotation );
this.scale.fromArray( json.scale );
this.forward.fromArray( json.forward );
this.up.fromArray( json.up );
this.boundingRadius = json.boundingRadius;
this.maxTurnRate = json.maxTurnRate;
this.canActivateTrigger = json.canActivateTrigger;
this.children = json.children.slice();
this.neighbors = json.neighbors.slice();
this.parent = json.parent;
this._localMatrix.fromArray( json._localMatrix );
this._worldMatrix.fromArray( json.worldMatrix );
this._cache.position.fromArray( json._cache.position );
this._cache.rotation.fromArray( json._cache.rotation );
this._cache.scale.fromArray( json._cache.scale );
this._started = json._started;
this._uuid = json.uuid;
return this;
}
/**
* Restores UUIDs with references to GameEntity objects.
*
* @param {Map<String,GameEntity>} entities - Maps game entities to UUIDs.
* @return {GameEntity} A reference to this game entity.
*/
resolveReferences( entities ) {
//
const neighbors = this.neighbors;
for ( let i = 0, l = neighbors.length; i < l; i ++ ) {
neighbors[ i ] = entities.get( neighbors[ i ] );
}
//
const children = this.children;
for ( let i = 0, l = children.length; i < l; i ++ ) {
children[ i ] = entities.get( children[ i ] );
}
//
this.parent = entities.get( this.parent ) || null;
return this;
}
// Updates the transformation matrix representing the local space.
_updateMatrix() {
const cache = this._cache;
if ( cache.position.equals( this.position ) &&
cache.rotation.equals( this.rotation ) &&
cache.scale.equals( this.scale ) ) {
return;
}
this._localMatrix.compose( this.position, this.rotation, this.scale );
cache.position.copy( this.position );
cache.rotation.copy( this.rotation );
cache.scale.copy( this.scale );
this._worldMatrixDirty = true;
}
_updateWorldMatrix() {
const parent = this.parent;
if ( parent !== null ) {
parent._updateWorldMatrix();
}
this._updateMatrix();
if ( this._worldMatrixDirty === true ) {
if ( parent === null ) {
this._worldMatrix.copy( this._localMatrix );
} else {
this._worldMatrix.multiplyMatrices( this.parent._worldMatrix, this._localMatrix );
}
this._worldMatrixDirty = false;
// invalidate world matrices of children
const children = this.children;
for ( let i = 0, l = children.length; i < l; i ++ ) {
const child = children[ i ];
child._worldMatrixDirty = true;
}
}
}
// deprecated
updateWorldMatrix() {
// this warning will be removed with v1.0.0
console.warn( 'GameEntity: .updateWorldMatrix() has been removed. World matrices are automatically updated on access.' );
return this;
}
}
function entitiesToIds( array ) {
const ids = new Array();
for ( let i = 0, l = array.length; i < l; i ++ ) {
ids.push( array[ i ].uuid );
}
return ids;
}
export { GameEntity };