-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathgraph-node.js
More file actions
1868 lines (1676 loc) · 61.9 KB
/
Copy pathgraph-node.js
File metadata and controls
1868 lines (1676 loc) · 61.9 KB
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EventHandler } from '../core/event-handler.js';
import { Tags } from '../core/tags.js';
import { Debug } from '../core/debug.js';
import { Mat3 } from '../core/math/mat3.js';
import { Mat4 } from '../core/math/mat4.js';
import { Quat } from '../core/math/quat.js';
import { Vec3 } from '../core/math/vec3.js';
const scaleCompensatePosTransform = new Mat4();
const scaleCompensatePos = new Vec3();
const scaleCompensateRot = new Quat();
const scaleCompensateRot2 = new Quat();
const scaleCompensateScale = new Vec3();
const scaleCompensateScaleForParent = new Vec3();
const tmpMat4 = new Mat4();
const tmpQuat = new Quat();
const position = new Vec3();
const invParentWtm = new Mat4();
const rotation = new Quat();
const invParentRot = new Quat();
const matrix = new Mat4();
const target = new Vec3();
const up = new Vec3();
/**
* Helper function that handles signature overloading to receive a test function.
*
* @param {FindNodeCallback|string} attr - Attribute or lambda.
* @param {*} [value] - Optional value in case of `attr` being a `string`
* @returns {FindNodeCallback} Test function that receives a GraphNode and returns a boolean.
*/
function createTest(attr, value) {
if (attr instanceof Function) {
return attr;
}
return (node) => {
let x = node[attr];
if (x instanceof Function) {
x = x();
}
return x === value;
};
}
/**
* Helper function to recurse findOne without calling createTest constantly.
*
* @param {GraphNode} node - Current node.
* @param {FindNodeCallback} test - Test function.
* @returns {GraphNode|null} A graph node that matches the search criteria. Returns null if no
* node is found.
*/
function findNode(node, test) {
if (test(node)) {
return node;
}
const children = node._children;
const len = children.length;
for (let i = 0; i < len; ++i) {
const result = findNode(children[i], test);
if (result) {
return result;
}
}
return null;
}
/**
* @callback FindNodeCallback
* Callback used by {@link GraphNode#find} and {@link GraphNode#findOne} to search through a graph
* node and all of its descendants.
* @param {GraphNode} node - The current graph node.
* @returns {boolean} Returning `true` will result in that node being returned from
* {@link GraphNode#find} or {@link GraphNode#findOne}.
*/
/**
* @callback ForEachNodeCallback
* Callback used by {@link GraphNode#forEach} to iterate through a graph node and all of its
* descendants.
* @param {GraphNode} node - The current graph node.
* @returns {void}
*/
/**
* A GraphNode is a node in the scene graph: a named object with a position, rotation and scale,
* and a list of {@link children} whose transforms are expressed relative to it. Nodes form a tree,
* and the world transform of any node is its local transform combined with the world transform of
* its {@link parent}; the {@link root} has no parent, so its world transform is its local one. The
* engine brings every world transform up to date each frame before rendering, so a change to a
* parent reaches all of its descendants.
*
* GraphNode is the base class of {@link Entity}, which adds components, so in practice these
* methods are called on entities. The conventions are the same on both:
*
* - Local methods such as {@link setLocalPosition} and {@link getLocalRotation} work relative to
* the parent. Their world counterparts, {@link setPosition}, {@link getRotation} and the rest,
* account for the whole chain of ancestors.
* - Setters accept separate components or a vector or quaternion, and copy the value.
* - Getters return the node's internal storage as read-only; clone the result if you need to
* keep or modify it.
* - Euler angles are in degrees, and {@link forward} is the node's negative Z axis.
*
* Build the hierarchy with {@link addChild}, {@link insertChild}, {@link removeChild} and
* {@link reparent}, and search it with {@link findByName}, {@link findByPath}, {@link findByTag}
* and {@link find}. Setting {@link enabled} to false disables the node and its whole subtree.
*
* @example
* // Move a node one unit in its own facing direction, then turn it to face a target
* node.translateLocal(0, 0, -1);
* node.lookAt(target.getPosition());
* @example
* // Getters return read-only internal storage: clone before modifying
* const start = node.getPosition().clone();
* start.y += 1;
* node.setPosition(start);
* @category Framework
*/
class GraphNode extends EventHandler {
/**
* The non-unique name of a graph node. Defaults to 'Untitled'.
*
* @type {string}
*/
name;
/**
* Interface for tagging graph nodes. Tag based searches can be performed using the
* {@link findByTag} function.
*
* @type {Tags}
*/
tags = new Tags(this);
// Local space properties of transform (only first 3 are settable by the user)
/** @private */
localPosition = new Vec3();
/** @private */
localRotation = new Quat();
/** @private */
localScale = new Vec3(1, 1, 1);
/**
* @type {Vec3}
* @private
*/
localEulerAngles = new Vec3(); // Only calculated on request
// World space properties of transform
/** @private */
position = new Vec3();
/** @private */
rotation = new Quat();
/** @private */
eulerAngles = new Vec3();
/**
* @type {Vec3|null}
* @private
*/
_scale = null;
/** @private */
localTransform = new Mat4();
/** @private */
_dirtyLocal = false;
/** @private */
_aabbVer = 0;
/**
* Marks the node to ignore hierarchy sync entirely (including children nodes). The engine code
* automatically freezes and unfreezes objects whenever required. Segregating dynamic and
* stationary nodes into subhierarchies allows to reduce sync time significantly.
*
* @private
*/
_frozen = false;
/** @private */
worldTransform = new Mat4();
/** @private */
_dirtyWorld = false;
/**
* Cached value representing the negatively scaled world transform. If the value is 0, this
* marks this value as dirty and it needs to be recalculated. If the value is 1, the world
* transform is not negatively scaled. If the value is -1, the world transform is negatively
* scaled.
*
* @private
*/
_worldScaleSign = 0;
/** @private */
_normalMatrix = new Mat3();
/** @private */
_dirtyNormal = true;
/**
* @type {Vec3|null}
* @private
*/
_right = null;
/**
* @type {Vec3|null}
* @private
*/
_up = null;
/**
* @type {Vec3|null}
* @private
*/
_forward = null;
/**
* @type {GraphNode|null}
* @private
*/
_parent = null;
/**
* @type {GraphNode[]}
* @protected
*/
_children = [];
/** @private */
_graphDepth = 0;
/**
* Represents enabled state of the entity. If the entity is disabled, the entity including all
* children are excluded from updates.
*
* @private
*/
_enabled = true;
/**
* Represents enabled state of the entity in the hierarchy. It's true only if this entity and
* all parent entities all the way to the scene's root are enabled.
*
* @private
*/
_enabledInHierarchy = false;
/** @ignore */
scaleCompensation = false;
/**
* Create a new GraphNode instance.
*
* @param {string} [name] - The non-unique name of a graph node. Defaults to 'Untitled'.
*/
constructor(name = 'Untitled') {
super();
this.name = name;
}
/**
* Gets the normalized local space X-axis vector of the graph node in world space.
*
* @type {Readonly<Vec3>}
*/
get right() {
if (!this._right) {
this._right = new Vec3();
}
return this.getWorldTransform().getX(this._right).normalize();
}
/**
* Gets the normalized local space Y-axis vector of the graph node in world space.
*
* @type {Readonly<Vec3>}
*/
get up() {
if (!this._up) {
this._up = new Vec3();
}
return this.getWorldTransform().getY(this._up).normalize();
}
/**
* Gets the normalized local space negative Z-axis vector of the graph node in world space.
*
* @type {Readonly<Vec3>}
*/
get forward() {
if (!this._forward) {
this._forward = new Vec3();
}
return this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1);
}
/**
* Gets the 3x3 transformation matrix used to transform normals.
*
* @type {Mat3}
* @ignore
*/
get normalMatrix() {
const normalMat = this._normalMatrix;
if (this._dirtyNormal) {
normalMat.invertMat4(this.getWorldTransform()).transpose();
this._dirtyNormal = false;
}
return normalMat;
}
/**
* Sets the enabled state of the GraphNode. If one of the GraphNode's parents is disabled there
* will be no other side effects. If all the parents are enabled then the new value will
* activate or deactivate all the enabled children of the GraphNode.
*
* @type {boolean}
*/
set enabled(enabled) {
if (this._enabled !== enabled) {
this._enabled = enabled;
// if enabling entity, make all children enabled in hierarchy only when the parent is as well
// if disabling entity, make all children disabled in hierarchy in all cases
if (enabled && this._parent?.enabled || !enabled) {
this._notifyHierarchyStateChanged(this, enabled);
}
}
}
/**
* Gets the enabled state of the GraphNode.
*
* @type {boolean}
*/
get enabled() {
// make sure to check this._enabled too because if that
// was false when a parent was updated the _enabledInHierarchy
// flag may not have been updated for optimization purposes
return this._enabled && this._enabledInHierarchy;
}
/**
* Gets the parent of this graph node.
*
* @type {GraphNode|null}
*/
get parent() {
return this._parent;
}
/**
* Gets the path of this graph node relative to the root of the hierarchy.
*
* @type {string}
*/
get path() {
let node = this._parent;
if (!node) {
return '';
}
let result = this.name;
while (node && node._parent) {
result = `${node.name}/${result}`;
node = node._parent;
}
return result;
}
/**
* Gets the oldest ancestor graph node from this graph node.
*
* @type {GraphNode}
*/
get root() {
let result = this;
while (result._parent) {
result = result._parent;
}
return result;
}
/**
* Gets the children of this graph node. Use addChild, insertChild, removeChild or reparent to
* change the hierarchy.
*
* @type {ReadonlyArray<GraphNode>}
*/
get children() {
return this._children;
}
// ---- deprecated block start ----
/**
* @deprecated Use GraphNode#children instead.
* @ignore
*/
getChildren() {
Debug.deprecated('GraphNode#getChildren is deprecated. Use GraphNode#children instead.');
return this.children;
}
/**
* @deprecated Use GraphNode#name instead.
* @ignore
*/
getName() {
Debug.deprecated('GraphNode#getName is deprecated. Use GraphNode#name instead.');
return this.name;
}
/**
* @deprecated Use GraphNode#path instead.
* @ignore
*/
getPath() {
Debug.deprecated('GraphNode#getPath is deprecated. Use GraphNode#path instead.');
return this.path;
}
/**
* @deprecated Use GraphNode#root instead.
* @ignore
*/
getRoot() {
Debug.deprecated('GraphNode#getRoot is deprecated. Use GraphNode#root instead.');
return this.root;
}
/**
* @deprecated Use GraphNode#parent instead.
* @returns {GraphNode|null} The parent node, or null if this node has no parent.
* @ignore
*/
getParent() {
Debug.deprecated('GraphNode#getParent is deprecated. Use GraphNode#parent instead.');
return this.parent;
}
/**
* @deprecated Use GraphNode#name instead.
* @param {string} name - The name to set.
* @ignore
*/
setName(name) {
Debug.deprecated('GraphNode#setName is deprecated. Use GraphNode#name instead.');
this.name = name;
}
// ---- deprecated block end ----
/**
* Gets the depth of this child within the graph. Note that for performance reasons this is
* only recalculated when a node is added to a new parent. In other words, it is not
* recalculated when a node is simply removed from the graph.
*
* @type {number}
*/
get graphDepth() {
return this._graphDepth;
}
/**
* @param {GraphNode} node - Graph node to update.
* @param {boolean} enabled - True if enabled in the hierarchy, false if disabled.
* @protected
*/
_notifyHierarchyStateChanged(node, enabled) {
node._onHierarchyStateChanged(enabled);
const c = node._children;
for (let i = 0, len = c.length; i < len; i++) {
if (c[i]._enabled) {
this._notifyHierarchyStateChanged(c[i], enabled);
}
}
}
/**
* Called when the enabled flag of the entity or one of its parents changes.
*
* @param {boolean} enabled - True if enabled in the hierarchy, false if disabled.
* @protected
*/
_onHierarchyStateChanged(enabled) {
// Override in derived classes
this._enabledInHierarchy = enabled;
if (enabled && !this._frozen) {
this._unfreezeParentToRoot();
}
}
/**
* @param {this} clone - The cloned graph node to copy into.
* @private
*/
_cloneInternal(clone) {
clone.name = this.name;
const tags = this.tags._list;
clone.tags.clear();
for (let i = 0; i < tags.length; i++) {
clone.tags.add(tags[i]);
}
clone.localPosition.copy(this.localPosition);
clone.localRotation.copy(this.localRotation);
clone.localScale.copy(this.localScale);
clone.localEulerAngles.copy(this.localEulerAngles);
clone.position.copy(this.position);
clone.rotation.copy(this.rotation);
clone.eulerAngles.copy(this.eulerAngles);
clone.localTransform.copy(this.localTransform);
clone._dirtyLocal = this._dirtyLocal;
clone.worldTransform.copy(this.worldTransform);
clone._dirtyWorld = this._dirtyWorld;
clone._dirtyNormal = this._dirtyNormal;
clone._aabbVer = this._aabbVer + 1;
clone._enabled = this._enabled;
clone.scaleCompensation = this.scaleCompensation;
// false as this node is not in the hierarchy yet
clone._enabledInHierarchy = false;
}
/**
* Clone a graph node.
*
* @returns {this} A clone of the specified graph node.
*/
clone() {
const clone = new this.constructor();
this._cloneInternal(clone);
return clone;
}
/**
* Copy a graph node.
*
* @param {GraphNode} source - The graph node to copy.
* @returns {GraphNode} The destination graph node.
* @ignore
*/
copy(source) {
source._cloneInternal(this);
return this;
}
/**
* Destroy the graph node and all of its descendants. First, the graph node is removed from the
* hierarchy. This is then repeated recursively for all descendants of the graph node.
*
* The last thing the graph node does is fire the `destroy` event.
*
* @example
* const firstChild = graphNode.children[0];
* firstChild.destroy(); // destroy child and all of its descendants
*/
destroy() {
// Detach from parent
this.remove();
// Recursively destroy all children
const children = this._children;
while (children.length) {
// Remove last child from the array
const child = children.pop();
// Disconnect it from the parent: this is only an optimization step, to prevent calling
// GraphNode#removeChild which would try to refind it via this._children.indexOf (which
// will fail, because we just removed it).
child._parent = null;
child.destroy();
}
// fire destroy event
this.fire('destroy', this);
// clear all events
this.off();
}
/**
* Search the graph node and all of its descendants for the nodes that satisfy some search
* criteria.
*
* @param {FindNodeCallback|string} attr - This can either be a function or a string. If it's a
* function, it is executed for each descendant node to test if node satisfies the search
* logic. Returning true from the function will include the node into the results. If it's a
* string then it represents the name of a field or a method of the node. If this is the name
* of a field then the value passed as the second argument will be checked for equality. If
* this is the name of a function then the return value of the function will be checked for
* equality against the value passed as the second argument to this function.
* @param {*} [value] - If the first argument (attr) is a property name then this value
* will be checked against the value of the property.
* @returns {GraphNode[]} The array of graph nodes that match the search criteria.
* @example
* // Finds all nodes that have a model component and have 'door' in their lower-cased name
* const doors = house.find((node) => {
* return node.model && node.name.toLowerCase().indexOf('door') !== -1;
* });
* @example
* // Finds all nodes that have the name property set to 'Test'
* const entities = parent.find('name', 'Test');
*/
find(attr, value) {
const results = [];
const test = createTest(attr, value);
this.forEach((node) => {
if (test(node)) {
results.push(node);
}
});
return results;
}
/**
* Search the graph node and all of its descendants for the first node that satisfies some
* search criteria.
*
* @param {FindNodeCallback|string} attr - This can either be a function or a string. If it's a
* function, it is executed for each descendant node to test if node satisfies the search
* logic. Returning true from the function will result in that node being returned from
* findOne. If it's a string then it represents the name of a field or a method of the node. If
* this is the name of a field then the value passed as the second argument will be checked for
* equality. If this is the name of a function then the return value of the function will be
* checked for equality against the value passed as the second argument to this function.
* @param {*} [value] - If the first argument (attr) is a property name then this value
* will be checked against the value of the property.
* @returns {GraphNode|null} A graph node that matches the search criteria. Returns null if no
* node is found.
* @example
* // Find the first node that is called 'head' and has a model component
* const head = player.findOne((node) => {
* return node.model && node.name === 'head';
* });
* @example
* // Finds the first node that has the name property set to 'Test'
* const node = parent.findOne('name', 'Test');
*/
findOne(attr, value) {
const test = createTest(attr, value);
return findNode(this, test);
}
/**
* Return all graph nodes that satisfy the search query. Query can be simply a string, or comma
* separated strings, to have inclusive results of graph nodes that match at least one query. A
* query that consists of an array of tags can be used to match graph nodes that have each tag
* of the array.
*
* @param {...*} query - Name of a tag or array of tags.
* @returns {GraphNode[]} A list of all graph nodes that match the query.
* @example
* // Return all graph nodes tagged with `animal`
* const animals = node.findByTag("animal");
* @example
* // Return all graph nodes tagged with `bird` OR `mammal`
* const birdsAndMammals = node.findByTag("bird", "mammal");
* @example
* // Return all graph nodes tagged with `carnivore` AND `mammal`
* const meatEatingMammals = node.findByTag(["carnivore", "mammal"]);
* @example
* // Return all graph nodes tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`)
* const meatEatingMammalsAndReptiles = node.findByTag(["carnivore", "mammal"], ["carnivore", "reptile"]);
*/
findByTag(...query) {
const results = [];
const queryNode = (node, checkNode) => {
if (checkNode && node.tags.has(...query)) {
results.push(node);
}
for (let i = 0; i < node._children.length; i++) {
queryNode(node._children[i], true);
}
};
queryNode(this, false);
return results;
}
/**
* Get the first node found in the graph with the name. The search is depth first.
*
* @param {string} name - The name of the node.
* @returns {GraphNode|null} The first node to be found matching the supplied name. Returns
* null if no node is found.
*/
findByName(name) {
return this.findOne('name', name);
}
/**
* Get the first node found in the graph by its full path in the graph. The full path has this
* form 'parent/child/sub-child'. The search is depth first.
*
* @param {string|string[]} path - The full path of the GraphNode as either a string or array
* of GraphNode names.
* @returns {GraphNode|null} The first node to be found matching the supplied path. Returns
* null if no node is found.
* @example
* // String form
* const grandchild = this.entity.findByPath('child/grandchild');
* @example
* // Array form
* const grandchild = this.entity.findByPath(['child', 'grandchild']);
*/
findByPath(path) {
// accept either string path with '/' separators or array of parts.
const parts = Array.isArray(path) ? path : path.split('/');
let result = this;
for (let i = 0, imax = parts.length; i < imax; ++i) {
result = result.children.find(c => c.name === parts[i]);
if (!result) {
return null;
}
}
return result;
}
/**
* Executes a provided function once on this graph node and all of its descendants.
*
* @param {ForEachNodeCallback} callback - The function to execute on the graph node and each
* descendant.
* @param {object} [thisArg] - Optional value to use as this when executing callback function.
* @example
* // Log the path and name of each node in descendant tree starting with "parent"
* parent.forEach((node) => {
* console.log(node.path + "/" + node.name);
* });
*/
forEach(callback, thisArg) {
callback.call(thisArg, this);
const children = this._children;
const len = children.length;
for (let i = 0; i < len; ++i) {
children[i].forEach(callback, thisArg);
}
}
/**
* Check if node is descendant of another node.
*
* @param {GraphNode} node - Potential ancestor of node.
* @returns {boolean} If node is descendant of another node.
* @example
* if (roof.isDescendantOf(house)) {
* // roof is descendant of house entity
* }
*/
isDescendantOf(node) {
let parent = this._parent;
while (parent) {
if (parent === node) {
return true;
}
parent = parent._parent;
}
return false;
}
/**
* Check if node is ancestor for another node.
*
* @param {GraphNode} node - Potential descendant of node.
* @returns {boolean} If node is ancestor for another node.
* @example
* if (body.isAncestorOf(foot)) {
* // foot is within body's hierarchy
* }
*/
isAncestorOf(node) {
return node.isDescendantOf(this);
}
/**
* Get the world space rotation for the specified GraphNode in Euler angles. The angles are in
* degrees and in XYZ order.
*
* Important: The value returned by this function should be considered read-only. In order to
* set the world space rotation of the graph node, use {@link setEulerAngles}.
*
* @returns {Readonly<Vec3>} The world space rotation of the graph node in Euler angle form.
* @example
* const angles = this.entity.getEulerAngles();
* angles.y = 180; // rotate the entity around Y by 180 degrees
* this.entity.setEulerAngles(angles);
*/
getEulerAngles() {
this.getWorldTransform().getEulerAngles(this.eulerAngles);
return this.eulerAngles;
}
/**
* Get the local space rotation for the specified GraphNode in Euler angles. The angles are in
* degrees and in XYZ order.
*
* Important: The value returned by this function should be considered read-only. In order to
* set the local space rotation of the graph node, use {@link setLocalEulerAngles}.
*
* @returns {Readonly<Vec3>} The local space rotation of the graph node as Euler angles in XYZ order.
* @example
* const angles = this.entity.getLocalEulerAngles();
* angles.y = 180;
* this.entity.setLocalEulerAngles(angles);
*/
getLocalEulerAngles() {
this.localRotation.getEulerAngles(this.localEulerAngles);
return this.localEulerAngles;
}
/**
* Get the position in local space for the specified GraphNode. The position is returned as a
* {@link Vec3}. The returned vector should be considered read-only. To update the local
* position, use {@link setLocalPosition}.
*
* @returns {Readonly<Vec3>} The local space position of the graph node.
* @example
* const position = this.entity.getLocalPosition().clone();
* position.x += 1; // move the entity 1 unit along x.
* this.entity.setLocalPosition(position);
*/
getLocalPosition() {
return this.localPosition;
}
/**
* Get the rotation in local space for the specified GraphNode. The rotation is returned as a
* {@link Quat}. The returned quaternion should be considered read-only. To update the local
* rotation, use {@link setLocalRotation}.
*
* @returns {Readonly<Quat>} The local space rotation of the graph node as a quaternion.
* @example
* const rotation = this.entity.getLocalRotation();
*/
getLocalRotation() {
return this.localRotation;
}
/**
* Get the scale in local space for the specified GraphNode. The scale is returned as a
* {@link Vec3}. The returned vector should be considered read-only. To update the local scale,
* use {@link setLocalScale}.
*
* @returns {Readonly<Vec3>} The local space scale of the graph node.
* @example
* const scale = this.entity.getLocalScale().clone();
* scale.x = 100;
* this.entity.setLocalScale(scale);
*/
getLocalScale() {
return this.localScale;
}
/**
* Get the local transform matrix for this graph node. This matrix is the transform relative to
* the node's parent's world transformation matrix.
*
* @returns {Readonly<Mat4>} The node's local transformation matrix.
* @example
* const transform = this.entity.getLocalTransform();
*/
getLocalTransform() {
if (this._dirtyLocal) {
this.localTransform.setTRS(this.localPosition, this.localRotation, this.localScale);
this._dirtyLocal = false;
}
return this.localTransform;
}
/**
* Get the world space position for the specified GraphNode. The position is returned as a
* {@link Vec3}. The value returned by this function should be considered read-only. In order
* to set the world space position of the graph node, use {@link setPosition}.
*
* @returns {Readonly<Vec3>} The world space position of the graph node.
* @example
* const position = this.entity.getPosition().clone();
* position.x = 10;
* this.entity.setPosition(position);
*/
getPosition() {
this.getWorldTransform().getTranslation(this.position);
return this.position;
}
/**
* Get the world space rotation for the specified GraphNode. The rotation is returned as a
* {@link Quat}. The value returned by this function should be considered read-only. In order
* to set the world space rotation of the graph node, use {@link setRotation}.
*
* @returns {Readonly<Quat>} The world space rotation of the graph node as a quaternion.
* @example
* const rotation = this.entity.getRotation();
*/
getRotation() {
this.rotation.setFromMat4(this.getWorldTransform());
return this.rotation;
}
/**
* Get the world space scale for the specified GraphNode. The returned value will only be
* correct for graph nodes that have a non-skewed world transform (a skew can be introduced by
* the compounding of rotations and scales higher in the graph node hierarchy). The scale is
* returned as a {@link Vec3}. The value returned by this function should be considered
* read-only. Note that it is not possible to set the world space scale of a graph node
* directly.
*
* @returns {Readonly<Vec3>} The world space scale of the graph node.
* @example
* const scale = this.entity.getScale();
* @ignore
*/
getScale() {
if (!this._scale) {
this._scale = new Vec3();
}
return this.getWorldTransform().getScale(this._scale);
}
/**
* Get the world transformation matrix for this graph node.
*
* @returns {Readonly<Mat4>} The node's world transformation matrix.
* @example
* const transform = this.entity.getWorldTransform();
*/
getWorldTransform() {
if (!this._dirtyLocal && !this._dirtyWorld) {
return this.worldTransform;
}
if (this._parent) {
this._parent.getWorldTransform();
}
this._sync();
return this.worldTransform;
}
/**
* Gets the cached value of negative scale sign of the world transform.
*
* @returns {number} -1 if world transform has negative scale, 1 otherwise.
* @ignore
*/
get worldScaleSign() {
if (this._worldScaleSign === 0) {
this._worldScaleSign = this.getWorldTransform().scaleSign;
}
return this._worldScaleSign;
}
/**
* Remove graph node from current parent.
*/
remove() {
this._parent?.removeChild(this);
}
/**
* Remove graph node from current parent and add as child to new parent.
*
* @param {GraphNode} parent - New parent to attach graph node to.
* @param {number} [index] - The child index where the child node should be placed.
*/