forked from cocos/cocos-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskeleton.ts
More file actions
1958 lines (1834 loc) · 69.2 KB
/
Copy pathskeleton.ts
File metadata and controls
1958 lines (1834 loc) · 69.2 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
/*
Copyright (c) 2020-2023 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { EDITOR_NOT_IN_PREVIEW, JSB } from 'internal:constants';
import { ccclass, executeInEditMode, help, menu, serializable, type, override, displayOrder, editable, visible } from 'cc.decorator';
import { Material, Texture2D } from '../asset/assets';
import { error, errorID, logID, warnID } from '../core/platform/debug';
import { Enum, EnumType, ccenum } from '../core/value-types/enum';
import { Node, NodeEventType } from '../scene-graph';
import { CCObjectFlags, Color, RecyclePool, js } from '../core';
import { SkeletonData } from './skeleton-data';
import type { Graphics } from '../2d/components/graphics';
import { UIRenderer } from '../2d/framework/ui-renderer';
import { Batcher2D } from '../2d/renderer/batcher-2d';
import { BlendFactor, BlendOp } from '../gfx';
import { MaterialInstance } from '../render-scene';
import { assetManager, builtinResMgr } from '../asset/asset-manager';
import { legacyCC } from '../core/global-exports';
import { SkeletonSystem } from './skeleton-system';
import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity';
import { AttachUtil } from './attach-util';
import spine from './lib/spine-core';
import { VertexEffectDelegate } from './vertex-effect-delegate';
import SkeletonCache, { AnimationCache, AnimationFrame, SkeletonCacheItemInfo } from './skeleton-cache';
import { TrackEntryListeners } from './track-entry-listeners';
import { setPropertyEnumType } from '../core/internal-index';
import { RenderData } from '../2d/renderer/render-data';
import { SPINE_VERSION } from './lib/spine-version';
function isSkeletonDataValid (skeletonData: SkeletonData | null): skeletonData is SkeletonData {
return !!skeletonData && !skeletonData.isEmpty();
}
const CachedFrameTime = 1 / 60;
type TrackListener = (x: spine.TrackEntry) => void;
type TrackListener2 = (x: spine.TrackEntry, ev: spine.Event | number) => void;
/**
* @en
* Animation playback rate.
* @zh
* 动画播放速率。
*/
export const timeScale = 1.0;
/**
* @en Enum for animation cache mode type.
* @zh Spine 动画缓存类型。
*/
export enum SpineAnimationCacheMode {
/**
* @en Unset mode.
* @zh 未设置模式。
*/
UNSET = -1,
/**
* @en The realtime mode.
* @zh 实时计算模式。
*/
REALTIME = 0,
/**
* @en The shared cache mode.
* @zh 共享缓存模式。
*/
SHARED_CACHE = 1,
/**
* @en The private cache mode.
* @zh 私有缓存模式。
*/
PRIVATE_CACHE = 2,
}
ccenum(SpineAnimationCacheMode);
// To keep the compatibility, don't use it internally, otherwise, enum value may be inlined to wrong value.
// Use AnimationCacheMode instead.
export const AnimationCacheMode = SpineAnimationCacheMode;
interface AnimationItem {
animationName: string;
loop: boolean;
delay: number;
}
/**
* @engineInternal
*/
export enum DefaultSkinsEnum {
default = 0,
}
ccenum(DefaultSkinsEnum);
/**
* @engineInternal
*/
export enum SpineDefaultAnimsEnum {
'<None>' = 0
}
ccenum(SpineDefaultAnimsEnum);
// To keep the compatibility, don't use it internally, otherwise, enum value may be inlined to wrong value.
// Use SpineDefaultAnimsEnum instead.
export const DefaultAnimsEnum = SpineDefaultAnimsEnum;
/**
* @engineInternal
*/
export enum SpineMaterialType {
COLORED_TEXTURED = 0,
TWO_COLORED = 1,
}
interface AnimationItem {
animationName: string;
loop: boolean;
delay: number;
}
/**
* @engineInternal
*/
export interface SkeletonDrawData {
material: Material | null;
texture: Texture2D | null;
indexOffset: number;
indexCount: number;
}
export interface TempColor {
r: number;
g: number;
b: number;
a: number;
}
/**
* @en
* The Sockets attached to bones, synchronous transform with spine animation.
* @zh
* Spine 挂点,可附着在目标骨骼上随 spine 动画一起运动。
* @class SpineSocket
*/
@ccclass('sp.Skeleton.SpineSocket')
export class SpineSocket {
/**
* @en Path of the target joint.
* @zh 此挂点的目标骨骼路径。
*/
@serializable
@editable
public path = '';
/**
* @en Transform output node.
* @zh 此挂点的变换信息输出节点。
*/
@type(Node)
@editable
@serializable
public target: Node | null = null;
constructor (path = '', target: Node | null = null) {
this.path = path;
this.target = target;
}
}
js.setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket');
/**
* @en
* The skeleton of Spine <br/>
* <br/>
* (Skeleton has a reference to a SkeletonData and stores the state for skeleton instance,
* which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible. <br/>
* Multiple skeletons can use the same SkeletonData which includes all animations, skins, and attachments.) <br/>
* Cocos Creator supports spine versions lower than 3.8.99.
* @zh
* Spine 骨骼动画 <br/>
* <br/>
* (Skeleton 具有对骨骼数据的引用并且存储了骨骼实例的状态,
* 它由当前的骨骼动作,slot 颜色,和可见的 slot attachments 组成。<br/>
* 多个 Skeleton 可以使用相同的骨骼数据,其中包括所有的动画,皮肤和 attachments。
* Cocos Creator 支持 spine 版本最高到3.8.99。
* @class Skeleton
* @extends UIRenderer
*/
@ccclass('sp.Skeleton')
@help('i18n:cc.Spine')
@menu('Spine/Skeleton')
@executeInEditMode
export class Skeleton extends UIRenderer {
public static SpineSocket = SpineSocket;
public static AnimationCacheMode = SpineAnimationCacheMode;
@serializable
protected _skeletonData: SkeletonData | null = null;
@serializable
protected defaultSkin = '';
@serializable
protected defaultAnimation = '';
/**
* @en Indicates whether to enable premultiplied alpha.
* You should disable this option when image's transparent area appears to have opaque pixels,
* or enable this option when image's half transparent area appears to be darken.
* @zh 是否启用贴图预乘。
* 当图片的透明区域出现色块时需要关闭该选项,当图片的半透明区域颜色变黑时需要启用该选项。
*/
@serializable
protected _premultipliedAlpha = true;
@serializable
protected _timeScale = 1;
@serializable
protected _preCacheMode: SpineAnimationCacheMode = SpineAnimationCacheMode.UNSET;
@serializable
protected _cacheMode = SpineAnimationCacheMode.REALTIME;
@serializable
protected _sockets: SpineSocket[] = [];
@serializable
protected _useTint = false;
@serializable
protected _debugMesh = false;
@serializable
protected _debugBones = false;
@serializable
protected _debugSlots = false;
@serializable
protected _enableBatch = false;
protected _runtimeData: spine.SkeletonData | null = null;
public _skeleton: spine.Skeleton = null!;
protected _instance: spine.SkeletonInstance | null = null;
protected _state: spine.AnimationState = null!;
protected _textures: Texture2D[] = [];
private _skeletonInfo: SkeletonCacheItemInfo | null = null;
// Animation name
protected _animationName = '';
protected _skinName = '';
protected _drawList = new RecyclePool<SkeletonDrawData>((): SkeletonDrawData => ({
material: null,
texture: null,
indexOffset: 0,
indexCount: 0,
}), 1);
protected _materialCache: { [key: string]: MaterialInstance } = {} as any;
public paused = false;
protected _enumSkins: EnumType = Enum({});
protected _enumAnimations: EnumType = Enum({});
protected attachUtil: AttachUtil;
protected _socketNodes: Map<number, Node> = new Map();
protected _cachedSockets: Map<string, number> = new Map<string, number>();
/**
* @engineInternal
*/
public _startEntry: spine.TrackEntry;
/**
* @engineInternal
*/
public _endEntry: spine.TrackEntry;
// Paused or playing state
protected _paused = false;
// Below properties will effect when cache mode is SHARED_CACHE or PRIVATE_CACHE.
// accumulate time
protected _accTime = 0;
// Play times counter
protected _playCount = 0;
// Skeleton cache
protected _skeletonCache: SkeletonCache | null = null;
protected _animCache: AnimationCache | null = null;
protected _animationQueue: AnimationItem[] = [];
// Head animation info of
protected _headAniInfo: AnimationItem | null = null;
// Is animation complete.
protected _isAniComplete = true;
// Play times
protected _playTimes = 0;
/**
* @engineInternal
*/
public _curFrame: AnimationFrame | null = null;
protected _listener: TrackEntryListeners | null = null;
/**
* @engineInternal
* @mangle
*/
public _debugRenderer: Graphics | null = null;
/**
* @engineInternal
* @mangle
*/
public _startSlotIndex: number;
/**
* @engineInternal
* @mangle
*/
public _endSlotIndex: number;
private _customMaterialInstance: MaterialInstance | null = null;
_vLength = 0;
_vBuffer: Uint8Array | null = null;
_iLength = 0;
_iBuffer: Uint8Array | null = null;
_model: any;
_tempColor: TempColor = { r: 0, g: 0, b: 0, a: 0 };
private _eventListenerID: number = -1;
private _slotTextures: Map<string, Texture2D> | null = null;
private _isRenderable: boolean = false;
constructor () {
super();
this._useVertexOpacity = true;
this._startEntry = { animation: { name: '' }, trackIndex: 0 } as spine.TrackEntry;
this._endEntry = { animation: { name: '' }, trackIndex: 0 } as spine.TrackEntry;
this._startSlotIndex = -1;
this._endSlotIndex = -1;
if (!JSB) {
this._instance = new spine.SkeletonInstance();
this._instance.dtRate = this._timeScale * timeScale;
this._instance.isCache = this.isAnimationCached();
}
this.attachUtil = new AttachUtil();
}
/**
* @engineInternal
*/
get drawList (): RecyclePool<SkeletonDrawData> { return this._drawList; }
/**
* @en
* The skeleton data contains the skeleton information (bind pose bones, slots, draw order,
* attachments, skins, etc) and animations but does not hold any state.<br/>
* Multiple skeletons can share the same skeleton data.
* @zh
* 骨骼数据包含了骨骼信息(绑定骨骼动作,slots,渲染顺序,
* attachments,皮肤等等)和动画但不持有任何状态。<br/>
* 多个 Skeleton 可以共用相同的骨骼数据。
* @property {sp.SkeletonData} skeletonData
*/
@editable
@type(SkeletonData)
get skeletonData (): SkeletonData | null {
return this._skeletonData;
}
set skeletonData (value: SkeletonData | null) {
if (value) value.resetEnums();
if (this._skeletonData !== value) {
this.destroyRenderData();
this._skeletonData = value as any;
this.defaultSkin = '';
this.defaultAnimation = '';
this._animationName = '';
this._skinName = '';
this._animCache = null;
this._destroySkeletonInfo(this._skeletonCache);
this._updateSkeletonData();
this._updateUITransform();
}
}
/**
* @engineInternal
*/
@visible(true)
@type(DefaultSkinsEnum)
get _defaultSkinIndex (): number {
if (isSkeletonDataValid(this.skeletonData)) {
const skinsEnum = this.skeletonData.getSkinsEnum();
if (skinsEnum) {
if (this.defaultSkin === '') {
// eslint-disable-next-line no-prototype-builtins
if (skinsEnum.hasOwnProperty(0)) {
this._defaultSkinIndex = 0;
return 0;
}
} else {
const skinIndex = skinsEnum[this.defaultSkin];
if (skinIndex !== undefined) {
return skinIndex;
}
}
}
}
return 0;
}
/**
* @engineInternal
*/
set _defaultSkinIndex (value: number) {
let skinsEnum;
if (isSkeletonDataValid(this.skeletonData)) {
skinsEnum = this.skeletonData.getSkinsEnum();
}
if (!skinsEnum) {
error(`${this.name} skin enums are invalid`);
return;
}
const skinName = skinsEnum[value];
if (skinName !== undefined) {
this.defaultSkin = String(skinName);
this.setSkin(this.defaultSkin);
this._refreshInspector();
this._markForUpdateRenderData();
} else {
error(`${this.name} skin enums are invalid`);
}
}
// value of 0 represents no animation
/**
* @engineInternal
*/
@visible(true)
@type(SpineDefaultAnimsEnum)
get _animationIndex (): number {
const animationName = EDITOR_NOT_IN_PREVIEW ? this.defaultAnimation : this.animation;
if (isSkeletonDataValid(this.skeletonData)) {
if (animationName) {
const animsEnum = this.skeletonData.getAnimsEnum();
if (animsEnum) {
const animIndex = animsEnum[animationName];
if (animIndex !== undefined) {
return animIndex;
}
}
} else {
this._refreshInspector();
}
}
return 0;
}
/**
* @engineInternal
*/
set _animationIndex (value: number) {
let animsEnum;
if (isSkeletonDataValid(this.skeletonData)) {
animsEnum = this.skeletonData.getAnimsEnum();
}
if (!animsEnum) {
error(`${this.name} animation enums are invalid`);
return;
}
const animName = String(animsEnum[value]);
if (animName !== undefined) {
this.animation = animName;
if (EDITOR_NOT_IN_PREVIEW) {
this.defaultAnimation = animName;
this._refreshInspector();
} else {
this.animation = animName;
}
} else {
error(`${this.name} animation enums are invalid`);
}
}
/**
* @en Animation mode, with options for real-time mode, private cached, or public cached mode.
* @zh 动画模式,可选实时模式,私有 cached 或公共 cached 模式。
*/
@editable
@type(SpineAnimationCacheMode)
get defaultCacheMode (): SpineAnimationCacheMode {
return this._cacheMode;
}
set defaultCacheMode (mode: SpineAnimationCacheMode) {
this._cacheMode = mode;
this.setAnimationCacheMode(this._cacheMode);
}
/**
* @en Whether premultipliedAlpha enabled.
* @zh 是否启用 alpha 预乘。
*/
@editable
get premultipliedAlpha (): boolean { return this._premultipliedAlpha; }
set premultipliedAlpha (v: boolean) {
if (v !== this._premultipliedAlpha) {
this._premultipliedAlpha = v;
this._instance!.setPremultipliedAlpha(v);
this._markForUpdateRenderData();
}
}
/**
* @en Whether play animations in loop mode.
* @zh 是否循环播放当前骨骼动画。
*/
@visible(true)
@serializable
public loop = true;
/**
* @en The time scale of this skeleton.
* @zh 当前骨骼中所有动画的时间缩放率。
*/
@editable
get timeScale (): number { return this._timeScale; }
set timeScale (value) {
if (value !== this._timeScale) {
this._timeScale = value;
if (this._instance) {
this._instance.dtRate = this._timeScale * timeScale;
}
}
}
/**
* @en Enabled two color tint.
* @zh 是否启用染色效果。
*/
@editable
get useTint (): boolean { return this._useTint; }
set useTint (value) {
if (value !== this._useTint) {
this._useTint = value;
this._updateUseTint();
}
}
/**
* @en If rendering a large number of identical textures and simple skeletal animations,
* enabling batching can reduce the number of draw calls and improve rendering performance.
* @zh 如果渲染大量相同纹理,且结构简单的骨骼动画,开启合批可以降低 draw call 数量提升渲染性能。
*/
@editable
get enableBatch (): boolean { return this._enableBatch; }
set enableBatch (value) {
if (value !== this._enableBatch) {
this._enableBatch = value;
this._updateBatch();
}
}
/**
* @en
* The bone sockets this animation component maintains.<br>
* A SpineSocket object contains a path reference to bone, and a target node.
* @zh
* 当前动画组件维护的挂点数组。一个挂点组件包括动画节点路径和目标节点。
*/
@type([SpineSocket])
get sockets (): SpineSocket[] {
return this._sockets;
}
set sockets (val: SpineSocket[]) {
if (EDITOR_NOT_IN_PREVIEW) {
this._verifySockets(val);
}
this._sockets = val;
this._updateSocketBindings();
this.attachUtil.init(this);
}
/**
* @en Indicates whether open debug slots.
* @zh 是否显示 slot 的 debug 信息。
*/
@editable
get debugSlots (): boolean { return this._debugSlots; }
set debugSlots (v: boolean) {
if (v !== this._debugSlots) {
this._debugSlots = v;
this._updateDebugDraw();
this._markForUpdateRenderData();
}
}
/**
* @en Indicates whether open debug bones.
* @zh 是否显示 bone 的 debug 信息。
*/
@editable
get debugBones (): boolean { return this._debugBones; }
set debugBones (v: boolean) {
if (v !== this._debugBones) {
this._debugBones = v;
this._updateDebugDraw();
this._markForUpdateRenderData();
}
}
/**
* @en Indicates whether open debug mesh.
* @zh 是否显示 mesh 的 debug 信息。
*/
@editable
get debugMesh (): boolean { return this._debugMesh; }
set debugMesh (value) {
if (value !== this._debugMesh) {
this._debugMesh = value;
this._updateDebugDraw();
this._markForUpdateRenderData();
}
}
get socketNodes (): Map<number, Node> | null { return this._socketNodes; }
/**
* @en The name of current playing animation.
* @zh 当前播放的动画名称。
* @property {String} animation
*/
get animation (): string {
return this._animationName;
}
set animation (value: string) {
if (value) {
this.setAnimation(0, value, this.loop);
} else {
this.clearAnimation(0);
}
}
/**
* @en The customMaterial。
* @zh 用户自定材质。
*/
@override
@type(Material)
@displayOrder(0)
get customMaterial (): Material | null {
return this._customMaterial;
}
set customMaterial (val) {
this._customMaterial = val;
this.updateMaterial();
this._markForUpdateRenderData();
}
/**
* @deprecated Since v3.8.7, it will be removed in the future.
* We are deprecating the `customMaterialInstance` field because it leads to shared material state across all slots,
* causing unexpected behavior (like the last blendMode change affecting all slots).
* Workaround:
* Switch to customMaterial. Whenever its value is modified, immediately call updateMaterial at the exact point of change.
*/
get customMaterialInstance (): MaterialInstance | null {
if (!this._customMaterial) {
return null;
}
if (!this._customMaterialInstance) {
const matInfo = {
parent: this._customMaterial,
subModelIdx: 0,
owner: this,
};
this._customMaterialInstance = new MaterialInstance(matInfo);
}
return this._customMaterialInstance;
}
public __preload (): void {
super.__preload();
if (EDITOR_NOT_IN_PREVIEW) {
this.paused = true;
}
this._updateSkeletonData();
this._updateDebugDraw();
}
/**
* @engineInternal
*/
public onRestore (): void {
this.updateMaterial();
this._markForUpdateRenderData();
}
/**
* @en Gets the animation state object.
* @zh 获取动画状态。
* @method getState
* @return {sp.spine.AnimationState} state
*/
public getState (): spine.AnimationState | undefined {
return this._state;
}
/**
* @en Be called when component state becomes available.
* @zh 组件状态变为可用时调用。
*/
public onEnable (): void {
super.onEnable();
this._flushAssembler();
SkeletonSystem.getInstance().add(this);
this._isRenderable = true;
}
/**
* @en Be called when component state becomes disabled.
* @zh 组件状态变为禁用状态时调用。
*/
public onDisable (): void {
super.onDisable();
SkeletonSystem.getInstance().remove(this);
this._isRenderable = false;
}
public onDestroy (): void {
if (this._eventListenerID > 0) {
TrackEntryListeners.removeListener(this._eventListenerID);
this._eventListenerID = -1;
}
this._drawList.destroy();
this.destroyRenderData();
this._cleanMaterialCache();
this._vBuffer = null;
this._iBuffer = null;
this.attachUtil.reset();
this._slotTextures?.clear();
this._slotTextures = null;
this._cachedSockets.clear();
this._socketNodes.clear();
//if (this._cacheMode == SpineAnimationCacheMode.PRIVATE_CACHE) this._animCache?.destroy();
this._animCache = null;
SkeletonSystem.getInstance().remove(this);
if (!JSB && this._instance) {
this._instance.destroy();
this._instance = null;
}
this._destroySkeletonInfo(this._skeletonCache);
this._skeletonCache = null;
super.onDestroy();
}
/**
* @en Clear animation and set to setup pose, default value of track index is 0.
* @zh 清除指定动画并还原到初始姿势, 默认清除 track索引 为0的动画。
* @param {Number} [trackIndex] @en track index. @zh track 的索引。
*/
public clearAnimation (trackIndex?: number): void {
if (!this.isAnimationCached()) {
this.clearTrack(trackIndex || 0);
this.setToSetupPose();
}
}
/**
* @en Clear all animations and set to setup pose.
* @zh 清除所有动画并还原到初始姿势。
*/
public clearAnimations (): void {
if (!this.isAnimationCached()) {
this.clearTracks();
this.setToSetupPose();
}
}
protected _updateSkeletonData (): void {
const skeletonData = this._skeletonData;
if (!isSkeletonDataValid(this._skeletonData)) {
this._runtimeData = null!;
this._state = null!;
this._skeleton = null!;
this._textures = [];
this._refreshInspector();
if (this._isRenderable) {
SkeletonSystem.getInstance().remove(this);
}
return;
}
if (this._instance) {
this._instance.dtRate = this._timeScale * timeScale;
}
//const data = this.skeletonData?.getRuntimeData();
//if (!data) return;
//this.setSkeletonData(data);
this._runtimeData = skeletonData!.getRuntimeData();
if (!this._runtimeData) return;
this.setSkeletonData(this._runtimeData);
this._textures = skeletonData!.textures;
this._refreshInspector();
/* The animation must be configured after the skin because the animation depends on the skin.
If the animation is set before the skin,
it will cause rendering issues when a prefab with Spine assets is added to the scene node tree.
*/
if (this.defaultSkin && this.defaultSkin !== '') {
this.setSkin(this.defaultSkin);
} else if (this._skinName && this._skinName !== '') {
this.setSkin(this._skinName);
}
if (this.defaultAnimation) {
this.animation = this.defaultAnimation.toString();
} else if (this._animationName) {
this.animation = this._animationName;
} else {
this.animation = '';
}
this._updateUseTint();
this._indexBoneSockets();
this._updateSocketBindings();
this.attachUtil.init(this);
this._preCacheMode = this._cacheMode;
}
/**
* @en
* Sets runtime skeleton data to sp.Skeleton.<br>
* This method is different from the `skeletonData` property. This method is passed in the raw data provided by the
* Spine runtime, and the skeletonData type is the asset type provided by Creator.
* @zh
* 设置底层运行时用到的 SkeletonData。<br>
* 这个接口有别于 `skeletonData` 属性,这个接口传入的是 Spine runtime 提供的原始数据,而 skeletonData 的类型是 Creator 提供的资源类型。
* @param skeletonData @en The skeleton data contains the skeleton information (bind pose bones, slots, draw order, attachments,
* skins, etc) and animations but does not hold any state. @zh 骨架数据(SkeletonData)包含骨架信息(绑定pose的骨骼、槽位、绘制顺序、附件、
* 皮肤等)和动画, 但不保存任何状态。
*/
public setSkeletonData (skeletonData: spine.SkeletonData): void {
if (!EDITOR_NOT_IN_PREVIEW) {
const preSkeletonCache = this._skeletonCache;
if (this._cacheMode === SpineAnimationCacheMode.SHARED_CACHE) {
this._skeletonCache = SkeletonCache.sharedCache;
} else if (this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) {
this._skeletonCache = new SkeletonCache();
this._skeletonCache.enablePrivateMode();
} else {
this._skeletonCache = null;
}
//cache mode may be changed
if (preSkeletonCache !== this._skeletonCache) {
this._destroySkeletonInfo(preSkeletonCache);
}
}
if (this.isAnimationCached()) {
if (this.debugBones || this.debugSlots) {
warnID(16410);
}
const skeletonInfo = this._skeletonCache!.getSkeletonInfo(this._skeletonData!);
if (this._skeletonInfo !== skeletonInfo) {
this._destroySkeletonInfo(this._skeletonCache);
if (!skeletonInfo && this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) {
this._animCache = this._skeletonCache!.initAnimationCache(this.skeletonData!.uuid, this._skeletonData!, this._animationName);
}
this._skeletonInfo = this._skeletonCache!.createSkeletonInfo(this._skeletonData!);
}
if (this._skeletonInfo) {
this._skeleton = this._skeletonInfo.skeleton!;
}
} else {
this._skeleton = this._instance!.initSkeleton(skeletonData);
this._state = this._instance!.getAnimationState();
this._instance!.setPremultipliedAlpha(this._premultipliedAlpha);
}
if (this._isRenderable) {
SkeletonSystem.getInstance().add(this);
}
// Recreate render data and mark dirty
this._flushAssembler();
}
/**
* @en Sets slots visible range.
* @zh 设置骨骼插槽可视范围。
* @param {Number} startSlotIndex @en start slot index. @zh 开始插槽的索引。
* @param {Number} endSlotIndex @en end slot index. @zh 结束插槽的索引。
*/
public setSlotsRange (startSlotIndex: number, endSlotIndex: number): void {
if (this.isAnimationCached()) {
warnID(16411);
} else {
this._startSlotIndex = startSlotIndex;
this._endSlotIndex = endSlotIndex;
}
}
/**
* @en
* Returns the attachment for the slot and attachment name.
* The skeleton looks first in its skin, then in the skeleton data’s default skin.<br>
* Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment object.
* @zh
* 通过 slot 和 attachment 的名称获取 attachment。Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。<br>
* 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment 对象。
*
* @method getAttachment
* @param {String} slotName @en slot name. @zh 插槽的名字。
* @param {String} attachmentName @en attachment name. @en 附件的名称。
* @return {sp.spine.Attachment}
*/
public getAttachment (slotName: string, attachmentName: string): spine.Attachment | null {
if (this._skeleton) {
return this._skeleton.getAttachmentByName(slotName, attachmentName);
}
return null;
}
/**
* @en
* Sets the attachment for the slot and attachment name.
* The skeleton looks first in its skin, then in the skeleton data’s default skin.
* @zh
* 通过 slot 和 attachment 的名字来设置 attachment。
* Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。
* @method setAttachment
* @param {String} slotName @en slot name. @zh 插槽的名字。
* @param {String} attachmentName @en attachment name. @en 附件的名称。
*/
public setAttachment (slotName: string, attachmentName: string): void {
if (this._skeleton) {
this._skeleton.setAttachment(slotName, attachmentName);
}
this.invalidAnimationCache();
}
/**
* @en
* Get Texture Atlas used in attachments.
* @zh
* 获取附件图集。
* @param regionAttachment @en An attachment type of RegionAttachment or BoundingBoxAttachment. @zh RegionAttachment 或 BoundingBoxAttachment 的附件。
* @return @en TextureRegion contains texture and atlas text information. @zh TextureRegion包含纹理和图集文本信息。
*/
public getTextureAtlas (regionAttachment: spine.RegionAttachment | spine.BoundingBoxAttachment): spine.TextureRegion {
return (regionAttachment as spine.RegionAttachment).region;
}
/**
* @en Set the current animation. Any queued animations are cleared.<br>
* @zh 设置当前动画。队列中的任何的动画将被清除。<br>
* @param trackIndex @en Index of track. @zh 动画通道索引。
* @param name @en The name of animation. @zh 动画名称。
* @param loop @en Use loop mode or not. @zh 是否使用循环播放模式。
*/
public setAnimation (trackIndex: number, name: string, loop?: boolean): spine.TrackEntry | null {
if (!(typeof name === 'string')) {
logID(7511);
return null;
}
const skeleton = this._skeleton;
const animation = skeleton ? skeleton.data.findAnimation(name) : null;
if (!animation) {
logID(7509, name);
return null;
}
let trackEntry: spine.TrackEntry | null = null;
if (loop === undefined) loop = true;
this._playTimes = loop ? 0 : 1;
if (this.isAnimationCached()) {
if (trackIndex !== 0) {
warnID(16412);
}
if (!this._skeletonCache) return null;
let cache = this._skeletonCache.getAnimationCache(this._skeletonData!.uuid, name);
if (!cache) {
cache = this._skeletonCache.initAnimationCache(this.skeletonData!.uuid, this._skeletonData!, name);
if (cache && this._skinName) cache.setSkin(this._skinName);
}
if (cache) {
this._animationName = name;
this._isAniComplete = false;
this._accTime = 0;
this._playCount = 0;
this._animCache = cache;
if (this._socketNodes.size > 0) {
this._animCache.enableCacheAttachedInfo();
}
this._animCache.updateToFrame(0);
this._curFrame = this._animCache.frames[0];
}
} else {
this._animationName = name;
trackEntry = this._instance!.setAnimation(trackIndex, name, loop);
}
this._markForUpdateRenderData();
return trackEntry;
}
/**
* @en Adds an animation to be played delay seconds after the current or last queued animation.<br>
* Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object.
* @zh 添加一个动画到动画队列尾部,还可以延迟指定的秒数。<br>
* 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry 对象。
* @param trackIndex @en Index of trackEntry. @zh TrackEntry 索引。
* @param name @en The name of animation. @zh 动画名称。
* @param loop @en Set play animation in a loop. @zh 是否循环播放。
* @param delay @en Delay time of animation start. @zh 动画开始的延迟时间。
* @return {sp.spine.TrackEntry}
*/