-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
416 lines (350 loc) · 10.4 KB
/
index.js
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
var EventEmitter = require('events').EventEmitter,
inherits = require('inherits'),
raf = require('raf'),
methods;
//the same as off window unless polyfilled or in node
var defaultRAFObject = {
requestAnimationFrame: raf,
cancelAnimationFrame: raf.cancel
};
function returnTrue(){ return true; }
//manage FPS if < 60, else return true;
function makeThrottle(fps){
var delay = 1000/fps;
var lastTime = Date.now();
if( fps<=0 || fps === Infinity ){
return returnTrue;
}
//if an fps throttle has been set then we'll assume
//it natively runs at 60fps,
var half = Math.ceil(1000 / 60) / 2;
return function(){
//if a custom fps is requested
var now = Date.now();
//is this frame within 8.5ms of the target?
//if so then next frame is gonna be too late
if(now - lastTime < delay - half){
return false;
}
lastTime = now;
return true;
};
}
/**
* Animitter provides event-based loops for the browser and node,
* using `requestAnimationFrame`
* @param {Object} [opts]
* @param {Number} [opts.fps=Infinity] the framerate requested, defaults to as fast as it can (60fps on window)
* @param {Number} [opts.delay=0] milliseconds delay between invoking `start` and initializing the loop
* @param {Object} [opts.requestAnimationFrameObject=global] the object on which to find `requestAnimationFrame` and `cancelAnimationFrame` methods
* @param {Boolean} [opts.fixedDelta=false] if true, timestamps will pretend to be executed at fixed intervals always
* @constructor
*/
function Animitter( opts ){
opts = opts || {};
this.__delay = opts.delay || 0;
/** @expose */
this.fixedDelta = !!opts.fixedDelta;
/** @expose */
this.frameCount = 0;
/** @expose */
this.deltaTime = 0;
/** @expose */
this.elapsedTime = 0;
/** @private */
this.__running = false;
/** @private */
this.__completed = false;
this.setFPS(opts.fps || Infinity);
this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject);
}
inherits(Animitter, EventEmitter);
function onStart(scope){
var now = Date.now();
var rAFID;
//dont let a second animation start on the same object
//use *.on('update',fn)* instead
if(scope.__running){
return scope;
}
exports.running += 1;
scope.__running = true;
scope.__lastTime = now;
scope.deltaTime = 0;
//emit **start** once at the beginning
scope.emit('start', scope.deltaTime, 0, scope.frameCount);
var lastRAFObject = scope.requestAnimationFrameObject;
var drawFrame = function(){
if(lastRAFObject !== scope.requestAnimationFrameObject){
//if the requestAnimationFrameObject switched in-between,
//then re-request with the new one to ensure proper update execution context
//i.e. VRDisplay#submitFrame() may only be requested through VRDisplay#requestAnimationFrame(drawFrame)
lastRAFObject = scope.requestAnimationFrameObject;
scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
return;
}
if(scope.__isReadyForUpdate()){
scope.update();
}
if(scope.__running){
rAFID = scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
} else {
scope.requestAnimationFrameObject.cancelAnimationFrame(rAFID);
}
};
scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
return scope;
}
methods = {
//EventEmitter Aliases
off : EventEmitter.prototype.removeListener,
trigger : EventEmitter.prototype.emit,
/**
* stops the animation and marks it as completed
* @emit Animitter#complete
* @returns {Animitter}
*/
complete: function(){
this.stop();
this.__completed = true;
this.emit('complete', this.frameCount, this.deltaTime);
return this;
},
/**
* stops the animation and removes all listeners
* @emit Animitter#stop
* @returns {Animitter}
*/
dispose: function(){
this.stop();
this.removeAllListeners();
return this;
},
/**
* get milliseconds between the last 2 updates
*
* @return {Number}
*/
getDeltaTime: function(){
return this.deltaTime;
},
/**
* get the total milliseconds that the animation has ran.
* This is the cumlative value of the deltaTime between frames
*
* @return {Number}
*/
getElapsedTime: function(){
return this.elapsedTime;
},
/**
* get the instances frames per second as calculated by the last delta
*
* @return {Number}
*/
getFPS: function(){
return this.deltaTime > 0 ? 1000 / this.deltaTime : 0;
if(this.deltaTime){
return 1000 / this.deltaTime;
}
},
/**
* get the explicit FPS limit set via `Animitter#setFPS(fps)` or
* via the initial `options.fps` property
*
* @returns {Number} either as set or Infinity
*/
getFPSLimit: function(){
return this.__fps;
},
/**
* get the number of frames that have occurred
*
* @return {Number}
*/
getFrameCount: function(){
return this.frameCount;
},
/**
* get the object providing `requestAnimationFrame`
* and `cancelAnimationFrame` methods
* @return {Object}
*/
getRequestAnimationFrameObject: function(){
return this.requestAnimationFrameObject;
},
/**
* is the animation loop active
*
* @return {boolean}
*/
isRunning: function(){
return this.__running;
},
/**
* is the animation marked as completed
*
* @return {boolean}
*/
isCompleted: function(){
return this.__completed;
},
/**
* reset the animation loop, marks as incomplete,
* leaves listeners intact
*
* @emit Animitter#reset
* @return {Animitter}
*/
reset: function(){
this.stop();
this.__completed = false;
this.__lastTime = 0;
this.deltaTime = 0;
this.elapsedTime = 0;
this.frameCount = 0;
this.emit('reset', 0, 0, this.frameCount);
return this;
},
/**
* set the framerate for the animation loop
*
* @param {Number} fps
* @return {Animitter}
*/
setFPS: function(fps){
this.__fps = fps;
this.__isReadyForUpdate = makeThrottle(fps);
return this;
},
/**
* set the object that will provide `requestAnimationFrame`
* and `cancelAnimationFrame` methods to this instance
* @param {Object} object
* @return {Animitter}
*/
setRequestAnimationFrameObject: function(object){
if(typeof object.requestAnimationFrame !== 'function' || typeof object.cancelAnimationFrame !== 'function'){
throw new Error("Invalid object provide to `setRequestAnimationFrameObject`");
}
this.requestAnimationFrameObject = object;
return this;
},
/**
* start an animation loop
* @emit Animitter#start
* @return {Animitter}
*/
start: function(){
var self = this;
if(this.__delay){
setTimeout(function(){
onStart(self);
}, this.__delay);
} else {
onStart(this);
}
return this;
},
/**
* stops the animation loop, does not mark as completed
*
* @emit Animitter#stop
* @return {Animitter}
*/
stop: function(){
if( this.__running ){
this.__running = false;
exports.running -= 1;
this.emit('stop', this.deltaTime, this.elapsedTime, this.frameCount);
}
return this;
},
/**
* update the animation loop once
*
* @emit Animitter#update
* @return {Animitter}
*/
update: function(){
this.frameCount++;
/** @private */
var now = Date.now();
this.__lastTime = this.__lastTime || now;
this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime;
this.elapsedTime += this.deltaTime;
this.__lastTime = now;
this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount);
return this;
}
};
for(var method in methods){
Animitter.prototype[method] = methods[method];
}
/**
* create an animitter instance,
* @param {Object} [options]
* @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number )
* @returns {Animitter}
*/
function createAnimitter(options, fn){
if( arguments.length === 1 && typeof options === 'function'){
fn = options;
options = {};
}
var _instance = new Animitter( options );
if( fn ){
_instance.on('update', fn);
}
return _instance;
}
module.exports = exports = createAnimitter;
/**
* create an animitter instance,
* where the scope is bound in all functions
* @param {Object} [options]
* @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number )
* @returns {Animitter}
*/
exports.bound = function(options, fn){
var loop = createAnimitter(options, fn),
functionKeys = functions(Animitter.prototype),
hasBind = !!Function.prototype.bind,
fnKey;
for(var i=0; i<functionKeys.length; i++){
fnKey = functionKeys[i];
loop[fnKey] = hasBind ? loop[fnKey].bind(loop) : bind(loop[fnKey], loop);
}
return loop;
};
exports.Animitter = Animitter;
/**
* if true, all `Animitter` instances will behave as if `options.fixedDelta = true`
*/
exports.globalFixedDelta = false;
//helpful to inherit from when using bundled
exports.EventEmitter = EventEmitter;
//keep a global counter of all loops running, helpful to watch in dev tools
exports.running = 0;
function bind(fn, scope){
if(typeof fn.bind === 'function'){
return fn.bind(scope);
}
return function(){
return fn.apply(scope, arguments);
};
}
function functions(obj){
var keys = Object.keys(obj);
var arr = [];
for(var i=0; i<keys.length; i++){
if(typeof obj[keys[i]] === 'function'){
arr.push(keys[i]);
}
}
return arr;
}
//polyfill Date.now for real-old browsers
Date.now = Date.now || function now() {
return new Date().getTime();
};