-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimation.js
More file actions
640 lines (634 loc) · 18.8 KB
/
Animation.js
File metadata and controls
640 lines (634 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/**
* Represents a single path keyframe
*/
class Frame
{
/**
The time position of the keyframe
*/
time = 0;
/**
Fill colour of the path
*/
fill = "#000000";
/**
Path data in SVG path format
*/
path = "";
}
/**
* Represents a single part (path) with keyframe animation
*/
class AnimatedPath
{
/**
Array of keyframes
*/
frames = [];
/** Contains the "static" elements of the path data */
path = [];
/**
Current fill colour
*/
fill = "#000000";
/**
Animation length
*/
length = 0;
/**
* Splits a string into individual chunks likely to contain path information.
* @param {string} path The path string to be chunked.
* @returns {string[]} The processed, chunked path.
*/
static chunk(path)
{
const out = [];
// this accumulates current piece
let buf = "";
// list of all path commands
let cmds =["l","v","h","c","q","z","m","a"];
// numeric param symbols
let nums =["0","1","2","3","4","5","6","7","8","9",".","-"];
for(let i=0;i<path.length;i++)
{
let c = path[i];
// if hit anything that's not a number or a command, split off
if(!nums.includes(c) && !cmds.includes(c.toLowerCase()))
{
out.push(buf);
buf ="";
}
// else accumulate
else
{
buf+=c;
}
}
// split off current buffer
out.push(buf);
return out;
}
/**
* Compares a list of chunked paths and determines which elements are static and which are varialble.
* @param {string[][]} paths List of chunked paths, each with the same number of commands.
* @returns {[string[], Number[][]]} A list of strings (constant parts) and values (one per frame of an animation).
*/
static diff(paths)
{
// keeps a list of unchanging items
const strings = [];
// keeps a list of items that change in keyframes
const values = new Array(paths.length);
// init an array of arrays for each frame
for(let i =0;i<paths.length;i++ )
{
values[i]= [];
}
// accumulator
let cur_str ="";
// go through every separate chunk in the first frame
// and find out if it changes in any other frames
paths[0].forEach((chunk, c)=>{
// this keeps track whether a different value was found
let eq = true;
// this is the reference value to compare to
let refval = paths[0][c];
// go through every frame
for(let i =0;i<paths.length;i++ )
{
// compare the corresponding chunk in this frame
if(paths[i][c]!=refval)
{
// if difference found, set the flag
eq = false;
}
}
// if no difference found, add the chunk as is to accumulator
if(eq)
{
cur_str += chunk +" ";
}
else
{
// otherwise, split the accumulator off
strings.push(cur_str);
cur_str = "";
// insert the changed chunk as a new value in each frame
for(let i =0;i<paths.length;i++ )
{
let val = parseFloat(paths[i][c]);
values[i].push(val);
}
}
});
// split the last accumulator off and finish
strings.push(cur_str);
return [strings, values];
}
/**
* Constructs a string by interleaving a list of strings and a list of values.
* @param {string[]} strings An array of strings, should be 1 item longer than the values.
* @param {Number[]} values An array of values, should be 1 item shorter than the strings.
* @returns {string} a complete string.
*/
static stitch(strings, values)
{
const result = [strings[0]];
values.forEach((val, i) => {
result.push(val,strings[i+1]);
});
return result.join(" ");
}
/**
* Provides interpolated list of values given two lists and a value indicating the amount to lerp.
* @param {Number[]} a first set of values
* @param {Number[]} b second set of values
* @param {Number} t amount to interpolate
* @returns a list of values of equal size
*/
static tween(a,b,t)
{
const c = [];
// basically lerp between corresponding values in the two arrays
a.forEach((val,i)=>{
c.push(a[i]+(b[i]-val)*t);
});
return c;
}
/**
* Tweens between two fill values. Currently only supports #RRGGBB strings.
* @param {*} a
* @param {*} b
* @param {*} t
* @returns
*/
static tweenFill(ctx, a,b,t)
{
if(typeof a == "string" && typeof b == "string")
{
return AnimatedPath.tweenHex(a,b,t);
}
if(a.type)
{
let graddef = AnimatedPath.tweenGradient(a,b,t);
switch(graddef.type)
{
case "linear":
{
let grad = ctx.createLinearGradient(...graddef.coords);
for(let i=0;i<graddef.stops.length;i++)
{
grad.addColorStop(graddef.stops[i],graddef.colours[i]);
}
return grad;
}
case "radial":
{
let grad = ctx.createRadialGradient(...graddef.coords);
for(let i=0;i<graddef.stops.length;i++)
{
grad.addColorStop(graddef.stops[i],graddef.colours[i]);
}
return grad;
}
}
}
}
static tweenGradient(a,b,t)
{
let finalcoords=[];
let finalcolours=[];
let finalstops = [];
a.coords.forEach((val,i)=>{
finalcoords.push(a.coords[i]+(b.coords[i]-a.coords[i])*t);
});
a.colours.forEach((val,i)=>{
finalcolours.push(AnimatedPath.tweenHex(a.colours[i],b.colours[i],t));
});
a.stops.forEach((val,i)=>{
finalstops.push(a.stops[i]+(b.stops[i]-a.stops[i])*t);
});
return {
type: a.type,
coords:finalcoords,
stops:finalstops,
colours:finalcolours
};
}
/**
* Tweens between two hex colours
* @param {string} a first colour as #RRGGBB
* @param {string} b second colour as #RRGGBB
* @param {string} t amount to interpolate
* @returns interpolated colour as #RRGGBB or #000000 if invalid format
*/
static tweenHex(a,b,t)
{
if(a[0]!="#")
{
return "#000000";
}
let aa = 255;
let ba = 255;
if(a.length>=9)
{
aa=parseInt(a.substring(7,9),16);
ba=parseInt(b.substring(7,9),16);
}
let ar = parseInt(a.substring(1,3),16);
let ag = parseInt(a.substring(3,5),16);
let ab = parseInt(a.substring(5,7),16);
let br = parseInt(b.substring(1,3),16);
let bg = parseInt(b.substring(3,5),16);
let bb = parseInt(b.substring(5,7),16);
let R = ar + (br-ar)*t;
let G = ag + (bg-ag)*t;
let B = ab + (bb-ab)*t;
let A = aa + (ba-aa)*t;
return AnimatedPath.rgbToHex(Math.floor(R), Math.floor(G), Math.floor(B), Math.floor(A));
}
/**
* Converts 3 values into hexadecimal RGB
* @param {number} r
* @param {number} g
* @param {number} b
* @param {number} a
* @returns
*/
static rgbToHex(r, g, b, a=255)
{
return "#" + AnimatedPath.componentToHex(r) + AnimatedPath.componentToHex(g) + AnimatedPath.componentToHex(b) + AnimatedPath.componentToHex(a);
}
/**
* Converts a single value to hex.
* @param {number} c
* @returns
*/
static componentToHex(c)
{
if(c<0 || c > 255)
{
console.warn("Invalid RGB component value <"+c+">.")
c=0;
}
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
/**
* Creates an AnimatedPath out of an array of keyframes
* @param {Array} frames
* @returns
*/
static fromKeyFrames(frames)
{
let result = new AnimatedPath();
let paths = [];
// add the frames to the new object
frames.forEach((f)=>{
// also save the paths in parallel for processing
paths.push(f.path);
result.frames.push({
"time": f.time,
"fill":f.fill,
"rotation":(f.rotation ?? 0)
});
});
let chunked = [];
// chunk the paths
paths.forEach((p)=>{
chunked.push(AnimatedPath.chunk(p));
});
// process chunked paths to extract only the changing values
let output = AnimatedPath.diff(chunked);
// set the static path data
result.path = output[0];
// set the changing values
result.frames.forEach((f,i)=>{
f.values = output[1][i];
// update path animation length to the highest time value seen
result.length = f.time;
});
if(result.length==0)
{
let f0=result.frames[0];
result.frames.push({
"time": 1,
"fill":f0.fill,
"rotation":(f0.rotation ?? 0),
"values": f0.values
});
result.length = 1;
}
return result;
}
/**
* Locates the correct keyframes corresponding to the time given
* @param {number} t
* @returns an object containing:
* "a", the values for previous frame,
* "b", the values for next frame,
* "t", the interpolation parameter between the frames
*/
findFrames(t)
{
let a,b,dT
let i =0;
let dS = 1;
// go through all frames
for(i=0; i<this.frames.length-1;i++)
{
// candidate a & b
a=this.frames[i];
b=this.frames[i+1];
// calculate how far ahead of "a"
dT = t-a['time'];
// time between "a" and "b"
dS = b['time']-a['time'];
// calculate lerp value between the two
dT/=dS;
// return everything if the candidate b is after T
if(t<=b['time'])
break;
}
return {
"a": a['values'],
"ra":a['rotation'],
"fa":a['fill'],
"b": b['values'],
"rb":b['rotation'],
"fb":b['fill'],
"t":dT
};
}
}
/**
* Represents one complete animation containing keyframed paths.
*/
class VectorAnimation
{
/**
* Position in the timeline
*/
current_time = 0;
/**
* Length of the animation in seconds
*/
length = 0.1;
/**
* Array of AnimatedPaths contained in the animation
*/
paths = [];
/**
* Name used to refer to the animation
*/
name = "";
/**
* Time left on the tint/fade effect
*/
fade_time = 0;
/**
* Full duration of the fade effect
*/
fade_start = 0;
/**
* Colour used for the fade effect
*/
fade_fill="";
/**
* Keeps track of the amount of time the animation has looped so far.
*/
loop_count = 0;
/**
* Shorthand check whether the animation has looped at least once.
*/
finished = false;
/**
* Creates a new instance of an animation given a list of animated paths and a name
* @param {AnimatedPath[]} paths
* @param {string} name
*/
constructor(paths, name)
{
this.name = name;
paths.forEach((p)=>this.paths.push(p));
// fix the animation's length to the length of the first path given
this.length = this.paths[0].length;
}
/**
* Draws the animation in its current state
* Drawing origin is 0,0 - translate the canvas to draw in a different location.
* @param {CanvasRenderingContext2D} ctx - canvas context to use
*/
draw(ctx)
{
// draw each path
for(let i =0;i<this.paths.length;i++)
{
let path = this.paths[i];
// get the two frames to tween
let frame=path.findFrames(this.current_time);
let values = AnimatedPath.tween(frame.a, frame.b, frame.t);
// tween rotation
let rot = frame.ra + (frame.rb-frame.ra)*frame.t;
// generate the SVG path commands from the path and the keyframe values
let strpath = AnimatedPath.stitch(path.path, values);
// tween fill
let fill = AnimatedPath.tweenFill(ctx,frame.fa, frame.fb, frame.t);
// render the path in its fill colour
ctx.fillStyle = fill;
// rotate
ctx.rotate(rot/180*Math.PI);
ctx.fill(new Path2D(strpath));
// if a fade is applied, also render the fade
if(this.fade_time>0 && this.fade_start > 0)
{
// calculate the fade intensity
let a = this.fade_time / this.fade_start;
ctx.fillStyle = "rgb("+this.fade_fill+" / " + a + ")";
ctx.fill(new Path2D(strpath));
}
// unrotate
ctx.rotate(-rot*Math.PI/180);
}
}
/**
* Update animation state
* @param {number} dT - elapsed time
*/
update(dT)
{
// progress timeline and fade timer
this.current_time+=dT;
this.fade_time-=dT;
// set fade params to zero if fade expired
if(this.fade_time<=0)
{
this.fade_time=0;
this.fade_start = 0;
}
// wrap around timeline if past length
while(this.current_time>this.length)
{
this.current_time-=this.length;
this.loop_count++;
this.finished=true;
}
}
/**
* Applies a fading colour tint effect
* @param {string} colour - colour to use, in decimal "R G B" format
* @param {number} time - seconds before the effect fully fades out
* @param {number} a - intensity of the effect at the start from 0 to 1, where 1 is solid colour
*/
applyFade(colour, time, a=1)
{
this.fade_fill=colour;
this.fade_time=time;
// if a is not 1, this sets a fake "start" time to start out the effect at the desired intensity
this.fade_start=time / a;
}
/**
* Copies fade effect values from another animation.
* @param {VectorAnimation} other
*/
cloneFadeParams(other)
{
this.fade_fill=other.fade_fill;
this.fade_start=other.fade_start;
this.fade_time=other.fade_time;
}
/**
* Resets all runtime values of the animation to defaults.
*/
reset()
{
this.loop_count=0;
this.finished=false;
this.current_time=0;
this.fade_fill="255 255 255";
this.fade_start=0;
this.fade_time=0;
}
}
/**
* Represents a complete graphics object with a collection of VectorAnimations
*/
class VectorSprite
{
/**
* Contains the VectorAnimations, referenced by name
*/
animations = {};
/**
* Currently playing animation.
*/
currentAnimation=null;
/**
* The animation to be played at the start or when the current animation finishes.
*/
default_animation="idle";
/**
* The amount of times the current animation is to be looped.
*/
loop_count=0;
/**
* Creates a new instance given a set of animations
* @param {VectorAnimation[]} animations
*/
constructor(animations)
{
// add each animation by its name
animations.forEach((a)=>{
this.animations[a.name] = a;
});
this.play(this.default_animation);
}
/**
* Sets the sprite to play an animation, optionally a fixed number of times before switching to the default animation.
* @param {string} name Animation name.
* @param {number} loopcount Amount of times to loop the animation, default is 0 which loops the animation indefinitely.
* @returns
*/
play(name,loopcount=0)
{
if(!this.animations[name])
{
console.error("Animation <"+name+"> not found in sprite.");
return;
}
// set and init the requested animation
this.currentAnimation=this.animations[name];
this.currentAnimation.reset();
this.loop_count = loopcount;
// copy ongoing information if possible like fade timers
let old = this.currentAnimation;
if(old)
{
this.currentAnimation.cloneFadeParams(old);
}
}
/**
* Applies a fading colour tint effect to the sprite.
* @param {string} colour - colour to use, in decimal "R G B" format
* @param {number} time - seconds before the effect fully fades out
* @param {number} a - intensity of the effect at the start from 0 to 1, where 1 is solid colour
*/
applyFade(colour, time, a=1)
{
if(this.currentAnimation)
{
this.currentAnimation.applyFade(colour,time,a);
}
}
/**
* Updates the state of the sprite: animation, loop counts etc
* @param {number} dT
* @returns
*/
update(dT)
{
if(!this.currentAnimation)
return;
this.currentAnimation.update(dT);
if(this.loop_count==0)
{
return;
}
if(this.currentAnimation.loop_count>=this.loop_count)
{
this.play(this.default_animation);
}
}
/**
* Renders the sprite on the given canvas.
* @param {CanvasRenderingContext2D} ctx
*/
draw(ctx)
{
if(!this.currentAnimation)
return;
this.currentAnimation.draw(ctx);
}
/**
* Creates a VectorSprite out of a raw JSON object
* @param {array} obj
* @returns
*/
static fromRawObject(obj)
{
let anims = [];
// get every animation by name
for(const [key, value] of Object.entries(obj))
{
let paths = [];
// create an AnimatedPath out of every path in the array and add
value.forEach((p,i)=>{
paths.push(AnimatedPath.fromKeyFrames(p));
});
// create an animation out of each set of paths and add to animations
anims.push(new VectorAnimation(paths, key));
}
// create and return the vector sprite
return new VectorSprite(anims);
}
}