forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.js
More file actions
1671 lines (1374 loc) · 61.8 KB
/
component.js
File metadata and controls
1671 lines (1374 loc) · 61.8 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 { Mat4 } from '../../../math/mat4.js';
import { Vec2 } from '../../../math/vec2.js';
import { Vec3 } from '../../../math/vec3.js';
import { Vec4 } from '../../../math/vec4.js';
import { FUNC_ALWAYS, FUNC_EQUAL, STENCILOP_INCREMENT, STENCILOP_REPLACE } from '../../../graphics/constants.js';
import { LAYERID_UI } from '../../../scene/constants.js';
import { BatchGroup } from '../../../scene/batching/batch-group.js';
import { StencilParameters } from '../../../scene/stencil-parameters.js';
import { Entity } from '../../entity.js';
import { Component } from '../component.js';
import { ELEMENTTYPE_GROUP, ELEMENTTYPE_IMAGE, ELEMENTTYPE_TEXT } from './constants.js';
import { ImageElement } from './image-element.js';
import { TextElement } from './text-element.js';
// #if _DEBUG
var _debugLogging = false;
// #endif
var position = new Vec3();
var invParentWtm = new Mat4();
var vecA = new Vec3();
var vecB = new Vec3();
var matA = new Mat4();
var matB = new Mat4();
var matC = new Mat4();
var matD = new Mat4();
/**
* @component
* @class
* @name ElementComponent
* @augments Component
* @classdesc ElementComponents are used to construct user interfaces. An ElementComponent's [type](#type)
* property can be configured in 3 main ways: as a text element, as an image element or as a group element.
* If the ElementComponent has a {@link ScreenComponent} ancestor in the hierarchy, it will be transformed
* with respect to the coordinate system of the screen. If there is no {@link ScreenComponent} ancestor,
* the ElementComponent will be transformed like any other entity.
*
* You should never need to use the ElementComponent constructor. To add an ElementComponent to a {@link Entity},
* use {@link Entity#addComponent}:
*
* ~~~javascript
* // Add an element component to an entity with the default options
* let entity = pc.Entity();
* entity.addComponent("element"); // This defaults to a 'group' element
* ~~~
*
* To create a simple text-based element:
*
* ~~~javascript
* entity.addComponent("element", {
* anchor: new pc.Vec4(0.5, 0.5, 0.5, 0.5), // centered anchor
* fontAsset: fontAsset,
* fontSize: 128,
* pivot: new pc.Vec2(0.5, 0.5), // centered pivot
* text: "Hello World!",
* type: pc.ELEMENTTYPE_TEXT
* });
* ~~~
*
* Once the ElementComponent is added to the entity, you can set and get any of its properties:
*
* ~~~javascript
* entity.element.color = pc.Color.RED; // Set the element's color to red
*
* console.log(entity.element.color); // Get the element's color and print it
* ~~~
*
* Relevant 'Engine-only' examples:
* * [Basic text rendering](http://playcanvas.github.io/#user-interface/text-basic.html)
* * [Rendering text outlines](http://playcanvas.github.io/#user-interface/text-outline.html)
* * [Adding drop shadows to text](http://playcanvas.github.io/#user-interface/text-drop-shadow.html)
* * [Coloring text with markup](http://playcanvas.github.io/#user-interface/text-markup.html)
* * [Wrapping text](http://playcanvas.github.io/#user-interface/text-wrap.html)
* * [Typewriter text](http://playcanvas.github.io/#user-interface/text-typewriter.html)
*
* @param {ElementComponentSystem} system - The ComponentSystem that created this Component.
* @param {Entity} entity - The Entity that this Component is attached to.
* @property {string} type The type of the ElementComponent. Can be:
*
* * {@link ELEMENTTYPE_GROUP}: The component can be used as a layout mechanism to create groups of ElementComponents e.g. panels.
* * {@link ELEMENTTYPE_IMAGE}: The component will render an image
* * {@link ELEMENTTYPE_TEXT}: The component will render text
*
* @property {Entity} screen The Entity with a {@link ScreenComponent} that this component belongs to. This is automatically set when the component is a child of a ScreenComponent.
* @property {number} drawOrder The draw order of the component. A higher value means that the component will be rendered on top of other components.
* @property {Vec4} anchor Specifies where the left, bottom, right and top edges of the component are anchored relative to its parent. Each value
* ranges from 0 to 1. E.g. a value of [0,0,0,0] means that the element will be anchored to the bottom left of its parent. A value of [1, 1, 1, 1] means
* it will be anchored to the top right. A split anchor is when the left-right or top-bottom pairs of the anchor are not equal. In that case the component will be resized to cover that entire area. E.g. a value of [0,0,1,1] will make the component resize exactly as its parent.
* @property {Vec2} pivot The position of the pivot of the component relative to its anchor. Each value ranges from 0 to 1 where [0,0] is the bottom left and [1,1] is the top right.
* @property {Vec4} margin The distance from the left, bottom, right and top edges of the anchor. For example if we are using a split anchor like [0,0,1,1] and the margin is [0,0,0,0] then the component will be the same width and height as its parent.
* @property {number} left The distance from the left edge of the anchor. Can be used in combination with a split anchor to make the component's left edge always be 'left' units away from the left.
* @property {number} right The distance from the right edge of the anchor. Can be used in combination with a split anchor to make the component's right edge always be 'right' units away from the right.
* @property {number} bottom The distance from the bottom edge of the anchor. Can be used in combination with a split anchor to make the component's top edge always be 'top' units away from the top.
* @property {number} top The distance from the top edge of the anchor. Can be used in combination with a split anchor to make the component's bottom edge always be 'bottom' units away from the bottom.
* @property {number} width The width of the element as set in the editor. Note that in some cases this may not reflect the true width at which the element is rendered, such as when the element is under the control of a {@link LayoutGroupComponent}. See `calculatedWidth` in order to ensure you are reading the true width at which the element will be rendered.
* @property {number} height The height of the element as set in the editor. Note that in some cases this may not reflect the true height at which the element is rendered, such as when the element is under the control of a {@link LayoutGroupComponent}. See `calculatedHeight` in order to ensure you are reading the true height at which the element will be rendered.
* @property {number} calculatedWidth The width at which the element will be rendered. In most cases this will be the same as `width`. However, in some cases the engine may calculate a different width for the element, such as when the element is under the control of a {@link LayoutGroupComponent}. In these scenarios, `calculatedWidth` may be smaller or larger than the width that was set in the editor.
* @property {number} calculatedHeight The height at which the element will be rendered. In most cases this will be the same as `height`. However, in some cases the engine may calculate a different height for the element, such as when the element is under the control of a {@link LayoutGroupComponent}. In these scenarios, `calculatedHeight` may be smaller or larger than the height that was set in the editor.
* @property {Vec3[]} screenCorners An array of 4 {@link Vec3}s that represent the bottom left, bottom right, top right and top left corners of the component relative to its parent {@link ScreenComponent}.
* @property {Vec3[]} worldCorners An array of 4 {@link Vec3}s that represent the bottom left, bottom right, top right and top left corners of the component in world space. Only works for 3D ElementComponents.
* @property {Vec2[]} canvasCorners An array of 4 {@link Vec2}s that represent the bottom left, bottom right, top right and top left corners of the component in canvas pixels. Only works for screen space ElementComponents.
* @property {boolean} useInput If true then the component will receive Mouse or Touch input events.
* @property {Color} color The color of the image for {@link ELEMENTTYPE_IMAGE} types or the color of the text for {@link ELEMENTTYPE_TEXT} types.
* @property {number} opacity The opacity of the image for {@link ELEMENTTYPE_IMAGE} types or the text for {@link ELEMENTTYPE_TEXT} types.
* @property {Color} outlineColor The text outline effect color and opacity. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} outlineThickness The width of the text outline effect. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {Color} shadowColor The text shadow effect color and opacity. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {Vec2} shadowOffset The text shadow effect shift amount from original text. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} textWidth The width of the text rendered by the component. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} textHeight The height of the text rendered by the component. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {boolean} autoWidth Automatically set the width of the component to be the same as the textWidth. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {boolean} autoHeight Automatically set the height of the component to be the same as the textHeight. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} fontAsset The id of the font asset used for rendering the text. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {Font} font The font used for rendering the text. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} fontSize The size of the font. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {boolean} autoFitWidth When true the font size and line height will scale so that the text fits inside the width of the Element. The font size will be scaled between minFontSize and maxFontSize. The value of autoFitWidth will be ignored if autoWidth is true.
* @property {boolean} autoFitHeight When true the font size and line height will scale so that the text fits inside the height of the Element. The font size will be scaled between minFontSize and maxFontSize. The value of autoFitHeight will be ignored if autoHeight is true.
* @property {number} minFontSize The minimum size that the font can scale to when autoFitWidth or autoFitHeight are true.
* @property {number} maxFontSize The maximum size that the font can scale to when autoFitWidth or autoFitHeight are true.
* @property {number} spacing The spacing between the letters of the text. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} lineHeight The height of each line of text. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {boolean} wrapLines Whether to automatically wrap lines based on the element width. Only works for {@link ELEMENTTYPE_TEXT} types, and when autoWidth is set to false.
* @property {number} maxLines The maximum number of lines that the Element can wrap to. Any leftover text will be appended to the last line. Set this to null to allow unlimited lines.
* @property {Vec2} alignment The horizontal and vertical alignment of the text. Values range from 0 to 1 where [0,0] is the bottom left and [1,1] is the top right. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {string} text The text to render. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {string} key The localization key to use to get the localized text from {@link Application#i18n}. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} textureAsset The id of the texture asset to render. Only works for {@link ELEMENTTYPE_IMAGE} types.
* @property {Texture} texture The texture to render. Only works for {@link ELEMENTTYPE_IMAGE} types.
* @property {number} spriteAsset The id of the sprite asset to render. Only works for {@link ELEMENTTYPE_IMAGE} types which can render either a texture or a sprite.
* @property {Sprite} sprite The sprite to render. Only works for {@link ELEMENTTYPE_IMAGE} types which can render either a texture or a sprite.
* @property {number} spriteFrame The frame of the sprite to render. Only works for {@link ELEMENTTYPE_IMAGE} types who have a sprite assigned.
* @property {number} pixelsPerUnit The number of pixels that map to one PlayCanvas unit. Only works for {@link ELEMENTTYPE_IMAGE} types who have a sliced sprite assigned.
* @property {number} materialAsset The id of the material asset to use when rendering an image. Only works for {@link ELEMENTTYPE_IMAGE} types.
* @property {Material} material The material to use when rendering an image. Only works for {@link ELEMENTTYPE_IMAGE} types.
* @property {Vec4} rect Specifies which region of the texture to use in order to render an image. Values range from 0 to 1 and indicate u, v, width, height. Only works for {@link ELEMENTTYPE_IMAGE} types.
* @property {boolean} rtlReorder Reorder the text for RTL languages using a function registered by `app.systems.element.registerUnicodeConverter`.
* @property {boolean} unicodeConverter Convert unicode characters using a function registered by `app.systems.element.registerUnicodeConverter`.
* @property {number} batchGroupId Assign element to a specific batch group (see {@link BatchGroup}). Default value is -1 (no group).
* @property {number[]} layers An array of layer IDs ({@link Layer#id}) to which this element should belong.
* Don't push/pop/splice or modify this array, if you want to change it - set a new one instead.
* @property {boolean} enableMarkup Flag for enabling markup processing. Only works for {@link ELEMENTTYPE_TEXT} types. The only supported tag is `[color]` with a hex color value. E.g `[color="#ff0000"]red text[/color]`
* @property {number} rangeStart Index of the first character to render. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {number} rangeEnd Index of the last character to render. Only works for {@link ELEMENTTYPE_TEXT} types.
* @property {boolean} mask Switch Image Element into a mask. Masks do not render into the scene, but instead limit child elements to only be rendered where this element is rendered.
*/
class ElementComponent extends Component {
constructor(system, entity) {
super(system, entity);
// set to true by the ElementComponentSystem while
// the component is being initialized
this._beingInitialized = false;
this._anchor = new Vec4();
this._localAnchor = new Vec4();
this._pivot = new Vec2();
this._width = this._calculatedWidth = 32;
this._height = this._calculatedHeight = 32;
this._margin = new Vec4(0, 0, -32, -32);
// the model transform used to render
this._modelTransform = new Mat4();
this._screenToWorld = new Mat4();
// transform that updates local position according to anchor values
this._anchorTransform = new Mat4();
this._anchorDirty = true;
// transforms to calculate screen coordinates
this._parentWorldTransform = new Mat4();
this._screenTransform = new Mat4();
// the corners of the element relative to its screen component.
// Order is bottom left, bottom right, top right, top left
this._screenCorners = [new Vec3(), new Vec3(), new Vec3(), new Vec3()];
// canvas-space corners of the element.
// Order is bottom left, bottom right, top right, top left
this._canvasCorners = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
// the world-space corners of the element
// Order is bottom left, bottom right, top right, top left
this._worldCorners = [new Vec3(), new Vec3(), new Vec3(), new Vec3()];
this._cornersDirty = true;
this._canvasCornersDirty = true;
this._worldCornersDirty = true;
this.entity.on('insert', this._onInsert, this);
this._patch();
this.screen = null;
this._type = ELEMENTTYPE_GROUP;
// element types
this._image = null;
this._text = null;
this._group = null;
this._drawOrder = 0;
// input related
this._useInput = false;
this._layers = [LAYERID_UI]; // assign to the default UI layer
this._addedModels = []; // store models that have been added to layer so we can re-add when layer is changed
this._batchGroupId = -1;
// #if _DEBUG
this._batchGroup = null;
// #endif
//
this._offsetReadAt = 0;
this._maskOffset = 0.5;
this._maskedBy = null; // the entity that is masking this element
}
_patch() {
this.entity._sync = this._sync;
this.entity.setPosition = this._setPosition;
this.entity.setLocalPosition = this._setLocalPosition;
}
_unpatch() {
this.entity._sync = Entity.prototype._sync;
this.entity.setPosition = Entity.prototype.setPosition;
this.entity.setLocalPosition = Entity.prototype.setLocalPosition;
}
_setPosition(x, y, z) {
if (!this.element.screen)
return Entity.prototype.setPosition.call(this, x, y, z);
if (x instanceof Vec3) {
position.copy(x);
} else {
position.set(x, y, z);
}
this.getWorldTransform(); // ensure hierarchy is up to date
invParentWtm.copy(this.element._screenToWorld).invert();
invParentWtm.transformPoint(position, this.localPosition);
if (!this._dirtyLocal)
this._dirtifyLocal();
}
_setLocalPosition(x, y, z) {
if (x instanceof Vec3) {
this.localPosition.copy(x);
} else {
this.localPosition.set(x, y, z);
}
// update margin
var element = this.element;
var p = this.localPosition;
var pvt = element._pivot;
element._margin.x = p.x - element._calculatedWidth * pvt.x;
element._margin.z = (element._localAnchor.z - element._localAnchor.x) - element._calculatedWidth - element._margin.x;
element._margin.y = p.y - element._calculatedHeight * pvt.y;
element._margin.w = (element._localAnchor.w - element._localAnchor.y) - element._calculatedHeight - element._margin.y;
if (!this._dirtyLocal)
this._dirtifyLocal();
}
// this method overwrites GraphNode#sync and so operates in scope of the Entity.
_sync() {
var element = this.element;
var screen = element.screen;
if (screen) {
if (element._anchorDirty) {
var resx = 0;
var resy = 0;
var px = 0;
var py = 1;
if (this._parent && this._parent.element) {
// use parent rect
resx = this._parent.element.calculatedWidth;
resy = this._parent.element.calculatedHeight;
px = this._parent.element.pivot.x;
py = this._parent.element.pivot.y;
} else {
// use screen rect
var resolution = screen.screen.resolution;
resx = resolution.x / screen.screen.scale;
resy = resolution.y / screen.screen.scale;
}
element._anchorTransform.setTranslate((resx * (element.anchor.x - px)), -(resy * (py - element.anchor.y)), 0);
element._anchorDirty = false;
element._calculateLocalAnchors();
}
// if element size is dirty
// recalculate its size
// WARNING: Order is important as calculateSize resets dirtyLocal
// so this needs to run before resetting dirtyLocal to false below
if (element._sizeDirty) {
element._calculateSize(false, false);
}
}
if (this._dirtyLocal) {
this.localTransform.setTRS(this.localPosition, this.localRotation, this.localScale);
// update margin
var p = this.localPosition;
var pvt = element._pivot;
element._margin.x = p.x - element._calculatedWidth * pvt.x;
element._margin.z = (element._localAnchor.z - element._localAnchor.x) - element._calculatedWidth - element._margin.x;
element._margin.y = p.y - element._calculatedHeight * pvt.y;
element._margin.w = (element._localAnchor.w - element._localAnchor.y) - element._calculatedHeight - element._margin.y;
this._dirtyLocal = false;
}
if (!screen) {
if (this._dirtyWorld) {
element._cornersDirty = true;
element._canvasCornersDirty = true;
element._worldCornersDirty = true;
}
return Entity.prototype._sync.call(this);
}
if (this._dirtyWorld) {
if (this._parent === null) {
this.worldTransform.copy(this.localTransform);
} else {
// transform element hierarchy
if (this._parent.element) {
element._screenToWorld.mul2(this._parent.element._modelTransform, element._anchorTransform);
} else {
element._screenToWorld.copy(element._anchorTransform);
}
element._modelTransform.mul2(element._screenToWorld, this.localTransform);
if (screen) {
element._screenToWorld.mul2(screen.screen._screenMatrix, element._screenToWorld);
if (!screen.screen.screenSpace) {
element._screenToWorld.mul2(screen.worldTransform, element._screenToWorld);
}
this.worldTransform.mul2(element._screenToWorld, this.localTransform);
// update parent world transform
var parentWorldTransform = element._parentWorldTransform;
parentWorldTransform.setIdentity();
var parent = this._parent;
if (parent && parent.element && parent !== screen) {
matA.setTRS(Vec3.ZERO, parent.getLocalRotation(), parent.getLocalScale());
parentWorldTransform.mul2(parent.element._parentWorldTransform, matA);
}
// update element transform
// rotate and scale around pivot
var depthOffset = vecA;
depthOffset.set(0, 0, this.localPosition.z);
var pivotOffset = vecB;
pivotOffset.set(element._absLeft + element._pivot.x * element.calculatedWidth, element._absBottom + element._pivot.y * element.calculatedHeight, 0);
matA.setTranslate(-pivotOffset.x, -pivotOffset.y, -pivotOffset.z);
matB.setTRS(depthOffset, this.getLocalRotation(), this.getLocalScale());
matC.setTranslate(pivotOffset.x, pivotOffset.y, pivotOffset.z);
element._screenTransform.mul2(element._parentWorldTransform, matC).mul(matB).mul(matA);
element._cornersDirty = true;
element._canvasCornersDirty = true;
element._worldCornersDirty = true;
} else {
this.worldTransform.copy(element._modelTransform);
}
}
this._dirtyWorld = false;
}
}
_onInsert(parent) {
// when the entity is reparented find a possible new screen and mask
var result = this._parseUpToScreen();
this.entity._dirtifyWorld();
this._updateScreen(result.screen);
this._dirtifyMask();
}
_dirtifyMask() {
var current = this.entity;
while (current) {
// search up the hierarchy until we find an entity which has:
// - no parent
// - screen component on parent
var next = current.parent;
if ((next === null || next.screen) && current.element) {
if (!this.system._prerender || !this.system._prerender.length) {
this.system._prerender = [];
this.system.app.once('prerender', this._onPrerender, this);
// #if _DEBUG
if (_debugLogging) console.log('register prerender');
// #endif
}
var i = this.system._prerender.indexOf(this.entity);
if (i >= 0) {
this.system._prerender.splice(i, 1);
}
var j = this.system._prerender.indexOf(current);
if (j < 0) {
this.system._prerender.push(current);
}
// #if _DEBUG
if (_debugLogging) console.log('set prerender root to: ' + current.name);
// #endif
}
current = next;
}
}
_onPrerender() {
for (var i = 0; i < this.system._prerender.length; i++) {
var mask = this.system._prerender[i];
// #if _DEBUG
if (_debugLogging) console.log('prerender from: ' + mask.name);
// #endif
// prevent call if element has been removed since being added
if (mask.element) {
var depth = 1;
mask.element.syncMask(depth);
}
}
this.system._prerender.length = 0;
}
_bindScreen(screen) {
// Bind the Element to the Screen. We used to subscribe to Screen events here. However,
// that was very slow when there are thousands of Elements. When the time comes to unbind
// the Element from the Screen, finding the event callbacks to remove takes a considerable
// amount of time. So instead, the Screen stores the Element component and calls its
// functions directly.
screen._bindElement(this);
}
_unbindScreen(screen) {
screen._unbindElement(this);
}
_updateScreen(screen) {
if (this.screen && this.screen !== screen) {
this._unbindScreen(this.screen.screen);
}
var previousScreen = this.screen;
this.screen = screen;
if (this.screen) {
this._bindScreen(this.screen.screen);
}
this._calculateSize(this._hasSplitAnchorsX, this._hasSplitAnchorsY);
this.fire('set:screen', this.screen, previousScreen);
this._anchorDirty = true;
// update all child screens
var children = this.entity.children;
for (var i = 0, l = children.length; i < l; i++) {
if (children[i].element) children[i].element._updateScreen(screen);
}
// calculate draw order
if (this.screen) this.screen.screen.syncDrawOrder();
}
syncMask(depth) {
var result = this._parseUpToScreen();
this._updateMask(result.mask, depth);
}
// set the maskedby property to the entity that is masking this element
// - set the stencil buffer to check the mask value
// so as to only render inside the mask
// Note: if this entity is itself a mask the stencil params
// will be updated in updateMask to include masking
_setMaskedBy(mask) {
var renderableElement = this._image || this._text;
if (mask) {
var ref = mask.element._image._maskRef;
// #if _DEBUG
if (_debugLogging) console.log("masking: " + this.entity.name + " with " + ref);
// #endif
var sp = new StencilParameters({
ref: ref,
func: FUNC_EQUAL
});
// if this is image or text, set the stencil parameters
if (renderableElement && renderableElement._setStencil) {
renderableElement._setStencil(sp);
}
this._maskedBy = mask;
} else {
// #if _DEBUG
if (_debugLogging) console.log("no masking on: " + this.entity.name);
// #endif
// remove stencil params if this is image or text
if (renderableElement && renderableElement._setStencil) {
renderableElement._setStencil(null);
}
this._maskedBy = null;
}
}
// recursively update entity's stencil params
// to render the correct value into the stencil buffer
_updateMask(currentMask, depth) {
var i, l, sp, children;
if (currentMask) {
this._setMaskedBy(currentMask);
// this element is also masking others
if (this.mask) {
var ref = currentMask.element._image._maskRef;
sp = new StencilParameters({
ref: ref,
func: FUNC_EQUAL,
zpass: STENCILOP_INCREMENT
});
this._image._setStencil(sp);
this._image._maskRef = depth;
// increment counter to count mask depth
depth++;
// #if _DEBUG
if (_debugLogging) {
console.log("masking from: " + this.entity.name + " with " + (sp.ref + 1));
console.log("depth++ to: ", depth);
}
// #endif
currentMask = this.entity;
}
// recurse through all children
children = this.entity.children;
for (i = 0, l = children.length; i < l; i++) {
if (children[i].element) {
children[i].element._updateMask(currentMask, depth);
}
}
// if mask counter was increased, decrement it as we come back up the hierarchy
if (this.mask) depth--;
} else {
// clearing mask
this._setMaskedBy(null);
if (this.mask) {
sp = new StencilParameters({
ref: depth,
func: FUNC_ALWAYS,
zpass: STENCILOP_REPLACE
});
this._image._setStencil(sp);
this._image._maskRef = depth;
// increment mask counter to count depth of masks
depth++;
// #if _DEBUG
if (_debugLogging) {
console.log("masking from: " + this.entity.name + " with " + sp.ref);
console.log("depth++ to: ", depth);
}
// #endif
currentMask = this.entity;
}
// recurse through all children
children = this.entity.children;
for (i = 0, l = children.length; i < l; i++) {
if (children[i].element) {
children[i].element._updateMask(currentMask, depth);
}
}
// decrement mask counter as we come back up the hierarchy
if (this.mask) depth--;
}
}
// search up the parent hierarchy until we reach a screen
// this screen is the parent screen
// also searches for masked elements to get the relevant mask
_parseUpToScreen() {
var result = {
screen: null,
mask: null
};
var parent = this.entity._parent;
while (parent && !parent.screen) {
if (parent.element && parent.element.mask) {
// mask entity
if (!result.mask) result.mask = parent;
}
parent = parent.parent;
}
if (parent && parent.screen) result.screen = parent;
return result;
}
_onScreenResize(res) {
this._anchorDirty = true;
this._cornersDirty = true;
this._worldCornersDirty = true;
this._calculateSize(this._hasSplitAnchorsX, this._hasSplitAnchorsY);
this.fire('screen:set:resolution', res);
}
_onScreenSpaceChange() {
this.fire('screen:set:screenspace', this.screen.screen.screenSpace);
}
_onScreenRemove() {
if (this.screen) {
if (this.screen._destroying) {
// If the screen entity is being destroyed, we don't call
// _updateScreen() as an optimization but we should still
// set it to null to clean up dangling references
this.screen = null;
} else {
this._updateScreen(null);
}
}
}
// store pixel positions of anchor relative to current parent resolution
_calculateLocalAnchors() {
var resx = 1000;
var resy = 1000;
var parent = this.entity._parent;
if (parent && parent.element) {
resx = parent.element.calculatedWidth;
resy = parent.element.calculatedHeight;
} else if (this.screen) {
var res = this.screen.screen.resolution;
var scale = this.screen.screen.scale;
resx = res.x / scale;
resy = res.y / scale;
}
this._localAnchor.set(
this._anchor.x * resx,
this._anchor.y * resy,
this._anchor.z * resx,
this._anchor.w * resy
);
}
// internal - apply offset x,y to local position and find point in world space
getOffsetPosition(x, y) {
var p = this.entity.getLocalPosition().clone();
p.x += x;
p.y += y;
this._screenToWorld.transformPoint(p, p);
return p;
}
onLayersChanged(oldComp, newComp) {
this.addModelToLayers(this._image ? this._image._model : this._text._model);
oldComp.off("add", this.onLayerAdded, this);
oldComp.off("remove", this.onLayerRemoved, this);
newComp.on("add", this.onLayerAdded, this);
newComp.on("remove", this.onLayerRemoved, this);
}
onLayerAdded(layer) {
var index = this.layers.indexOf(layer.id);
if (index < 0) return;
if (this._image) {
layer.addMeshInstances(this._image._model.meshInstances);
} else if (this._text) {
layer.addMeshInstances(this._text._model.meshInstances);
}
}
onLayerRemoved(layer) {
var index = this.layers.indexOf(layer.id);
if (index < 0) return;
if (this._image) {
layer.removeMeshInstances(this._image._model.meshInstances);
} else if (this._text) {
layer.removeMeshInstances(this._text._model.meshInstances);
}
}
onEnable() {
if (this._image) this._image.onEnable();
if (this._text) this._text.onEnable();
if (this._group) this._group.onEnable();
if (this.useInput && this.system.app.elementInput) {
this.system.app.elementInput.addElement(this);
}
this.system.app.scene.on("set:layers", this.onLayersChanged, this);
if (this.system.app.scene.layers) {
this.system.app.scene.layers.on("add", this.onLayerAdded, this);
this.system.app.scene.layers.on("remove", this.onLayerRemoved, this);
}
if (this._batchGroupId >= 0) {
this.system.app.batcher.insert(BatchGroup.ELEMENT, this.batchGroupId, this.entity);
}
this.fire("enableelement");
}
onDisable() {
this.system.app.scene.off("set:layers", this.onLayersChanged, this);
if (this.system.app.scene.layers) {
this.system.app.scene.layers.off("add", this.onLayerAdded, this);
this.system.app.scene.layers.off("remove", this.onLayerRemoved, this);
}
if (this._image) this._image.onDisable();
if (this._text) this._text.onDisable();
if (this._group) this._group.onDisable();
if (this.system.app.elementInput && this.useInput) {
this.system.app.elementInput.removeElement(this);
}
if (this._batchGroupId >= 0) {
this.system.app.batcher.remove(BatchGroup.ELEMENT, this.batchGroupId, this.entity);
}
this.fire("disableelement");
}
onRemove() {
this.entity.off('insert', this._onInsert, this);
this._unpatch();
if (this._image) this._image.destroy();
if (this._text) this._text.destroy();
if (this.system.app.elementInput && this.useInput) {
this.system.app.elementInput.removeElement(this);
}
// if there is a screen, update draw-order
if (this.screen && this.screen.screen) {
this._unbindScreen(this.screen.screen);
this.screen.screen.syncDrawOrder();
}
this.off();
}
// recalculates
// localAnchor, width, height, (local position is updated if anchors are split)
// assumes these properties are up to date
// _margin
_calculateSize(propagateCalculatedWidth, propagateCalculatedHeight) {
// can't calculate if local anchors are wrong
if (!this.entity._parent && !this.screen) return;
this._calculateLocalAnchors();
var newWidth = this._absRight - this._absLeft;
var newHeight = this._absTop - this._absBottom;
if (propagateCalculatedWidth) {
this._setWidth(newWidth);
} else {
this._setCalculatedWidth(newWidth, false);
}
if (propagateCalculatedHeight) {
this._setHeight(newHeight);
} else {
this._setCalculatedHeight(newHeight, false);
}
var p = this.entity.getLocalPosition();
p.x = this._margin.x + this._calculatedWidth * this._pivot.x;
p.y = this._margin.y + this._calculatedHeight * this._pivot.y;
this.entity.setLocalPosition(p);
this._sizeDirty = false;
}
// internal set width without updating margin
_setWidth(w) {
this._width = w;
this._setCalculatedWidth(w, false);
this.fire('set:width', this._width);
}
// internal set height without updating margin
_setHeight(h) {
this._height = h;
this._setCalculatedHeight(h, false);
this.fire('set:height', this._height);
}
_setCalculatedWidth(value, updateMargins) {
if (Math.abs(value - this._calculatedWidth) <= 1e-4)
return;
this._calculatedWidth = value;
this.entity._dirtifyLocal();
if (updateMargins) {
var p = this.entity.getLocalPosition();
var pvt = this._pivot;
this._margin.x = p.x - this._calculatedWidth * pvt.x;
this._margin.z = (this._localAnchor.z - this._localAnchor.x) - this._calculatedWidth - this._margin.x;
}
this._flagChildrenAsDirty();
this.fire('set:calculatedWidth', this._calculatedWidth);
this.fire('resize', this._calculatedWidth, this._calculatedHeight);
}
_setCalculatedHeight(value, updateMargins) {
if (Math.abs(value - this._calculatedHeight) <= 1e-4)
return;
this._calculatedHeight = value;
this.entity._dirtifyLocal();
if (updateMargins) {
var p = this.entity.getLocalPosition();
var pvt = this._pivot;
this._margin.y = p.y - this._calculatedHeight * pvt.y;
this._margin.w = (this._localAnchor.w - this._localAnchor.y) - this._calculatedHeight - this._margin.y;
}
this._flagChildrenAsDirty();
this.fire('set:calculatedHeight', this._calculatedHeight);
this.fire('resize', this._calculatedWidth, this._calculatedHeight);
}
_flagChildrenAsDirty() {
var i, l;
var c = this.entity._children;
for (i = 0, l = c.length; i < l; i++) {
if (c[i].element) {
c[i].element._anchorDirty = true;
c[i].element._sizeDirty = true;
}
}
}
addModelToLayers(model) {
var layer;
this._addedModels.push(model);
for (var i = 0; i < this.layers.length; i++) {
layer = this.system.app.scene.layers.getLayerById(this.layers[i]);
if (!layer) continue;
layer.addMeshInstances(model.meshInstances);
}
}
removeModelFromLayers(model) {
var layer;
var idx = this._addedModels.indexOf(model);
if (idx >= 0) {
this._addedModels.splice(idx, 1);
}
for (var i = 0; i < this.layers.length; i++) {
layer = this.system.app.scene.layers.getLayerById(this.layers[i]);
if (!layer) continue;
layer.removeMeshInstances(model.meshInstances);
}
}
getMaskOffset() {
// reset offset on new frame
// we always count offset down from 0.5
var frame = this.system.app.frame;
if (this._offsetReadAt !== frame) {
this._maskOffset = 0.5;
this._offsetReadAt = frame;
}
var mo = this._maskOffset;
this._maskOffset -= 0.001;
return mo;
}
isVisibleForCamera(camera) {
var clipL, clipR, clipT, clipB;
if (this.maskedBy) {
var corners = this.maskedBy.element.screenCorners;
clipL = Math.min(Math.min(corners[0].x, corners[1].x), Math.min(corners[2].x, corners[3].x));
clipR = Math.max(Math.max(corners[0].x, corners[1].x), Math.max(corners[2].x, corners[3].x));
clipB = Math.min(Math.min(corners[0].y, corners[1].y), Math.min(corners[2].y, corners[3].y));
clipT = Math.max(Math.max(corners[0].y, corners[1].y), Math.max(corners[2].y, corners[3].y));
} else {
var sw = this.system.app.graphicsDevice.width;
var sh = this.system.app.graphicsDevice.height;
var cameraWidth = camera._rect.z * sw;
var cameraHeight = camera._rect.w * sh;
clipL = camera._rect.x * sw;
clipR = clipL + cameraWidth;
clipT = (1 - camera._rect.y) * sh;
clipB = clipT - cameraHeight;
}
var hitCorners = this.screenCorners;
var left = Math.min(Math.min(hitCorners[0].x, hitCorners[1].x), Math.min(hitCorners[2].x, hitCorners[3].x));
var right = Math.max(Math.max(hitCorners[0].x, hitCorners[1].x), Math.max(hitCorners[2].x, hitCorners[3].x));
var bottom = Math.min(Math.min(hitCorners[0].y, hitCorners[1].y), Math.min(hitCorners[2].y, hitCorners[3].y));
var top = Math.max(Math.max(hitCorners[0].y, hitCorners[1].y), Math.max(hitCorners[2].y, hitCorners[3].y));
if (right < clipL ||
left > clipR ||
bottom > clipT ||
top < clipB) {
return false;
}
return true;
}
_isScreenSpace() {
if (this.screen && this.screen.screen) {
return this.screen.screen.screenSpace;
}
return false;
}
_isScreenCulled() {
if (this.screen && this.screen.screen) {
return this.screen.screen.cull;
}
return false;
}
}
Object.defineProperty(ElementComponent.prototype, "type", {