-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnimPlayer.cs
2543 lines (2199 loc) · 73.9 KB
/
UnimPlayer.cs
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
// © 2020 JAY EDRY ALL RIGHTS RESERVED
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
using UnityEngine.Events;
using FullSerializer;
namespace Unim
{
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
public class UnimPlayer : MonoBehaviour
{
#region FIELDS
// Shared Unim Data
public UnimData UnimData; // Stores shared Unim variables
[Header("Input Files")]
[SerializeField] protected Texture2D unimSheetAsset;
[SerializeField] protected TextAsset unimDataAsset;
[SerializeField] private bool loadDataAsBytes;
[Header("General Init Settings")]
[SerializeField] private ClipUpdateMode updateMode = ClipUpdateMode.Time;
[SerializeField] private float frameRate = 30;
[SerializeField] private bool initOnAwake = true;
[SerializeField] private bool enhancedColorOperations = true;
[SerializeField] private bool playOnAwake = true;
[Header("Additional Init Settings")]
[SerializeField] private ScaleTypes scaleMode = ScaleTypes.ScaleToFitUnitWidth;
[SerializeField] private float scaleMultiplier = 1;
[Tooltip("Set pivot position.\n\n" +
"Bottom Left ( -1, -1 )\n" +
"Top Right ( 1, 1 )")]
[SerializeField] private Vector2 pivotCoordinates;
[SerializeField] private float spriteDepth = 0.001f;
[SerializeField] private Vector2 cullingBoundsScaler = Vector2.one;
// Hidden Sorting properties
[HideInInspector] [SerializeField] private int sortingLayerId;
[HideInInspector] [SerializeField] private int orderInLayer;
// Hidden Parameters
[HideInInspector] [SerializeField] private GameObject[] trackObjectsToLink; // Linked to trackObjects by index
[HideInInspector] [SerializeField] private UnityEvent[] triggerUnityEvents; // Linked to triggerEvents by index
// Vertex Variables
private ColorOffsetType fillColorOffset; // The overwrite animation color
private ColorOffsetType[][] spriteColorOffsets; // The overwrite sprite color
private Color[] finalFrameVertexRenderColorsSub; // Subtractive colors for each vertex passed to shader
private Vector2[]
finalFrameVertexRenderColorsAddRG; // Red & Green additive colors for each vertex passed to shader
private Vector2[]
finalFrameVertexRenderColorsAddBA; // Blue & Alpha additive colors for each vertex passed to shader
// Material Properties
private Material mat;
private Texture2D spriteSheet;
private MeshRenderer rend;
// Mesh properties
private Mesh mesh;
private string meshName = "Sprite Mesh";
private Matrix4x4 pivotScaleOffsetMatrix; // Mesh pivot & scaler offset matrix
private Vector3[][] finalTransformedVertices;
// Delegates
public delegate void OnTriggerEvent(); // Defines OnTriggerEvent event
private Action unimUnloadHandler; // Handles destruction of Unim
public Action ClipStartDelegate; // TODO implement this
public Action ClipCompleteDelegate; // TODO implement this
// TriggerEvents
private TriggerEvent[] triggerEvents;
public Dictionary<int, List<TriggerEvent>>
triggerEventByFrameNumber; // Used for invoking trigger events on played frames
public Dictionary<string, TriggerEvent> triggerEventByTriggerName; // Used for subscribing to triggers
// Trackers
private Tracker[] trackers;
private float scaleValue;
private Vector3 trackPosOffset;
// Frame
public int CurrentFrame => currentFrame;
private int currentFrame = 1;
private int prevFrame;
// Coroutine for animated color operations
private Coroutine fadeFillCo;
private Coroutine fadeSpriteCo;
// Optimization bools
private bool prevRenderHasAnimation = true; // Prevents processes from two consecutive blank frames.
private bool forceRender; // Guarantees render for that frame
private bool isCustomSheetCreated;
private bool currentFrameHasFillCol;
private bool prevFrameHasFillCol;
private bool currentFrameHasSpriteCol;
private bool prevFrameHasSpriteCol;
// Playback parameters
private readonly Queue<PlayableAnimation> animationQueue = new Queue<PlayableAnimation>(); // Anims to be played
private PlayableAnimation currentAnim;
private float elapsedFrameTime;
private float elapsedClipTime;
private float prevFrameRate;
public bool IsPlaying { get; private set; }
private int clipLoopCount;
private float spfAbsolute;
private float spf;
public float Spf // Seconds per frame
{
get { return spf; }
private set
{
spf = value;
spfAbsolute = Mathf.Abs(spf);
}
}
#endregion
#region CLASSES AND STRUCTS
private class ColorOffsetType
{
public Color colorSub;
public Color colorAdd;
public ColorOperation colorOperation;
public ColorOffsetType()
{
colorSub = Color.white;
colorAdd = Color.clear;
colorOperation = ColorOperation.Combine;
}
public void Reset()
{
colorSub = Color.white;
colorAdd = Color.clear;
colorOperation = ColorOperation.Combine;
}
}
public enum ColorOperation
{
Overwrite,
Combine
}
public enum ScaleTypes
{
OnePixelPerUnit,
ScaleToFitUnitHeight,
ScaleToFitUnitWidth
}
public enum ClipUpdateMode
{
Time,
UnscaledTime,
Manual
}
// Playables
public class PlayableAnimation
{
public UnimClip Clip { get; private set; }
public PlayType PlayType { get; private set; }
public int FrameOffset { get; private set; }
public int MaxCount { get; private set; }
public float MaxPlayTime { get; private set; }
public Action OnStart { get; private set; }
public Action OnEnd { get; private set; }
public Action OnExit { get; private set; }
public bool isInfLoop
{
get { return MaxCount <= 0; }
}
public PlayableAnimation(UnimClip clip, PlayType playType = PlayType.Loop, int startFrameOffset = 0,
int maxCount = -1, float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null,
Action onExit = null)
{
Clip = clip;
PlayType = playType;
FrameOffset = startFrameOffset;
MaxCount = maxCount;
MaxPlayTime = maxPlayTime;
// delegates
OnStart = onStart;
OnEnd = onEnd;
OnExit = onExit;
}
}
public class TriggerEvent
{
public UnimData.Trigger trigger;
private event OnTriggerEvent onTriggerEvent;
public void SubscribeToTrigger(OnTriggerEvent method)
{
onTriggerEvent += method;
}
public void UnSubscribeToTrigger(OnTriggerEvent method)
{
onTriggerEvent -= method;
}
public void RunTrigger()
{
if (onTriggerEvent != null)
{
onTriggerEvent();
}
}
}
public class Tracker
{
public UnimData.TrackObject trackObject;
public GameObject gameObject;
}
public enum PlayType
{
Loop,
PlayOnce,
SingleFrame
}
#endregion
#region UNIM INITIALIZERS
private void Awake()
{
Spf = fpsToSpf(frameRate); // Frames Per Second to Seconds Per Frame. Automatically sets spfAbsolute
if (initOnAwake)
{
InitUnim();
}
if (playOnAwake)
{
UnimClip playAll = new UnimClip(" ALL ", 1, UnimData.MaxFrames - 1);
BeginNewAnim(new PlayableAnimation(playAll));
}
}
private void Destroy()
{
if (unimUnloadHandler != null)
{
unimUnloadHandler();
}
}
public void InitUnim()
{
InitUnim(unimDataAsset, unimSheetAsset, loadDataAsBytes);
}
protected void InitUnim(TextAsset unimData, Texture2D sheet, bool loadAsBytes = false)
{
// Validate Unim Files
if (unimData == null)
{
throw new Exception("No UnimData asset assigned!");
}
// Validate Sheet
if (sheet == null)
{
throw new Exception("No UnimSheet asset assigned!");
}
// Initialize differently if in Play or Editor mode
currentFrame = 1;
if (rend == null)
{
rend = GetComponent<MeshRenderer>();
}
if (Application.isPlaying)
{
InitMain(unimData, sheet, loadAsBytes);
}
else
{
EditorInitMain(unimData, sheet, loadAsBytes);
}
}
private void InitMain(TextAsset unimData, Texture2D spriteSheet, bool loadAsBytes)
{
UnimData = LoadUnimData(unimData, loadAsBytes);
rend.sharedMaterial = LoadUnimMaterial(spriteSheet);
SetSortingLayer(sortingLayerId, orderInLayer);
InitPivotScaleOffset();
InitTriggerEvents();
InitTrackers();
InitColorOperations();
InitRenderVariables(this);
}
private void EditorInitMain(TextAsset file, Texture2D spriteSheet, bool loadAsBytes)
{
UnimData = UnimCache.Instance.LoadUnimData(file, loadAsBytes, true);
rend.material = UnimCache.Instance.LoadUnimMaterial(spriteSheet, true);
SetSortingLayer(sortingLayerId, orderInLayer);
InitPivotScaleOffset();
InitColorOperations();
InitRenderVariables(this);
}
public void SetSortingLayer(int layerId, int order)
{
rend.sortingLayerID = layerId;
rend.sortingOrder = order;
}
private void InitPivotScaleOffset()
{
// Reset Matrix
pivotScaleOffsetMatrix = Matrix4x4.identity;
// Scale Width and Height
scaleValue = 1;
switch (scaleMode)
{
case ScaleTypes.OnePixelPerUnit:
scaleValue = 1f * scaleMultiplier;
break;
case ScaleTypes.ScaleToFitUnitHeight:
scaleValue = 1f / (float) UnimData.sceneHeight * scaleMultiplier;
break;
case ScaleTypes.ScaleToFitUnitWidth:
scaleValue = 1f / (float) UnimData.sceneWidth * scaleMultiplier;
break;
}
pivotScaleOffsetMatrix.m03 = pivotCoordinates.x * -(UnimData.sceneWidth * scaleValue / 2); //posX;
pivotScaleOffsetMatrix.m13 = pivotCoordinates.y * -(UnimData.sceneHeight * scaleValue / 2); //posY;
// PivotOffset
pivotScaleOffsetMatrix.m00 = scaleValue; //scaleX;
pivotScaleOffsetMatrix.m11 = scaleValue; //scaleY;
// Scale Sprite Depth
pivotScaleOffsetMatrix.m22 = spriteDepth; //scaleZ;
// ReCalculate Culling Bounds
if (mesh != null)
{
mesh.bounds = new Bounds(
new Vector3(pivotScaleOffsetMatrix.m03, pivotScaleOffsetMatrix.m13,
(spriteDepth * UnimData.maxSprites) / 2),
new Vector3(UnimData.sceneWidth * scaleValue * cullingBoundsScaler.x,
UnimData.sceneHeight * scaleValue * cullingBoundsScaler.y, spriteDepth * UnimData.maxSprites)
);
}
finalTransformedVertices = new Vector3[UnimData.frameData.Length][];
for (int i = 0; i < UnimData.frameData.Length; i++)
{
finalTransformedVertices[i] = new Vector3[UnimData.frameData[0].vertTransforms.Length];
for (int j = 0; j < UnimData.frameData[i].vertTransforms.Length; j++)
{
finalTransformedVertices[i][j] =
pivotScaleOffsetMatrix.MultiplyPoint(UnimData.frameData[i].vertTransforms[j]);
}
}
}
private void InitColorOperations()
{
// Instantiates global color offset as: Color.clear, ColorOperation.Combine
fillColorOffset = new ColorOffsetType();
if (enhancedColorOperations)
{
// populate individual sprite specific variables
UnimData.animSpriteUsagePositionsBySpriteName = GenerateSpriteDataBySpriteNameDict(this);
// Instantiates an array for each animation vertex as: Color.clear, ColorOperation.Add
spriteColorOffsets = InitSpriteColorsOffset(this);
}
}
private void InitTriggerEvents()
{
if (UnimData.triggersExist)
{
// Create look up tables
triggerEventByFrameNumber = new Dictionary<int, List<TriggerEvent>>();
triggerEventByTriggerName = new Dictionary<string, TriggerEvent>();
// Create triggers instance
triggerEvents = new TriggerEvent[UnimData.triggers.Length];
for (int i = 0; i < triggerEvents.Length; i++)
{
triggerEvents[i] = new TriggerEvent();
triggerEvents[i].trigger = UnimData.triggers[i]; // Assign UnimData.trigger to triggerEvents
int frmNum = triggerEvents[i].trigger.frame; // Store frameNum
// Add trigger event to lookup table by frame number
if (!triggerEventByFrameNumber.ContainsKey(frmNum))
{
triggerEventByFrameNumber.Add(frmNum, new List<TriggerEvent>() {triggerEvents[i]});
}
else
{
triggerEventByFrameNumber[frmNum].Add(triggerEvents[i]);
}
// Add trigger event to lookup table by trigger name
if (!triggerEventByTriggerName.ContainsKey(triggerEvents[i].trigger.name))
{
triggerEventByTriggerName.Add(triggerEvents[i].trigger.name, triggerEvents[i]);
}
else
{
Debug.LogError("There can not be two instances of the same Trigger Name '" +
triggerEvents[i].trigger.name + "'");
}
}
}
}
private void InitTrackers()
{
if (UnimData.trackObjectsExist)
{
// Set Track Offset Position for use in updates.
trackPosOffset.x = 0.5f * UnimData.sceneWidth * scaleValue * (-pivotCoordinates.x - 1);
trackPosOffset.y = 0.5f * UnimData.sceneHeight * scaleValue * (-pivotCoordinates.y - 1);
// Create trackers instance
trackers = new Tracker[UnimData.trackObjects.Length];
for (int i = 0; i < trackers.Length; i++)
{
trackers[i] = new Tracker();
trackers[i].trackObject = UnimData.trackObjects[i];
// Create Game Track GameObject and parent it
trackers[i].gameObject = new GameObject(UnimData.trackObjects[i].name);
trackers[i].gameObject.transform.parent = transform;
// If obj exists in scene parent it to TrackObj otherwise instantiate to TrackObj
if (i < trackObjectsToLink.Length && trackObjectsToLink[i] != null)
{
if (trackObjectsToLink[i].scene.IsValid())
{
trackObjectsToLink[i].transform.parent = trackers[i].gameObject.transform;
}
else
{
Instantiate(trackObjectsToLink[i], trackers[i].gameObject.transform);
}
}
}
}
}
private UnimData LoadUnimData(TextAsset unimData, bool loadAsBytes)
{
// If animation data already exists load from file, otherwise load from cache
UnimData u = UnimCache.Instance.LoadUnimData(unimData, loadAsBytes);
unimUnloadHandler += () => { UnimCache.Instance.UnloadUnimData(unimData); };
return u;
}
private Material LoadUnimMaterial(Texture2D spriteSheetPath)
{
Material m = UnimCache.Instance.LoadUnimMaterial(spriteSheetPath);
unimUnloadHandler += () => { UnimCache.Instance.UnloadUnimMaterial(spriteSheetPath); };
return m;
}
private void InitRenderVariables(UnimPlayer unimPlayer)
{
// create Mesh
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
meshFilter.sharedMesh = CreateUnimMesh();
// create meshes to display sprites
mesh = GetComponent<MeshFilter>().sharedMesh;
// allocate space for maximum number of verticies needed in animation
finalFrameVertexRenderColorsSub = new Color[UnimData.TotalVertexCount];
finalFrameVertexRenderColorsAddRG = new Vector2[UnimData.TotalVertexCount];
finalFrameVertexRenderColorsAddBA = new Vector2[UnimData.TotalVertexCount];
// Instantiate with default values
for (int i = 0; i < UnimData.TotalVertexCount; i++)
{
finalFrameVertexRenderColorsSub[i] = Color.white;
finalFrameVertexRenderColorsAddRG[i] = new Vector2(0, 0);
finalFrameVertexRenderColorsAddBA[i] = new Vector2(0, 0);
}
}
private Mesh CreateUnimMesh()
{
// mesh init -1 1
Mesh m = new Mesh();
m.name = meshName;
// set initial vertices to match scene width and height. Used for culling bounds
float px = pivotCoordinates.x;
float py = pivotCoordinates.y;
float sw = (float) UnimData.sceneWidth;
float sh = (float) UnimData.sceneHeight;
float left = -sw / 2 - px / 2 * sw;
float right = sw / 2 - px / 2 * sw; //
float bottom = -sh / 2 - py / 2 * sh;
float top = sh / 2 - py / 2 * sh; //
Vector2 cullTopLeft = new Vector2(left, top);
Vector2 cullTopRight = new Vector2(right, top);
Vector2 cullBottomRight = new Vector2(right, bottom);
Vector2 cullBottomLeft = new Vector2(left, bottom);
//Positions rest of verts in center of cull area
Vector2 centerPoint = Vector2.Lerp(cullBottomLeft, cullTopRight, 0.5f);
// set up vertecies for sprite mesh
Vector3[] vertexArray = new Vector3[UnimData.TotalVertexCount];
for (int i = 0;
i < vertexArray.Length;
i = i + 4) // set all sprites to be a square 1 unit mesh except for the last mesh which is set to mimic the size of the flash scene
{
if (i == 0)
{
vertexArray[i + 0] = cullTopLeft;
vertexArray[i + 1] = cullTopRight;
vertexArray[i + 2] = cullBottomRight;
vertexArray[i + 3] = cullBottomLeft;
}
else
{
vertexArray[i + 0] = centerPoint;
vertexArray[i + 1] = centerPoint;
vertexArray[i + 2] = centerPoint;
vertexArray[i + 3] = centerPoint;
}
}
m.vertices = vertexArray;
// setup uv's for vertecies of sprite mesh
Vector2[] uvArray = new Vector2[UnimData.TotalVertexCount];
for (int i = 0; i < uvArray.Length; i++)
{
uvArray[i] = Vector2.zero; // make all uv's reference the bottom left point of the sprite sheet.
}
m.uv = uvArray;
// setup triangle faces for vertecies
int numTrianglesPoints =
UnimData.maxSprites * 2 * 3; // each sprite has 2 triangles. Each triangle has 3 points.
int[] trianglePointArray = new int[numTrianglesPoints];
int triangleCount = 0;
for (int i = 0;
i < trianglePointArray.Length;
i = i + 6) // add triangles to all vertecies minus the last 4( vertecies
{
trianglePointArray[i] = 0 + triangleCount;
trianglePointArray[i + 1] = 1 + triangleCount;
trianglePointArray[i + 2] = 2 + triangleCount;
trianglePointArray[i + 3] = 0 + triangleCount;
trianglePointArray[i + 4] = 2 + triangleCount;
trianglePointArray[i + 5] = 3 + triangleCount;
triangleCount = triangleCount + 4;
}
m.triangles = trianglePointArray;
// set up normals
m.RecalculateNormals();
return m;
}
private ColorOffsetType[][] InitSpriteColorsOffset(UnimPlayer unimPlayer)
{
ColorOffsetType[][] s = new ColorOffsetType[UnimData.MaxFrames][];
for (int i = 0; i < s.Length; i++)
{
s[i] = new ColorOffsetType[UnimData.TotalVertexCount];
for (int j = 0; j < s[i].Length; j++)
{
s[i][j] = new ColorOffsetType();
}
}
return s;
}
private Dictionary<string, List<int[]>> GenerateSpriteDataBySpriteNameDict(UnimPlayer unimPlayer)
{
Dictionary<string, List<int[]>> dict = new Dictionary<string, List<int[]>>();
// For each sprite key create a list of int arrays
for (int i = 0; i < UnimData.sprites.Length; i++)
{
dict.Add(UnimData.sprites[i].name, new List<int[]>());
}
for (int i = 0; i < UnimData.animationData.Length; i++)
{
for (int j = 0; j < UnimData.animationData[i].Length; j++)
{
string imageName = UnimData.sprites[UnimData.animationData[i][j].spriteID].name;
dict[imageName].Add(new int[2] {i, j});
}
}
return dict;
}
#endregion
#region PLAYBACK METHODS
private void Update()
{
if (updateMode == ClipUpdateMode.Time)
{
UpdateClip(Time.deltaTime);
}
else if (updateMode == ClipUpdateMode.UnscaledTime)
{
UpdateClip(Time.unscaledDeltaTime);
}
}
public void UpdateClip(float deltaTime)
{
if (prevFrameRate != frameRate)
{
Spf = fpsToSpf(frameRate); // Automatically sets spfAbsolute
prevFrameRate = frameRate;
}
if (IsPlaying)
{
elapsedFrameTime += deltaTime;
if (elapsedFrameTime >= spfAbsolute)
{
UpdateFrame(deltaTime);
elapsedFrameTime -= spfAbsolute * Mathf.Floor(elapsedFrameTime / spfAbsolute);
}
}
}
private void OnWillRenderObject()
{
if (prevFrame != currentFrame || forceRender)
{
RunUnimFrame(currentFrame);
prevFrame = currentFrame;
forceRender = false;
}
}
private int GetFrameOffsetFromOutsideClipBounds(int frame, UnimClip unimClip)
{
if (frame < unimClip.startFrame)
{
return frame - unimClip.startFrame;
}
else if (frame >= unimClip.endFrame)
{
return frame - unimClip.endFrame + 1;
}
else
{
return 0;
}
}
private void EndPlayback()
{
IsPlaying = false;
elapsedFrameTime = 0;
}
private void UpdateFrame(float deltaTime)
{
// Update time the clip has been playing
elapsedClipTime += deltaTime;
// Null check
if (currentAnim == null)
{
Debug.LogError("no animation in Queue");
return;
}
// Exit Clip if playing past Max Play Time
if (elapsedClipTime >= currentAnim.MaxPlayTime)
{
if (animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
}
else
{
EndPlayback();
}
}
// Update next frame
int newFrame = currentFrame + (int) Mathf.Floor(elapsedFrameTime / Spf); // Increment frame
int offset =
GetFrameOffsetFromOutsideClipBounds(newFrame,
currentAnim.Clip); // Returns how many frames outside of the clips designated frames
// SingleFrame update
if (currentAnim.PlayType == PlayType.SingleFrame)
{
clipLoopCount++;
if (clipLoopCount >= currentAnim.MaxCount)
{
if (animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
}
else
{
EndPlayback();
}
}
return;
}
// PlayOnce update
else if (currentAnim.PlayType == PlayType.PlayOnce)
{
if (offset != 0) // If newFrame is out of Clips frame bounds
{
clipLoopCount++; // Increment Loop Counter
// If an animation is available in the queue then start playing it.
if (animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
newFrame = currentFrame; // currentFrame is set by AssignNextAnimInQueue()
}
else
{
if (offset < 0)
{
newFrame = currentAnim.Clip.startFrame;
}
else
{
newFrame = currentAnim.Clip.endFrame - 1;
}
EndPlayback();
}
}
}
// Loop update
else if (currentAnim.PlayType == PlayType.Loop)
{
if (offset != 0) // If newFrame is out of Clips frame bounds
{
clipLoopCount++; // Increment Loop Counter
// If max loop count reached
if (!currentAnim.isInfLoop && clipLoopCount >= currentAnim.MaxCount)
{
// If an animation is available in the queue then start playing it.
if (animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
newFrame = currentFrame; // currentFrame is set by AssignNextAnimInQueue()
}
else
{
if (offset > 0)
{
newFrame = currentAnim.Clip.endFrame;
}
else
{
newFrame = currentAnim.Clip.startFrame;
}
EndPlayback();
}
}
else if (offset < 0)
{
newFrame = currentAnim.Clip.endFrame -
Mathf.FloorToInt((currentAnim.Clip.startFrame - newFrame) %
currentAnim.Clip.duration);
}
else if (newFrame >= currentAnim.Clip.endFrame)
{
newFrame = currentAnim.Clip.startFrame +
Mathf.FloorToInt((newFrame - currentAnim.Clip.endFrame) %
currentAnim.Clip.duration);
}
}
}
currentFrame = newFrame; // Update to next frame
}
public void PlayNextAnimInQueue()
{
if (animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
}
else
{
Debug.Log("No animations available in queue");
}
}
private void BeginNewAnim(PlayableAnimation anim)
{
// Setting Clip to null and MaxCount to -1 triggers a stop
if (anim.Clip == null && anim.MaxCount == -1)
{
Stop();
return;
}
// If current animation is instantly interruptable and animation in queue
if ((anim.MaxCount == 0 || anim.PlayType == PlayType.SingleFrame && anim.MaxCount <= 0) &&
animationQueue.Count > 0)
{
BeginNewAnim(animationQueue.Dequeue());
return;
}
currentAnim = anim;
clipLoopCount = 0; // Reset loop counter
elapsedClipTime = 0;
// Set first frame to play
if (currentAnim.FrameOffset > 0)
{
currentFrame = currentAnim.Clip.startFrame + currentAnim.FrameOffset;
if (currentFrame >= currentAnim.Clip.endFrame)
{
currentFrame = currentAnim.Clip.endFrame - 1;
Debug.LogWarning("Attempted to offset frame out of clip range.");
}
}
else if (currentAnim.FrameOffset < 0)
{
currentFrame = currentAnim.Clip.endFrame + currentAnim.FrameOffset - 1;
if (currentFrame < currentAnim.Clip.startFrame)
{
currentFrame = currentAnim.Clip.startFrame;
Debug.LogWarning("Attempted to offset frame out of clip range.");
}
}
else
{
currentFrame = currentAnim.Clip.startFrame;
}
// isPlaying set to false only when SingleFrame play type with 0 or less MaxCount
if (currentAnim.PlayType == PlayType.SingleFrame && currentAnim.MaxCount <= 0)
{
IsPlaying = false;
}
else
{
IsPlaying = true;
}
}
public void PlayClip<T>(T clipEnum, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null) where T : Enum
{
PlayClip(Convert.ToInt32(clipEnum), playType, startFrameOffset, maxCount, maxPlayTime, onStart, onEnd, onExit);
}
public void PlayClip(string clipName, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null)
{
if (UnimData.clipIndexByClipName.ContainsKey(clipName))
{
PlayClip(UnimData.clipIndexByClipName[clipName], playType, startFrameOffset, maxCount, maxPlayTime,
onStart,
onEnd, onExit);
}
else
{
Debug.LogError($"Clip name '{clipName}' does not exist.");
}
}
public void PlayClip(int clipIndex, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null)
{
if (clipIndex >= 0 && clipIndex < UnimData.clips.Length)
{
ClearAnimationQueue();
BeginNewAnim(new PlayableAnimation(UnimData.clips[clipIndex], playType, startFrameOffset, maxCount,
maxPlayTime, onStart,
onEnd, onExit));
}
else
{
Debug.LogError($"Index out of clip range");
}
}
public void Stop()
{
ClearAnim();
}
public void QueueStop()
{
animationQueue.Enqueue(new PlayableAnimation(null, maxCount: -1)); // Specific parameters to trigger stop
}
private void ClearAnim()
{
ClearAnimationQueue();
currentAnim = null;
clipLoopCount = 0;
elapsedClipTime = 0;
currentFrame = 0;
IsPlaying = false;
}
public void QueueClip<T>(T clipEnum, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null) where T : Enum
{
QueueClip(Convert.ToInt32(clipEnum), playType, startFrameOffset, maxCount, maxPlayTime,
onStart, onEnd, onExit);
}
public void QueueClip(string clipName, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null)
{
if (UnimData.clipIndexByClipName.ContainsKey(clipName))
{
QueueClip(UnimData.clipIndexByClipName[clipName], playType, startFrameOffset, maxCount, maxPlayTime,
onStart, onEnd, onExit);
}
else
{
Debug.LogError($"Clip name '{clipName}' does not exist.");
}
}
public void QueueClip(int clipIndex, PlayType playType, int startFrameOffset = 0, int maxCount = -1,
float maxPlayTime = Mathf.Infinity, Action onStart = null, Action onEnd = null, Action onExit = null)
{
// Play queued animation immediately if nothing else is queued or playing
if (animationQueue.Count <= 0 && IsPlaying == false)
{
PlayClip(clipIndex, playType, startFrameOffset, maxCount, maxPlayTime, onStart, onEnd, onExit);
return;
}
animationQueue.Enqueue(new PlayableAnimation(UnimData.clips[clipIndex], playType, startFrameOffset,
maxCount,
maxPlayTime, onStart,
onEnd, onExit));
}
public virtual void ClearAnimationQueue()
{
animationQueue.Clear();
}