-
Notifications
You must be signed in to change notification settings - Fork 52
/
rive.ts
3030 lines (2700 loc) · 89.2 KB
/
rive.ts
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 * as rc from "./rive_advanced.mjs";
import packageData from "package.json";
import { Animation } from "./animation";
import { registerTouchInteractions, sanitizeUrl, BLANK_URL } from "./utils";
// Note: Re-exporting a few types from rive_advanced.mjs to expose for high-level
// API usage without re-defining their type definition here. May want to revisit
// and see if we want to expose both types from rive.ts and rive_advanced.mjs in
// the future
export type {
FileAsset,
AudioAsset,
FontAsset,
ImageAsset,
} from "./rive_advanced.mjs";
/**
* Generic type for a parameterless void callback
*/
export type VoidCallback = () => void;
export type AssetLoadCallback = (
asset: rc.FileAsset,
bytes: Uint8Array,
) => Boolean;
interface SetupRiveListenersOptions {
isTouchScrollEnabled?: boolean;
}
/**
* Type for artboard bounds
*/
export type Bounds = rc.AABB;
// #region layout
// Fit options for the canvas
export enum Fit {
Cover = "cover",
Contain = "contain",
Fill = "fill",
FitWidth = "fitWidth",
FitHeight = "fitHeight",
None = "none",
ScaleDown = "scaleDown",
Layout = "layout",
}
// Alignment options for the canvas
export enum Alignment {
Center = "center",
TopLeft = "topLeft",
TopCenter = "topCenter",
TopRight = "topRight",
CenterLeft = "centerLeft",
CenterRight = "centerRight",
BottomLeft = "bottomLeft",
BottomCenter = "bottomCenter",
BottomRight = "bottomRight",
}
// Interface for the Layout static method contructor
export interface LayoutParameters {
fit?: Fit;
alignment?: Alignment;
layoutScaleFactor?: number;
minX?: number;
minY?: number;
maxX?: number;
maxY?: number;
}
// Alignment options for Rive animations in a HTML canvas
export class Layout {
// Runtime fit and alignment are accessed every frame, so we cache their
// values to save cycles
private cachedRuntimeFit: rc.Fit;
private cachedRuntimeAlignment: rc.Alignment;
public readonly fit: Fit;
public readonly alignment: Alignment;
public readonly layoutScaleFactor: number;
public readonly minX: number;
public readonly minY: number;
public readonly maxX: number;
public readonly maxY: number;
constructor(params?: LayoutParameters) {
this.fit = params?.fit ?? Fit.Contain;
this.alignment = params?.alignment ?? Alignment.Center;
this.layoutScaleFactor = params?.layoutScaleFactor ?? 1;
this.minX = params?.minX ?? 0;
this.minY = params?.minY ?? 0;
this.maxX = params?.maxX ?? 0;
this.maxY = params?.maxY ?? 0;
}
// Alternative constructor to build a Layout from an interface/object
static new({
fit,
alignment,
minX,
minY,
maxX,
maxY,
}: LayoutParameters): Layout {
console.warn(
"This function is deprecated: please use `new Layout({})` instead",
);
return new Layout({ fit, alignment, minX, minY, maxX, maxY });
}
/**
* Makes a copy of the layout, replacing any specified parameters
*/
public copyWith({
fit,
alignment,
layoutScaleFactor,
minX,
minY,
maxX,
maxY,
}: LayoutParameters): Layout {
return new Layout({
fit: fit ?? this.fit,
alignment: alignment ?? this.alignment,
layoutScaleFactor: layoutScaleFactor ?? this.layoutScaleFactor,
minX: minX ?? this.minX,
minY: minY ?? this.minY,
maxX: maxX ?? this.maxX,
maxY: maxY ?? this.maxY,
});
}
// Returns fit for the Wasm runtime format
public runtimeFit(rive: rc.RiveCanvas): rc.Fit {
if (this.cachedRuntimeFit) return this.cachedRuntimeFit;
let fit;
if (this.fit === Fit.Cover) fit = rive.Fit.cover;
else if (this.fit === Fit.Contain) fit = rive.Fit.contain;
else if (this.fit === Fit.Fill) fit = rive.Fit.fill;
else if (this.fit === Fit.FitWidth) fit = rive.Fit.fitWidth;
else if (this.fit === Fit.FitHeight) fit = rive.Fit.fitHeight;
else if (this.fit === Fit.ScaleDown) fit = rive.Fit.scaleDown;
else if (this.fit === Fit.Layout) fit = rive.Fit.layout;
else fit = rive.Fit.none;
this.cachedRuntimeFit = fit;
return fit;
}
// Returns alignment for the Wasm runtime format
public runtimeAlignment(rive: rc.RiveCanvas): rc.Alignment {
if (this.cachedRuntimeAlignment) return this.cachedRuntimeAlignment;
let alignment;
if (this.alignment === Alignment.TopLeft)
alignment = rive.Alignment.topLeft;
else if (this.alignment === Alignment.TopCenter)
alignment = rive.Alignment.topCenter;
else if (this.alignment === Alignment.TopRight)
alignment = rive.Alignment.topRight;
else if (this.alignment === Alignment.CenterLeft)
alignment = rive.Alignment.centerLeft;
else if (this.alignment === Alignment.CenterRight)
alignment = rive.Alignment.centerRight;
else if (this.alignment === Alignment.BottomLeft)
alignment = rive.Alignment.bottomLeft;
else if (this.alignment === Alignment.BottomCenter)
alignment = rive.Alignment.bottomCenter;
else if (this.alignment === Alignment.BottomRight)
alignment = rive.Alignment.bottomRight;
else alignment = rive.Alignment.center;
this.cachedRuntimeAlignment = alignment;
return alignment;
}
}
// #endregion
// #region runtime
// Callback type when looking for a runtime instance
export type RuntimeCallback = (rive: rc.RiveCanvas) => void;
// Runtime singleton; use getInstance to provide a callback that returns the
// Rive runtime
export class RuntimeLoader {
// Singleton helpers
private static runtime: rc.RiveCanvas;
// Flag to indicate that loading has started/completed
private static isLoading = false;
// List of callbacks for the runtime that come in while loading
private static callBackQueue: RuntimeCallback[] = [];
// Instance of the Rive runtime
private static rive: rc.RiveCanvas;
// Path to the Wasm file; default path works for testing only;
// if embedded wasm is used then this is never used.
private static wasmURL = `https://unpkg.com/${packageData.name}@${packageData.version}/rive.wasm`;
// Class is never instantiated
private constructor() {}
// Loads the runtime
private static loadRuntime(): void {
rc.default({
// Loads Wasm bundle
locateFile: () => RuntimeLoader.wasmURL,
})
.then((rive: rc.RiveCanvas) => {
RuntimeLoader.runtime = rive;
// Fire all the callbacks
while (RuntimeLoader.callBackQueue.length > 0) {
RuntimeLoader.callBackQueue.shift()?.(RuntimeLoader.runtime);
}
})
.catch((error) => {
// Capture specific error details
const errorDetails = {
message: error?.message || "Unknown error",
type: error?.name || "Error",
// Some browsers may provide additional WebAssembly-specific details
wasmError:
error instanceof WebAssembly.CompileError ||
error instanceof WebAssembly.RuntimeError,
originalError: error,
};
// Log detailed error for debugging
console.debug("Rive WASM load error details:", errorDetails);
// In case unpkg fails, or the wasm was not supported, we try to load the fallback module from jsdelivr.
// This `rive_fallback.wasm` is compiled to support older architecture.
// TODO: (Gordon): preemptively test browser support and load the correct wasm file. Then use jsdelvr only if unpkg fails.
const backupJsdelivrUrl = `https://cdn.jsdelivr.net/npm/${packageData.name}@${packageData.version}/rive_fallback.wasm`;
if (RuntimeLoader.wasmURL.toLowerCase() !== backupJsdelivrUrl) {
console.warn(
`Failed to load WASM from ${RuntimeLoader.wasmURL} (${errorDetails.message}), trying jsdelivr as a backup`,
);
RuntimeLoader.setWasmUrl(backupJsdelivrUrl);
RuntimeLoader.loadRuntime();
} else {
const errorMessage = [
`Could not load Rive WASM file from ${RuntimeLoader.wasmURL} or ${backupJsdelivrUrl}.`,
"Possible reasons:",
"- Network connection is down",
"- WebAssembly is not supported in this environment",
"- The WASM file is corrupted or incompatible",
"\nError details:",
`- Type: ${errorDetails.type}`,
`- Message: ${errorDetails.message}`,
`- WebAssembly-specific error: ${errorDetails.wasmError}`,
"\nTo resolve, you may need to:",
"1. Check your network connection",
"2. Set a new WASM source via RuntimeLoader.setWasmUrl()",
"3. Call RuntimeLoader.loadRuntime() again",
].join("\n");
console.error(errorMessage);
}
});
}
// Provides a runtime instance via a callback
public static getInstance(callback: RuntimeCallback): void {
// If it's not loading, start loading runtime
if (!RuntimeLoader.isLoading) {
RuntimeLoader.isLoading = true;
RuntimeLoader.loadRuntime();
}
if (!RuntimeLoader.runtime) {
RuntimeLoader.callBackQueue.push(callback);
} else {
callback(RuntimeLoader.runtime);
}
}
// Provides a runtime instance via a promise
public static awaitInstance(): Promise<rc.RiveCanvas> {
return new Promise<rc.RiveCanvas>((resolve) =>
RuntimeLoader.getInstance((rive: rc.RiveCanvas): void => resolve(rive)),
);
}
// Manually sets the wasm url
public static setWasmUrl(url: string): void {
RuntimeLoader.wasmURL = url;
}
// Gets the current wasm url
public static getWasmUrl(): string {
return RuntimeLoader.wasmURL;
}
}
// #endregion
// #region state machines
export enum StateMachineInputType {
Number = 56,
Trigger = 58,
Boolean = 59,
}
/**
* An input for a state machine
*/
export class StateMachineInput {
constructor(
public readonly type: StateMachineInputType,
private runtimeInput: rc.SMIInput,
) {}
/**
* Returns the name of the input
*/
public get name(): string {
return this.runtimeInput.name;
}
/**
* Returns the current value of the input
*/
public get value(): number | boolean {
return this.runtimeInput.value;
}
/**
* Sets the value of the input
*/
public set value(value: number | boolean) {
this.runtimeInput.value = value;
}
/**
* Fires a trigger; does nothing on Number or Boolean input types
*/
public fire(): void {
if (this.type === StateMachineInputType.Trigger) {
this.runtimeInput.fire();
}
}
}
export enum RiveEventType {
General = 128,
OpenUrl = 131,
}
class StateMachine {
/**
* Caches the inputs from the runtime
*/
public readonly inputs: StateMachineInput[] = [];
/**
* Runtime state machine instance
*/
public readonly instance: rc.StateMachineInstance;
/**
* @constructor
* @param stateMachine runtime state machine object
* @param instance runtime state machine instance object
*/
constructor(
private stateMachine: rc.StateMachine,
runtime: rc.RiveCanvas,
public playing: boolean,
private artboard: rc.Artboard,
) {
this.instance = new runtime.StateMachineInstance(stateMachine, artboard);
this.initInputs(runtime);
}
public get name(): string {
return this.stateMachine.name;
}
/**
* Returns a list of state names that have changed on this frame
*/
public get statesChanged(): string[] {
const names: string[] = [];
for (let i = 0; i < this.instance.stateChangedCount(); i++) {
names.push(this.instance.stateChangedNameByIndex(i));
}
return names;
}
/**
* Advances the state machine instance by a given time.
* @param time - the time to advance the animation by in seconds
*/
public advance(time: number) {
this.instance.advance(time);
}
/**
* Returns the number of events reported from the last advance call
* @returns Number of events reported
*/
public reportedEventCount(): number {
return this.instance.reportedEventCount();
}
/**
* Returns a RiveEvent object emitted from the last advance call at the given index
* of a list of potentially multiple events. If an event at the index is not found,
* undefined is returned.
* @param i index of the event reported in a list of potentially multiple events
* @returns RiveEvent or extended RiveEvent object returned, or undefined
*/
reportedEventAt(i: number): rc.OpenUrlEvent | rc.RiveEvent | undefined {
return this.instance.reportedEventAt(i);
}
/**
* Fetches references to the state machine's inputs and caches them
* @param runtime an instance of the runtime; needed for the SMIInput types
*/
private initInputs(runtime: rc.RiveCanvas): void {
// Fetch the inputs from the runtime if we don't have them
for (let i = 0; i < this.instance.inputCount(); i++) {
const input = this.instance.input(i);
this.inputs.push(this.mapRuntimeInput(input, runtime));
}
}
/**
* Maps a runtime input to it's appropriate type
* @param input
*/
private mapRuntimeInput(
input: rc.SMIInput,
runtime: rc.RiveCanvas,
): StateMachineInput {
if (input.type === runtime.SMIInput.bool) {
return new StateMachineInput(
StateMachineInputType.Boolean,
input.asBool(),
);
} else if (input.type === runtime.SMIInput.number) {
return new StateMachineInput(
StateMachineInputType.Number,
input.asNumber(),
);
} else if (input.type === runtime.SMIInput.trigger) {
return new StateMachineInput(
StateMachineInputType.Trigger,
input.asTrigger(),
);
}
}
/**
* Deletes the backing Wasm state machine instance; once this is called, this
* state machine is no more.
*/
public cleanup() {
this.instance.delete();
}
}
// #endregion
// #region animator
/**
* Manages animation
*/
class Animator {
/**
* Constructs a new animator
* @constructor
* @param runtime Rive runtime; needed to instance animations & state machines
* @param artboard the artboard that holds all animations and state machines
* @param animations optional list of animations
* @param stateMachines optional list of state machines
*/
constructor(
private runtime: rc.RiveCanvas,
private artboard: rc.Artboard,
private eventManager: EventManager,
public readonly animations: Animation[] = [],
public readonly stateMachines: StateMachine[] = [],
) {}
/**
* Adds animations and state machines by their names. If names are shared
* between animations & state machines, then the first one found will be
* created. Best not to use the same names for these in your Rive file.
* @param animatable the name(s) of animations and state machines to add
* @returns a list of names of the playing animations and state machines
*/
public add(
animatables: string | string[],
playing: boolean,
fireEvent = true,
): string[] {
animatables = mapToStringArray(animatables);
// If animatables is empty, play or pause everything
if (animatables.length === 0) {
this.animations.forEach((a) => (a.playing = playing));
this.stateMachines.forEach((m) => (m.playing = playing));
} else {
// Play/pause already instanced items, or create new instances
const instancedAnimationNames = this.animations.map((a) => a.name);
const instancedMachineNames = this.stateMachines.map((m) => m.name);
for (let i = 0; i < animatables.length; i++) {
const aIndex = instancedAnimationNames.indexOf(animatables[i]);
const mIndex = instancedMachineNames.indexOf(animatables[i]);
if (aIndex >= 0 || mIndex >= 0) {
if (aIndex >= 0) {
// Animation is instanced, play/pause it
this.animations[aIndex].playing = playing;
} else {
// State machine is instanced, play/pause it
this.stateMachines[mIndex].playing = playing;
}
} else {
// Try to create a new animation instance
const anim = this.artboard.animationByName(animatables[i]);
if (anim) {
const newAnimation = new Animation(
anim,
this.artboard,
this.runtime,
playing,
);
// Display the first frame of the specified animation
newAnimation.advance(0);
newAnimation.apply(1.0);
this.animations.push(newAnimation);
} else {
// Try to create a new state machine instance
const sm = this.artboard.stateMachineByName(animatables[i]);
if (sm) {
const newStateMachine = new StateMachine(
sm,
this.runtime,
playing,
this.artboard,
);
this.stateMachines.push(newStateMachine);
}
}
}
}
}
// Fire play/paused events for animations
if (fireEvent) {
if (playing) {
this.eventManager.fire({
type: EventType.Play,
data: this.playing,
});
} else {
this.eventManager.fire({
type: EventType.Pause,
data: this.paused,
});
}
}
return playing ? this.playing : this.paused;
}
/**
* Adds linear animations by their names.
* @param animatables the name(s) of animations to add
* @param playing whether animations should play on instantiation
*/
public initLinearAnimations(animatables: string[], playing: boolean) {
// Play/pause already instanced items, or create new instances
// This validation is kept to maintain compatibility with current behavior.
// But given that it this is called during artboard initialization
// it should probably be safe to remove.
const instancedAnimationNames = this.animations.map((a) => a.name);
for (let i = 0; i < animatables.length; i++) {
const aIndex = instancedAnimationNames.indexOf(animatables[i]);
if (aIndex >= 0) {
this.animations[aIndex].playing = playing;
} else {
// Try to create a new animation instance
const anim = this.artboard.animationByName(animatables[i]);
if (anim) {
const newAnimation = new Animation(
anim,
this.artboard,
this.runtime,
playing,
);
// Display the first frame of the specified animation
newAnimation.advance(0);
newAnimation.apply(1.0);
this.animations.push(newAnimation);
}
}
}
}
/**
* Adds state machines by their names.
* @param animatables the name(s) of state machines to add
* @param playing whether state machines should play on instantiation
*/
public initStateMachines(animatables: string[], playing: boolean) {
// Play/pause already instanced items, or create new instances
// This validation is kept to maintain compatibility with current behavior.
// But given that it this is called during artboard initialization
// it should probably be safe to remove.
const instancedStateMachineNames = this.stateMachines.map((a) => a.name);
for (let i = 0; i < animatables.length; i++) {
const aIndex = instancedStateMachineNames.indexOf(animatables[i]);
if (aIndex >= 0) {
this.stateMachines[aIndex].playing = playing;
} else {
// Try to create a new state machine instance
const sm = this.artboard.stateMachineByName(animatables[i]);
if (sm) {
const newStateMachine = new StateMachine(
sm,
this.runtime,
playing,
this.artboard,
);
this.stateMachines.push(newStateMachine);
} else {
// In order to maintain compatibility with current behavior, if a state machine is not found
// we look for an animation with the same name
this.initLinearAnimations([animatables[i]], playing);
}
}
}
}
/**
* Play the named animations/state machines
* @param animatables the names of the animations/machines to play; plays all if empty
* @returns a list of the playing items
*/
public play(animatables: string | string[]): string[] {
return this.add(animatables, true);
}
/**
* Pauses named animations and state machines, or everything if nothing is
* specified
* @param animatables names of the animations and state machines to pause
* @returns a list of names of the animations and state machines paused
*/
public pause(animatables: string[]): string[] {
return this.add(animatables, false);
}
/**
* Set time of named animations
* @param animations names of the animations to scrub
* @param value time scrub value, a floating point number to which the playhead is jumped
* @returns a list of names of the animations that were scrubbed
*/
public scrub(animatables: string[], value: number): string[] {
const forScrubbing = this.animations.filter((a) =>
animatables.includes(a.name),
);
forScrubbing.forEach((a) => (a.scrubTo = value));
return forScrubbing.map((a) => a.name);
}
/**
* Returns a list of names of all animations and state machines currently
* playing
*/
public get playing(): string[] {
return this.animations
.filter((a) => a.playing)
.map((a) => a.name)
.concat(this.stateMachines.filter((m) => m.playing).map((m) => m.name));
}
/**
* Returns a list of names of all animations and state machines currently
* paused
*/
public get paused(): string[] {
return this.animations
.filter((a) => !a.playing)
.map((a) => a.name)
.concat(this.stateMachines.filter((m) => !m.playing).map((m) => m.name));
}
/**
* Stops and removes all named animations and state machines
* @param animatables animations and state machines to remove
* @returns a list of names of removed items
*/
public stop(animatables?: string[] | string): string[] {
animatables = mapToStringArray(animatables);
// If nothing's specified, wipe them out, all of them
let removedNames: string[] = [];
// Stop everything
if (animatables.length === 0) {
removedNames = this.animations
.map((a) => a.name)
.concat(this.stateMachines.map((m) => m.name));
// Clean up before emptying the arrays
this.animations.forEach((a) => a.cleanup());
this.stateMachines.forEach((m) => m.cleanup());
// Empty out the arrays
this.animations.splice(0, this.animations.length);
this.stateMachines.splice(0, this.stateMachines.length);
} else {
// Remove only the named animations/state machines
const animationsToRemove = this.animations.filter((a) =>
animatables.includes(a.name),
);
animationsToRemove.forEach((a) => {
a.cleanup();
this.animations.splice(this.animations.indexOf(a), 1);
});
const machinesToRemove = this.stateMachines.filter((m) =>
animatables.includes(m.name),
);
machinesToRemove.forEach((m) => {
m.cleanup();
this.stateMachines.splice(this.stateMachines.indexOf(m), 1);
});
removedNames = animationsToRemove
.map((a) => a.name)
.concat(machinesToRemove.map((m) => m.name));
}
this.eventManager.fire({
type: EventType.Stop,
data: removedNames,
});
// Return the list of animations removed
return removedNames;
}
/**
* Returns true if at least one animation is active
*/
public get isPlaying(): boolean {
return (
this.animations.reduce((acc, curr) => acc || curr.playing, false) ||
this.stateMachines.reduce((acc, curr) => acc || curr.playing, false)
);
}
/**
* Returns true if all animations are paused and there's at least one animation
*/
public get isPaused(): boolean {
return (
!this.isPlaying &&
(this.animations.length > 0 || this.stateMachines.length > 0)
);
}
/**
* Returns true if there are no playing or paused animations/state machines
*/
public get isStopped(): boolean {
return this.animations.length === 0 && this.stateMachines.length === 0;
}
/**
* If there are no animations or state machines, add the first one found
* @returns the name of the animation or state machine instanced
*/
public atLeastOne(playing: boolean, fireEvent = true): string {
let instancedName: string;
if (this.animations.length === 0 && this.stateMachines.length === 0) {
if (this.artboard.animationCount() > 0) {
// Add the first animation
this.add(
[(instancedName = this.artboard.animationByIndex(0).name)],
playing,
fireEvent,
);
} else if (this.artboard.stateMachineCount() > 0) {
// Add the first state machine
this.add(
[(instancedName = this.artboard.stateMachineByIndex(0).name)],
playing,
fireEvent,
);
}
}
return instancedName;
}
/**
* Checks if any animations have looped and if so, fire the appropriate event
*/
public handleLooping() {
for (const animation of this.animations.filter((a) => a.playing)) {
// Emit if the animation looped
if (animation.loopValue === 0 && animation.loopCount) {
animation.loopCount = 0;
// This is a one-shot; if it has ended, delete the instance
this.stop(animation.name);
} else if (animation.loopValue === 1 && animation.loopCount) {
this.eventManager.fire({
type: EventType.Loop,
data: { animation: animation.name, type: LoopType.Loop },
});
animation.loopCount = 0;
}
// Wasm indicates a loop at each time the animation
// changes direction, so a full loop/lap occurs every
// two loop counts
else if (animation.loopValue === 2 && animation.loopCount > 1) {
this.eventManager.fire({
type: EventType.Loop,
data: { animation: animation.name, type: LoopType.PingPong },
});
animation.loopCount = 0;
}
}
}
/**
* Checks if states have changed in state machines and fires a statechange
* event
*/
public handleStateChanges() {
const statesChanged: string[] = [];
for (const stateMachine of this.stateMachines.filter((sm) => sm.playing)) {
statesChanged.push(...stateMachine.statesChanged);
}
if (statesChanged.length > 0) {
this.eventManager.fire({
type: EventType.StateChange,
data: statesChanged,
});
}
}
public handleAdvancing(time: number) {
this.eventManager.fire({
type: EventType.Advance,
data: time,
});
}
}
// #endregion
// #region events
/**
* Supported event types triggered in Rive
*/
export enum EventType {
Load = "load",
LoadError = "loaderror",
Play = "play",
Pause = "pause",
Stop = "stop",
Loop = "loop",
Draw = "draw",
Advance = "advance",
StateChange = "statechange",
RiveEvent = "riveevent",
AudioStatusChange = "audiostatuschange", // internal event. TODO: split
}
export type RiveEventPayload = rc.RiveEvent | rc.OpenUrlEvent;
// Event reported by Rive for significant events during animation playback (i.e. play, pause, stop, etc.),
// as well as for custom Rive events reported from the state machine defined at design-time.
export interface Event {
type: EventType;
data?: string | string[] | LoopEvent | number | RiveEventPayload | RiveFile;
}
/**
* Looping types: one-shot, loop, and ping-pong
*/
export enum LoopType {
OneShot = "oneshot", // has value 0 in runtime
Loop = "loop", // has value 1 in runtime
PingPong = "pingpong", // has value 2 in runtime
}
/**
* Loop events are returned through onloop callbacks
*/
export interface LoopEvent {
animation: string;
type: LoopType;
}
/**
* Loop events are returned through onloop callbacks
*/
export type EventCallback = (event: Event) => void;
/**
* Event listeners registered with the event manager
*/
export interface EventListener {
type: EventType;
callback: EventCallback;
}
/**
* FPS Reporting through callbacks sent to the WASM runtime
*/
export type FPSCallback = (fps: number) => void;
// Manages Rive events and listeners
class EventManager {
constructor(private listeners: EventListener[] = []) {}
// Gets listeners of specified type
private getListeners(type: EventType): EventListener[] {
return this.listeners.filter((e) => e.type === type);
}
// Adds a listener
public add(listener: EventListener): void {
if (!this.listeners.includes(listener)) {
this.listeners.push(listener);
}
}
/**
* Removes a listener
* @param listener the listener with the callback to be removed
*/
public remove(listener: EventListener): void {
// We can't simply look for the listener as it'll be a different instance to
// one originally subscribed. Find all the listeners of the right type and
// then check their callbacks which should match.
for (let i = 0; i < this.listeners.length; i++) {
const currentListener = this.listeners[i];
if (currentListener.type === listener.type) {
if (currentListener.callback === listener.callback) {
this.listeners.splice(i, 1);
break;
}
}
}
}
/**
* Clears all listeners of specified type, or every listener if no type is
* specified
* @param type the type of listeners to clear, or all listeners if not
* specified
*/
public removeAll(type?: EventType) {
if (!type) {
this.listeners.splice(0, this.listeners.length);
} else {
this.listeners
.filter((l) => l.type === type)
.forEach((l) => this.remove(l));
}
}
// Fires an event
public fire(event: Event): void {
const eventListeners = this.getListeners(event.type);
eventListeners.forEach((listener) => listener.callback(event));
}
}
// #endregion
// #region Manages a queue of tasks
// A task in the queue; will fire the action when the queue is processed; will
// also optionally fire an event.
export interface Task {
action?: VoidCallback;
event?: Event;
}
// Manages a queue of tasks
class TaskQueueManager {
private queue: Task[] = [];
constructor(private eventManager: EventManager) {}
// Adds a task top the queue
public add(task: Task): void {
this.queue.push(task);
}