-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathCoreNode.ts
More file actions
2282 lines (2008 loc) · 61.1 KB
/
CoreNode.ts
File metadata and controls
2282 lines (2008 loc) · 61.1 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
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2023 Comcast Cable Communications Management, LLC.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
assertTruthy,
getNewId,
mergeColorAlphaPremultiplied,
} from '../utils.js';
import type { TextureOptions } from './CoreTextureManager.js';
import type { CoreRenderer } from './renderers/CoreRenderer.js';
import type { Stage } from './Stage.js';
import type {
Texture,
TextureFailedEventHandler,
TextureFreedEventHandler,
TextureLoadedEventHandler,
} from './textures/Texture.js';
import type {
Dimensions,
NodeTextureFailedPayload,
NodeTextureFreedPayload,
NodeTextureLoadedPayload,
} from '../common/CommonTypes.js';
import { EventEmitter } from '../common/EventEmitter.js';
import {
copyRect,
intersectRect,
type Bound,
type RectWithValid,
createBound,
boundInsideBound,
boundLargeThanBound,
createPreloadBounds,
} from './lib/utils.js';
import { Matrix3d } from './lib/Matrix3d.js';
import { RenderCoords } from './lib/RenderCoords.js';
import type { AnimationSettings } from './animations/CoreAnimation.js';
import type { IAnimationController } from '../common/IAnimationController.js';
import { CoreAnimation } from './animations/CoreAnimation.js';
import { CoreAnimationController } from './animations/CoreAnimationController.js';
import type { BaseShaderController } from '../main-api/ShaderController.js';
export enum CoreNodeRenderState {
Init = 0,
OutOfBounds = 2,
InBounds = 4,
InViewport = 8,
}
const CoreNodeRenderStateMap: Map<CoreNodeRenderState, string> = new Map();
CoreNodeRenderStateMap.set(CoreNodeRenderState.Init, 'init');
CoreNodeRenderStateMap.set(CoreNodeRenderState.OutOfBounds, 'outOfBounds');
CoreNodeRenderStateMap.set(CoreNodeRenderState.InBounds, 'inBounds');
CoreNodeRenderStateMap.set(CoreNodeRenderState.InViewport, 'inViewport');
export enum UpdateType {
/**
* Child updates
*/
Children = 1,
/**
* Scale/Rotate transform update
*
* @remarks
* CoreNode Properties Updated:
* - `scaleRotateTransform`
*/
ScaleRotate = 2,
/**
* Translate transform update (x/y/width/height/pivot/mount)
*
* @remarks
* CoreNode Properties Updated:
* - `localTransform`
*/
Local = 4,
/**
* Global Transform update
*
* @remarks
* CoreNode Properties Updated:
* - `globalTransform`
* - `renderCoords`
* - `renderBound`
*/
Global = 8,
/**
* Clipping rect update
*
* @remarks
* CoreNode Properties Updated:
* - `clippingRect`
*/
Clipping = 16,
/**
* Calculated ZIndex update
*
* @remarks
* CoreNode Properties Updated:
* - `calcZIndex`
*/
CalculatedZIndex = 32,
/**
* Z-Index Sorted Children update
*
* @remarks
* CoreNode Properties Updated:
* - `children` (sorts children by their `calcZIndex`)
*/
ZIndexSortedChildren = 64,
/**
* Premultiplied Colors update
*
* @remarks
* CoreNode Properties Updated:
* - `premultipliedColorTl`
* - `premultipliedColorTr`
* - `premultipliedColorBl`
* - `premultipliedColorBr`
*/
PremultipliedColors = 128,
/**
* World Alpha update
*
* @remarks
* CoreNode Properties Updated:
* - `worldAlpha` = `parent.worldAlpha` * `alpha`
*/
WorldAlpha = 256,
/**
* Render State update
*
* @remarks
* CoreNode Properties Updated:
* - `renderState`
*/
RenderState = 512,
/**
* Is Renderable update
*
* @remarks
* CoreNode Properties Updated:
* - `isRenderable`
*/
IsRenderable = 1024,
/**
* Render Texture update
*/
RenderTexture = 2048,
/**
* Track if parent has render texture
*/
ParentRenderTexture = 4096,
/**
* Render Bounds update
*/
RenderBounds = 8192,
/**
* None
*/
None = 0,
/**
* All
*/
All = 16383,
}
/**
* A custom data map which can be stored on an CoreNode
*
* @remarks
* This is a map of key-value pairs that can be stored on an INode. It is used
* to store custom data that can be used by the application.
* The data stored can only be of type string, number or boolean.
*/
export type CustomDataMap = {
[key: string]: string | number | boolean | undefined;
};
/**
* Writable properties of a Node.
*/
export interface CoreNodeProps {
/**
* The x coordinate of the Node's Mount Point.
*
* @remarks
* See {@link mountX} and {@link mountY} for more information about setting
* the Mount Point.
*
* @default `0`
*/
x: number;
/**
* The y coordinate of the Node's Mount Point.
*
* @remarks
* See {@link mountX} and {@link mountY} for more information about setting
* the Mount Point.
*
* @default `0`
*/
y: number;
/**
* The width of the Node.
*
* @default `0`
*/
width: number;
/**
* The height of the Node.
*
* @default `0`
*/
height: number;
/**
* The alpha opacity of the Node.
*
* @remarks
* The alpha value is a number between 0 and 1, where 0 is fully transparent
* and 1 is fully opaque.
*
* @default `1`
*/
alpha: number;
/**
* Autosize mode
*
* @remarks
* When enabled, when a texture is loaded into the Node, the Node will
* automatically resize to the dimensions of the texture.
*
* Text Nodes are always autosized based on their text content regardless
* of this mode setting.
*
* @default `false`
*/
autosize: boolean;
/**
* Margin around the Node's bounds for preloading
*
* @default `null`
*/
boundsMargin: number | [number, number, number, number] | null;
/**
* Clipping Mode
*
* @remarks
* Enable Clipping Mode when you want to prevent the drawing of a Node and
* its descendants from overflowing outside of the Node's x/y/width/height
* bounds.
*
* For WebGL, clipping is implemented using the high-performance WebGL
* operation scissor. As a consequence, clipping does not work for
* non-rectangular areas. So, if the element is rotated
* (by itself or by any of its ancestors), clipping will not work as intended.
*
* TODO: Add support for non-rectangular clipping either automatically or
* via Render-To-Texture.
*
* @default `false`
*/
clipping: boolean;
/**
* The color of the Node.
*
* @remarks
* The color value is a number in the format 0xRRGGBBAA, where RR is the red
* component, GG is the green component, BB is the blue component, and AA is
* the alpha component.
*
* Gradient colors may be set by setting the different color sub-properties:
* {@link colorTop}, {@link colorBottom}, {@link colorLeft}, {@link colorRight},
* {@link colorTl}, {@link colorTr}, {@link colorBr}, {@link colorBl} accordingly.
*
* @default `0xffffffff` (opaque white)
*/
color: number;
/**
* The color of the top edge of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorTop: number;
/**
* The color of the bottom edge of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorBottom: number;
/**
* The color of the left edge of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorLeft: number;
/**
* The color of the right edge of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorRight: number;
/**
* The color of the top-left corner of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorTl: number;
/**
* The color of the top-right corner of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorTr: number;
/**
* The color of the bottom-right corner of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorBr: number;
/**
* The color of the bottom-left corner of the Node for gradient rendering.
*
* @remarks
* See {@link color} for more information about color values and gradient
* rendering.
*/
colorBl: number;
/**
* The Node's parent Node.
*
* @remarks
* The value `null` indicates that the Node has no parent. This may either be
* because the Node is the root Node of the scene graph, or because the Node
* has been removed from the scene graph.
*
* In order to make sure that a Node can be rendered on the screen, it must
* be added to the scene graph by setting it's parent property to a Node that
* is already in the scene graph such as the root Node.
*
* @default `null`
*/
parent: CoreNode | null;
/**
* The Node's z-index.
*
* @remarks
* TBD
*/
zIndex: number;
/**
* The Node's Texture.
*
* @remarks
* The `texture` defines a rasterized image that is contained within the
* {@link width} and {@link height} dimensions of the Node. If null, the
* Node will use an opaque white {@link ColorTexture} when being drawn, which
* essentially enables colors (including gradients) to be drawn.
*
* If set, by default, the texture will be drawn, as is, stretched to the
* dimensions of the Node. This behavior can be modified by setting the TBD
* and TBD properties.
*
* To create a Texture in order to set it on this property, call
* {@link RendererMain.createTexture}.
*
* If the {@link src} is set on a Node, the Node will use the
* {@link ImageTexture} by default and the Node will simply load the image at
* the specified URL.
*
* Note: If this is a Text Node, the Texture will be managed by the Node's
* {@link TextRenderer} and should not be set explicitly.
*/
texture: Texture | null;
/**
* Whether to prevent the node from being cleaned up
* @default false
*/
preventCleanup: boolean;
/**
* Options to associate with the Node's Texture
*/
textureOptions: TextureOptions;
/**
* The Node's shader
*
* @remarks
* The `shader` defines a {@link Shader} used to draw the Node. By default,
* the Default Shader is used which simply draws the defined {@link texture}
* or {@link color}(s) within the Node without any special effects.
*
* To create a Shader in order to set it on this property, call
* {@link RendererMain.createShader}.
*
* Note: If this is a Text Node, the Shader will be managed by the Node's
* {@link TextRenderer} and should not be set explicitly.
*/
shader: BaseShaderController;
/**
* Image URL
*
* @remarks
* When set, the Node's {@link texture} is automatically set to an
* {@link ImageTexture} using the source image URL provided (with all other
* settings being defaults)
*/
src: string | null;
zIndexLocked: number;
/**
* Scale to render the Node at
*
* @remarks
* The scale value multiplies the provided {@link width} and {@link height}
* of the Node around the Node's Pivot Point (defined by the {@link pivot}
* props).
*
* Behind the scenes, setting this property sets both the {@link scaleX} and
* {@link scaleY} props to the same value.
*
* NOTE: When the scaleX and scaleY props are explicitly set to different values,
* this property returns `null`. Setting `null` on this property will have no
* effect.
*
* @default 1.0
*/
scale: number | null;
/**
* Scale to render the Node at (X-Axis)
*
* @remarks
* The scaleX value multiplies the provided {@link width} of the Node around
* the Node's Pivot Point (defined by the {@link pivot} props).
*
* @default 1.0
*/
scaleX: number;
/**
* Scale to render the Node at (Y-Axis)
*
* @remarks
* The scaleY value multiplies the provided {@link height} of the Node around
* the Node's Pivot Point (defined by the {@link pivot} props).
*
* @default 1.0
*/
scaleY: number;
/**
* Combined position of the Node's Mount Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Mount Point at the top-left corner of the Node.
* - `0.5` defines it at the center of the Node.
* - `1.0` defines it at the bottom-right corner of the node.
*
* Use the {@link mountX} and {@link mountY} props seperately for more control
* of the Mount Point.
*
* When assigned, the same value is also passed to both the {@link mountX} and
* {@link mountY} props.
*
* @default 0 (top-left)
*/
mount: number;
/**
* X position of the Node's Mount Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Mount Point's X position as the left-most edge of the
* Node
* - `0.5` defines it as the horizontal center of the Node
* - `1.0` defines it as the right-most edge of the Node.
*
* The combination of {@link mountX} and {@link mountY} define the Mount Point
*
* @default 0 (left-most edge)
*/
mountX: number;
/**
* Y position of the Node's Mount Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Mount Point's Y position as the top-most edge of the
* Node
* - `0.5` defines it as the vertical center of the Node
* - `1.0` defines it as the bottom-most edge of the Node.
*
* The combination of {@link mountX} and {@link mountY} define the Mount Point
*
* @default 0 (top-most edge)
*/
mountY: number;
/**
* Combined position of the Node's Pivot Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Pivot Point at the top-left corner of the Node.
* - `0.5` defines it at the center of the Node.
* - `1.0` defines it at the bottom-right corner of the node.
*
* Use the {@link pivotX} and {@link pivotY} props seperately for more control
* of the Pivot Point.
*
* When assigned, the same value is also passed to both the {@link pivotX} and
* {@link pivotY} props.
*
* @default 0.5 (center)
*/
pivot: number;
/**
* X position of the Node's Pivot Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Pivot Point's X position as the left-most edge of the
* Node
* - `0.5` defines it as the horizontal center of the Node
* - `1.0` defines it as the right-most edge of the Node.
*
* The combination of {@link pivotX} and {@link pivotY} define the Pivot Point
*
* @default 0.5 (centered on x-axis)
*/
pivotX: number;
/**
* Y position of the Node's Pivot Point
*
* @remarks
* The value can be any number between `0.0` and `1.0`:
* - `0.0` defines the Pivot Point's Y position as the top-most edge of the
* Node
* - `0.5` defines it as the vertical center of the Node
* - `1.0` defines it as the bottom-most edge of the Node.
*
* The combination of {@link pivotX} and {@link pivotY} define the Pivot Point
*
* @default 0.5 (centered on y-axis)
*/
pivotY: number;
/**
* Rotation of the Node (in Radians)
*
* @remarks
* Sets the amount to rotate the Node by around it's Pivot Point (defined by
* the {@link pivot} props). Positive values rotate the Node clockwise, while
* negative values rotate it counter-clockwise.
*
* Example values:
* - `-Math.PI / 2`: 90 degree rotation counter-clockwise
* - `0`: No rotation
* - `Math.PI / 2`: 90 degree rotation clockwise
* - `Math.PI`: 180 degree rotation clockwise
* - `3 * Math.PI / 2`: 270 degree rotation clockwise
* - `2 * Math.PI`: 360 rotation clockwise
*/
rotation: number;
/**
* Whether the Node is rendered to a texture
*
* @remarks
* TBD
*
* @default false
*/
rtt: boolean;
/**
* Node data element for custom data storage (optional)
*
* @remarks
* This property is used to store custom data on the Node as a key/value data store.
* Data values are limited to string, numbers, booleans. Strings will be truncated
* to a 2048 character limit for performance reasons.
*
* This is not a data storage mechanism for large amounts of data please use a
* dedicated data storage mechanism for that.
*
* The custom data will be reflected in the inspector as part of `data-*` attributes
*
* @default `undefined`
*/
data?: CustomDataMap;
/**
* Image Type to explicitly set the image type that is being loaded
*
* @remarks
* This property must be used with a `src` that points at an image. In some cases
* the extension doesn't provide a reliable representation of the image type. In such
* cases set the ImageType explicitly.
*
* `regular` is used for normal images such as png, jpg, etc
* `compressed` is used for ETC1/ETC2 compressed images with a PVR or KTX container
* `svg` is used for scalable vector graphics
*
* @default `undefined`
*/
imageType?: 'regular' | 'compressed' | 'svg' | null;
/**
* She width of the rectangle from which the Image Texture will be extracted.
* This value can be negative. If not provided, the image's source natural
* width will be used.
*/
srcWidth?: number;
/**
* The height of the rectangle from which the Image Texture will be extracted.
* This value can be negative. If not provided, the image's source natural
* height will be used.
*/
srcHeight?: number;
/**
* The x coordinate of the reference point of the rectangle from which the Texture
* will be extracted. `width` and `height` are provided. And only works when
* createImageBitmap is available. Only works when createImageBitmap is supported on the browser.
*/
srcX?: number;
/**
* The y coordinate of the reference point of the rectangle from which the Texture
* will be extracted. Only used when source `srcWidth` width and `srcHeight` height
* are provided. Only works when createImageBitmap is supported on the browser.
*/
srcY?: number;
/**
* By enabling Strict bounds the renderer will not process & render child nodes of a node that is out of the visible area
*
* @remarks
* When enabled out of bound nodes, i.e. nodes that are out of the visible area, will
* **NOT** have their children processed and renderer anymore. This means the children of a out of bound
* node will not receive update processing such as positioning updates and will not be drawn on screen.
* As such the rest of the branch of the update tree that sits below this node will not be processed anymore
*
* This is a big performance gain but may be disabled in cases where the width of the parent node is
* unknown and the render must process the child nodes regardless of the viewport status of the parent node
*
* @default false
*/
strictBounds: boolean;
}
/**
* Grab all the number properties of type T
*/
type NumberProps<T> = {
[Key in keyof T as NonNullable<T[Key]> extends number ? Key : never]: number;
};
/**
* Properties of a Node used by the animate() function
*/
export interface CoreNodeAnimateProps extends NumberProps<CoreNodeProps> {
/**
* Shader properties to animate
*/
shaderProps: Record<string, number>;
// TODO: textureProps: Record<string, number>;
}
/**
* A visual Node in the Renderer scene graph.
*
* @remarks
* CoreNode is an internally used class that represents a Renderer Node in the
* scene graph. See INode.ts for the public APIs exposed to Renderer users
* that include generic types for Shaders.
*/
export class CoreNode extends EventEmitter {
readonly children: CoreNode[] = [];
protected _id: number = getNewId();
readonly props: CoreNodeProps;
public updateType = UpdateType.All;
public childUpdateType = UpdateType.None;
public globalTransform?: Matrix3d;
public scaleRotateTransform?: Matrix3d;
public localTransform?: Matrix3d;
public renderCoords?: RenderCoords;
public renderBound?: Bound;
public strictBound?: Bound;
public preloadBound?: Bound;
public clippingRect: RectWithValid = {
x: 0,
y: 0,
width: 0,
height: 0,
valid: false,
};
public isRenderable = false;
public renderState: CoreNodeRenderState = CoreNodeRenderState.Init;
public worldAlpha = 1;
public premultipliedColorTl = 0;
public premultipliedColorTr = 0;
public premultipliedColorBl = 0;
public premultipliedColorBr = 0;
public calcZIndex = 0;
public hasRTTupdates = false;
public parentHasRenderTexture = false;
constructor(readonly stage: Stage, props: CoreNodeProps) {
super();
this.props = {
...props,
parent: null,
texture: null,
src: null,
rtt: false,
};
// Assign props to instance
this.parent = props.parent;
this.texture = props.texture;
this.src = props.src;
this.rtt = props.rtt;
if (props.boundsMargin) {
this.boundsMargin = Array.isArray(props.boundsMargin)
? props.boundsMargin
: [
props.boundsMargin,
props.boundsMargin,
props.boundsMargin,
props.boundsMargin,
];
}
this.setUpdateType(
UpdateType.ScaleRotate |
UpdateType.Local |
UpdateType.RenderBounds |
UpdateType.RenderState,
);
}
//#region Textures
loadTexture(): void {
const { texture } = this.props;
assertTruthy(texture);
// If texture is already loaded / failed, trigger loaded event manually
// so that users get a consistent event experience.
// We do this in a microtask to allow listeners to be attached in the same
// synchronous task after calling loadTexture()
queueMicrotask(() => {
texture.preventCleanup = this.props.preventCleanup;
// Preload texture if required
if (this.textureOptions.preload) {
texture.ctxTexture.load();
}
texture.on('loaded', this.onTextureLoaded);
texture.on('failed', this.onTextureFailed);
texture.on('freed', this.onTextureFreed);
// If the parent is a render texture, the initial texture status
// will be set to freed until the texture is processed by the
// Render RTT nodes. So we only need to listen fo changes and
// no need to check the texture.state until we restructure how
// textures are being processed.
if (this.parentHasRenderTexture) {
this.notifyParentRTTOfUpdate();
return;
}
if (texture.state === 'loaded') {
assertTruthy(texture.dimensions);
this.onTextureLoaded(texture, texture.dimensions);
} else if (texture.state === 'failed') {
assertTruthy(texture.error);
this.onTextureFailed(texture, texture.error);
} else if (texture.state === 'freed') {
this.onTextureFreed(texture);
}
});
}
unloadTexture(): void {
if (this.texture !== null) {
this.texture.off('loaded', this.onTextureLoaded);
this.texture.off('failed', this.onTextureFailed);
this.texture.off('freed', this.onTextureFreed);
this.texture.setRenderableOwner(this, false);
}
}
autosizeNode(dimensions: Dimensions) {
if (this.autosize) {
this.width = dimensions.width;
this.height = dimensions.height;
}
}
private onTextureLoaded: TextureLoadedEventHandler = (_, dimensions) => {
this.autosizeNode(dimensions);
// Texture was loaded. In case the RAF loop has already stopped, we request
// a render to ensure the texture is rendered.
this.stage.requestRender();
// If parent has a render texture, flag that we need to update
if (this.parentHasRenderTexture) {
this.notifyParentRTTOfUpdate();
}
this.emit('loaded', {
type: 'texture',
dimensions,
} satisfies NodeTextureLoadedPayload);
// Trigger a local update if the texture is loaded and the resizeMode is 'contain'
if (this.props.textureOptions?.resizeMode?.type === 'contain') {
this.setUpdateType(UpdateType.Local);
}
};
private onTextureFailed: TextureFailedEventHandler = (_, error) => {
// If parent has a render texture, flag that we need to update
if (this.parentHasRenderTexture) {
this.notifyParentRTTOfUpdate();
}
this.emit('failed', {
type: 'texture',
error,
} satisfies NodeTextureFailedPayload);
};
private onTextureFreed: TextureFreedEventHandler = () => {
// If parent has a render texture, flag that we need to update
if (this.parentHasRenderTexture) {
this.notifyParentRTTOfUpdate();
}
this.emit('freed', {
type: 'texture',
} satisfies NodeTextureFreedPayload);
};
//#endregion Textures
/**
* Change types types is used to determine the scope of the changes being applied
*
* @remarks
* See {@link UpdateType} for more information on each type
*
* @param type
*/
setUpdateType(type: UpdateType): void {
this.updateType |= type;
const parent = this.props.parent;
if (!parent) return;
if ((parent.updateType & UpdateType.Children) === 0) {
// Inform the parent if it doesn’t already have a child update
parent.setUpdateType(UpdateType.Children);
}
}
sortChildren() {
this.children.sort((a, b) => a.calcZIndex - b.calcZIndex);
}
updateScaleRotateTransform() {
const { rotation, scaleX, scaleY } = this.props;
// optimize simple translation cases
if (rotation === 0 && scaleX === 1 && scaleY === 1) {
this.scaleRotateTransform = undefined;
return;
}
this.scaleRotateTransform = Matrix3d.rotate(
rotation,
this.scaleRotateTransform,
).scale(scaleX, scaleY);
}
updateLocalTransform() {
const { x, y, width, height } = this.props;
const mountTranslateX = this.props.mountX * width;
const mountTranslateY = this.props.mountY * height;
if (this.scaleRotateTransform) {
const pivotTranslateX = this.props.pivotX * width;
const pivotTranslateY = this.props.pivotY * height;
this.localTransform = Matrix3d.translate(
x - mountTranslateX + pivotTranslateX,
y - mountTranslateY + pivotTranslateY,
this.localTransform,
)
.multiply(this.scaleRotateTransform)
.translate(-pivotTranslateX, -pivotTranslateY);
} else {
this.localTransform = Matrix3d.translate(
x - mountTranslateX,
y - mountTranslateY,
this.localTransform,
);
}
// Handle 'contain' resize mode
const texture = this.props.texture;
if (
texture &&
texture.dimensions &&
this.props.textureOptions?.resizeMode?.type === 'contain'
) {
let resizeModeScaleX = 1;
let resizeModeScaleY = 1;
let extraX = 0;
let extraY = 0;
const { width: tw, height: th } = texture.dimensions;
const txAspectRatio = tw / th;
const nodeAspectRatio = width / height;
if (txAspectRatio > nodeAspectRatio) {
// Texture is wider than node
// Center the node vertically (shift down by extraY)
// Scale the node vertically to maintain original aspect ratio
const scaleX = width / tw;
const scaledTxHeight = th * scaleX;
extraY = (height - scaledTxHeight) / 2;
resizeModeScaleY = scaledTxHeight / height;
} else {
// Texture is taller than node (or equal)
// Center the node horizontally (shift right by extraX)
// Scale the node horizontally to maintain original aspect ratio
const scaleY = height / th;
const scaledTxWidth = tw * scaleY;
extraX = (width - scaledTxWidth) / 2;
resizeModeScaleX = scaledTxWidth / width;
}
// Apply the extra translation and scale to the local transform
this.localTransform
.translate(extraX, extraY)
.scale(resizeModeScaleX, resizeModeScaleY);
}
this.setUpdateType(UpdateType.Global);
}
/**
* @todo: test for correct calculation flag
* @param delta
*/