forked from leapmotion/leapjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leap-0.6.4.js
9420 lines (8420 loc) · 272 KB
/
leap-0.6.4.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
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
/*!
* LeapJS v0.6.4
* http://github.com/leapmotion/leapjs/
*
* Copyright 2013 LeapMotion, Inc. and other contributors
* Released under the Apache-2.0 license
* http://github.com/leapmotion/leapjs/blob/master/LICENSE.txt
*/
;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var Pointable = require('./pointable'),
glMatrix = require("gl-matrix")
, vec3 = glMatrix.vec3
, mat3 = glMatrix.mat3
, mat4 = glMatrix.mat4
, _ = require('underscore');
var Bone = module.exports = function(finger, data) {
this.finger = finger;
this._center = null, this._matrix = null;
/**
* An integer code for the name of this bone.
*
* * 0 -- metacarpal
* * 1 -- proximal
* * 2 -- medial
* * 3 -- distal
* * 4 -- arm
*
* @member type
* @type {number}
* @memberof Leap.Bone.prototype
*/
this.type = data.type;
/**
* The position of the previous, or base joint of the bone closer to the wrist.
* @type {vector3}
*/
this.prevJoint = data.prevJoint;
/**
* The position of the next joint, or the end of the bone closer to the finger tip.
* @type {vector3}
*/
this.nextJoint = data.nextJoint;
/**
* The estimated width of the tool in millimeters.
*
* The reported width is the average width of the visible portion of the
* tool from the hand to the tip. If the width isn't known,
* then a value of 0 is returned.
*
* Pointable objects representing fingers do not have a width property.
*
* @member width
* @type {number}
* @memberof Leap.Pointable.prototype
*/
this.width = data.width;
var displacement = new Array(3);
vec3.sub(displacement, data.nextJoint, data.prevJoint);
this.length = vec3.length(displacement);
/**
*
* These fully-specify the orientation of the bone.
* See examples/threejs-bones.html for more info
* Three vec3s:
* x (red): The rotation axis of the finger, pointing outwards. (In general, away from the thumb )
* y (green): The "up" vector, orienting the top of the finger
* z (blue): The roll axis of the bone.
*
* Most up vectors will be pointing the same direction, except for the thumb, which is more rightwards.
*
* The thumb has one fewer bones than the fingers, but there are the same number of joints & joint-bases provided
* the first two appear in the same position, but only the second (proximal) rotates.
*
* Normalized.
*/
this.basis = data.basis;
};
Bone.prototype.left = function(){
if (this._left) return this._left;
this._left = mat3.determinant(this.basis[0].concat(this.basis[1]).concat(this.basis[2])) < 0;
return this._left;
};
/**
* The Affine transformation matrix describing the orientation of the bone, in global Leap-space.
* It contains a 3x3 rotation matrix (in the "top left"), and center coordinates in the fourth column.
*
* Unlike the basis, the right and left hands have the same coordinate system.
*
*/
Bone.prototype.matrix = function(){
if (this._matrix) return this._matrix;
var b = this.basis,
t = this._matrix = mat4.create();
// open transform mat4 from rotation mat3
t[0] = b[0][0], t[1] = b[0][1], t[2] = b[0][2];
t[4] = b[1][0], t[5] = b[1][1], t[6] = b[1][2];
t[8] = b[2][0], t[9] = b[2][1], t[10] = b[2][2];
t[3] = this.center()[0];
t[7] = this.center()[1];
t[11] = this.center()[2];
if ( this.left() ) {
// flip the basis to be right-handed
t[0] *= -1;
t[1] *= -1;
t[2] *= -1;
}
return this._matrix;
};
/**
* Helper method to linearly interpolate between the two ends of the bone.
*
* when t = 0, the position of prevJoint will be returned
* when t = 1, the position of nextJoint will be returned
*/
Bone.prototype.lerp = function(out, t){
vec3.lerp(out, this.prevJoint, this.nextJoint, t);
};
/**
*
* The center position of the bone
* Returns a vec3 array.
*
*/
Bone.prototype.center = function(){
if (this._center) return this._center;
var center = vec3.create();
this.lerp(center, 0.5);
this._center = center;
return center;
};
// The negative of the z-basis
Bone.prototype.direction = function(){
return [
this.basis[2][0] * -1,
this.basis[2][1] * -1,
this.basis[2][2] * -1
];
};
},{"./pointable":14,"gl-matrix":23,"underscore":24}],2:[function(require,module,exports){
var CircularBuffer = module.exports = function(size) {
this.pos = 0;
this._buf = [];
this.size = size;
}
CircularBuffer.prototype.get = function(i) {
if (i == undefined) i = 0;
if (i >= this.size) return undefined;
if (i >= this._buf.length) return undefined;
return this._buf[(this.pos - i - 1) % this.size];
}
CircularBuffer.prototype.push = function(o) {
this._buf[this.pos % this.size] = o;
return this.pos++;
}
},{}],3:[function(require,module,exports){
var chooseProtocol = require('../protocol').chooseProtocol
, EventEmitter = require('events').EventEmitter
, _ = require('underscore');
var BaseConnection = module.exports = function(opts) {
this.opts = _.defaults(opts || {}, {
host : '127.0.0.1',
enableGestures: false,
scheme: this.getScheme(),
port: this.getPort(),
background: false,
optimizeHMD: false,
requestProtocolVersion: BaseConnection.defaultProtocolVersion
});
this.host = this.opts.host;
this.port = this.opts.port;
this.scheme = this.opts.scheme;
this.protocolVersionVerified = false;
this.background = null;
this.optimizeHMD = null;
this.on('ready', function() {
this.enableGestures(this.opts.enableGestures);
this.setBackground(this.opts.background);
this.setOptimizeHMD(this.opts.optimizeHMD);
if (this.opts.optimizeHMD){
console.log("Optimized for head mounted display usage.");
}else {
console.log("Optimized for desktop usage.");
}
});
};
// The latest available:
BaseConnection.defaultProtocolVersion = 6;
BaseConnection.prototype.getUrl = function() {
return this.scheme + "//" + this.host + ":" + this.port + "/v" + this.opts.requestProtocolVersion + ".json";
}
BaseConnection.prototype.getScheme = function(){
return 'ws:'
}
BaseConnection.prototype.getPort = function(){
return 6437
}
BaseConnection.prototype.setBackground = function(state) {
this.opts.background = state;
if (this.protocol && this.protocol.sendBackground && this.background !== this.opts.background) {
this.background = this.opts.background;
this.protocol.sendBackground(this, this.opts.background);
}
}
BaseConnection.prototype.setOptimizeHMD = function(state) {
this.opts.optimizeHMD = state;
if (this.protocol && this.protocol.sendOptimizeHMD && this.optimizeHMD !== this.opts.optimizeHMD) {
this.optimizeHMD = this.opts.optimizeHMD;
this.protocol.sendOptimizeHMD(this, this.opts.optimizeHMD);
}
}
BaseConnection.prototype.handleOpen = function() {
if (!this.connected) {
this.connected = true;
this.emit('connect');
}
}
BaseConnection.prototype.enableGestures = function(enabled) {
this.gesturesEnabled = enabled ? true : false;
this.send(this.protocol.encode({"enableGestures": this.gesturesEnabled}));
}
BaseConnection.prototype.handleClose = function(code, reason) {
if (!this.connected) return;
this.disconnect();
// 1001 - an active connection is closed
// 1006 - cannot connect
if (code === 1001 && this.opts.requestProtocolVersion > 1) {
if (this.protocolVersionVerified) {
this.protocolVersionVerified = false;
}else{
this.opts.requestProtocolVersion--;
}
}
this.startReconnection();
}
BaseConnection.prototype.startReconnection = function() {
var connection = this;
if(!this.reconnectionTimer){
(this.reconnectionTimer = setInterval(function() { connection.reconnect() }, 500));
}
}
BaseConnection.prototype.stopReconnection = function() {
this.reconnectionTimer = clearInterval(this.reconnectionTimer);
}
// By default, disconnect will prevent auto-reconnection.
// Pass in true to allow the reconnection loop not be interrupted continue
BaseConnection.prototype.disconnect = function(allowReconnect) {
if (!allowReconnect) this.stopReconnection();
if (!this.socket) return;
this.socket.close();
delete this.socket;
delete this.protocol;
delete this.background; // This is not persisted when reconnecting to the web socket server
delete this.optimizeHMD;
delete this.focusedState;
if (this.connected) {
this.connected = false;
this.emit('disconnect');
}
return true;
}
BaseConnection.prototype.reconnect = function() {
if (this.connected) {
this.stopReconnection();
} else {
this.disconnect(true);
this.connect();
}
}
BaseConnection.prototype.handleData = function(data) {
var message = JSON.parse(data);
var messageEvent;
if (this.protocol === undefined) {
messageEvent = this.protocol = chooseProtocol(message);
this.protocolVersionVerified = true;
this.emit('ready');
} else {
messageEvent = this.protocol(message);
}
this.emit(messageEvent.type, messageEvent);
}
BaseConnection.prototype.connect = function() {
if (this.socket) return;
this.socket = this.setupSocket();
return true;
}
BaseConnection.prototype.send = function(data) {
this.socket.send(data);
}
BaseConnection.prototype.reportFocus = function(state) {
if (!this.connected || this.focusedState === state) return;
this.focusedState = state;
this.emit(this.focusedState ? 'focus' : 'blur');
if (this.protocol && this.protocol.sendFocused) {
this.protocol.sendFocused(this, this.focusedState);
}
}
_.extend(BaseConnection.prototype, EventEmitter.prototype);
},{"../protocol":15,"events":21,"underscore":24}],4:[function(require,module,exports){
var BaseConnection = module.exports = require('./base')
, _ = require('underscore');
var BrowserConnection = module.exports = function(opts) {
BaseConnection.call(this, opts);
var connection = this;
this.on('ready', function() { connection.startFocusLoop(); })
this.on('disconnect', function() { connection.stopFocusLoop(); })
}
_.extend(BrowserConnection.prototype, BaseConnection.prototype);
BrowserConnection.__proto__ = BaseConnection;
BrowserConnection.prototype.useSecure = function(){
return location.protocol === 'https:'
}
BrowserConnection.prototype.getScheme = function(){
return this.useSecure() ? 'wss:' : 'ws:'
}
BrowserConnection.prototype.getPort = function(){
return this.useSecure() ? 6436 : 6437
}
BrowserConnection.prototype.setupSocket = function() {
var connection = this;
var socket = new WebSocket(this.getUrl());
socket.onopen = function() { connection.handleOpen(); };
socket.onclose = function(data) { connection.handleClose(data['code'], data['reason']); };
socket.onmessage = function(message) { connection.handleData(message.data) };
socket.onerror = function(error) {
// attempt to degrade to ws: after one failed attempt for older Leap Service installations.
if (connection.useSecure() && connection.scheme === 'wss:'){
connection.scheme = 'ws:';
connection.port = 6437;
connection.disconnect();
connection.connect();
}
};
return socket;
}
BrowserConnection.prototype.startFocusLoop = function() {
if (this.focusDetectorTimer) return;
var connection = this;
var propertyName = null;
if (typeof document.hidden !== "undefined") {
propertyName = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
propertyName = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
propertyName = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
propertyName = "webkitHidden";
} else {
propertyName = undefined;
}
if (connection.windowVisible === undefined) {
connection.windowVisible = propertyName === undefined ? true : document[propertyName] === false;
}
var focusListener = window.addEventListener('focus', function(e) {
connection.windowVisible = true;
updateFocusState();
});
var blurListener = window.addEventListener('blur', function(e) {
connection.windowVisible = false;
updateFocusState();
});
this.on('disconnect', function() {
window.removeEventListener('focus', focusListener);
window.removeEventListener('blur', blurListener);
});
var updateFocusState = function() {
var isVisible = propertyName === undefined ? true : document[propertyName] === false;
connection.reportFocus(isVisible && connection.windowVisible);
}
// save 100ms when resuming focus
updateFocusState();
this.focusDetectorTimer = setInterval(updateFocusState, 100);
}
BrowserConnection.prototype.stopFocusLoop = function() {
if (!this.focusDetectorTimer) return;
clearTimeout(this.focusDetectorTimer);
delete this.focusDetectorTimer;
}
},{"./base":3,"underscore":24}],5:[function(require,module,exports){
var process=require("__browserify_process");var Frame = require('./frame')
, Hand = require('./hand')
, Pointable = require('./pointable')
, Finger = require('./finger')
, CircularBuffer = require("./circular_buffer")
, Pipeline = require("./pipeline")
, EventEmitter = require('events').EventEmitter
, gestureListener = require('./gesture').gestureListener
, Dialog = require('./dialog')
, _ = require('underscore');
/**
* Constructs a Controller object.
*
* When creating a Controller object, you may optionally pass in options
* to set the host , set the port, enable gestures, or select the frame event type.
*
* ```javascript
* var controller = new Leap.Controller({
* host: '127.0.0.1',
* port: 6437,
* enableGestures: true,
* frameEventName: 'animationFrame'
* });
* ```
*
* @class Controller
* @memberof Leap
* @classdesc
* The Controller class is your main interface to the Leap Motion Controller.
*
* Create an instance of this Controller class to access frames of tracking data
* and configuration information. Frame data can be polled at any time using the
* [Controller.frame]{@link Leap.Controller#frame}() function. Call frame() or frame(0) to get the most recent
* frame. Set the history parameter to a positive integer to access previous frames.
* A controller stores up to 60 frames in its frame history.
*
* Polling is an appropriate strategy for applications which already have an
* intrinsic update loop, such as a game.
*
* loopWhileDisconnected defaults to true, and maintains a 60FPS frame rate even when Leap Motion is not streaming
* data at that rate (such as no hands in frame). This is important for VR/WebGL apps which rely on rendering for
* regular visual updates, including from other input devices. Flipping this to false should be considered an
* optimization for very specific use-cases.
*
*
*/
var Controller = module.exports = function(opts) {
var inNode = (typeof(process) !== 'undefined' && process.versions && process.versions.node),
controller = this;
opts = _.defaults(opts || {}, {
inNode: inNode
});
this.inNode = opts.inNode;
opts = _.defaults(opts || {}, {
frameEventName: this.useAnimationLoop() ? 'animationFrame' : 'deviceFrame',
suppressAnimationLoop: !this.useAnimationLoop(),
loopWhileDisconnected: true,
useAllPlugins: false,
checkVersion: true
});
this.animationFrameRequested = false;
this.onAnimationFrame = function(timestamp) {
if (controller.lastConnectionFrame.valid){
controller.emit('animationFrame', controller.lastConnectionFrame);
}
controller.emit('frameEnd', timestamp);
if (
controller.loopWhileDisconnected &&
( ( controller.connection.focusedState !== false ) // loop while undefined, pre-ready.
|| controller.connection.opts.background) ){
window.requestAnimationFrame(controller.onAnimationFrame);
}else{
controller.animationFrameRequested = false;
}
};
this.suppressAnimationLoop = opts.suppressAnimationLoop;
this.loopWhileDisconnected = opts.loopWhileDisconnected;
this.frameEventName = opts.frameEventName;
this.useAllPlugins = opts.useAllPlugins;
this.history = new CircularBuffer(200);
this.lastFrame = Frame.Invalid;
this.lastValidFrame = Frame.Invalid;
this.lastConnectionFrame = Frame.Invalid;
this.accumulatedGestures = [];
this.checkVersion = opts.checkVersion;
if (opts.connectionType === undefined) {
this.connectionType = (this.inBrowser() ? require('./connection/browser') : require('./connection/node'));
} else {
this.connectionType = opts.connectionType;
}
this.connection = new this.connectionType(opts);
this.streamingCount = 0;
this.devices = {};
this.plugins = {};
this._pluginPipelineSteps = {};
this._pluginExtendedMethods = {};
if (opts.useAllPlugins) this.useRegisteredPlugins();
this.setupFrameEvents(opts);
this.setupConnectionEvents();
this.startAnimationLoop(); // immediately when started
}
Controller.prototype.gesture = function(type, cb) {
var creator = gestureListener(this, type);
if (cb !== undefined) {
creator.stop(cb);
}
return creator;
}
/*
* @returns the controller
*/
Controller.prototype.setBackground = function(state) {
this.connection.setBackground(state);
return this;
}
Controller.prototype.setOptimizeHMD = function(state) {
this.connection.setOptimizeHMD(state);
return this;
}
Controller.prototype.inBrowser = function() {
return !this.inNode;
}
Controller.prototype.useAnimationLoop = function() {
return this.inBrowser() && !this.inBackgroundPage();
}
Controller.prototype.inBackgroundPage = function(){
// http://developer.chrome.com/extensions/extension#method-getBackgroundPage
return (typeof(chrome) !== "undefined") &&
chrome.extension &&
chrome.extension.getBackgroundPage &&
(chrome.extension.getBackgroundPage() === window)
}
/*
* @returns the controller
*/
Controller.prototype.connect = function() {
this.connection.connect();
return this;
}
Controller.prototype.streaming = function() {
return this.streamingCount > 0;
}
Controller.prototype.connected = function() {
return !!this.connection.connected;
}
Controller.prototype.startAnimationLoop = function(){
if (!this.suppressAnimationLoop && !this.animationFrameRequested) {
this.animationFrameRequested = true;
window.requestAnimationFrame(this.onAnimationFrame);
}
}
/*
* @returns the controller
*/
Controller.prototype.disconnect = function() {
this.connection.disconnect();
return this;
}
/**
* Returns a frame of tracking data from the Leap.
*
* Use the optional history parameter to specify which frame to retrieve.
* Call frame() or frame(0) to access the most recent frame; call frame(1) to
* access the previous frame, and so on. If you use a history value greater
* than the number of stored frames, then the controller returns an invalid frame.
*
* @method frame
* @memberof Leap.Controller.prototype
* @param {number} history The age of the frame to return, counting backwards from
* the most recent frame (0) into the past and up to the maximum age (59).
* @returns {Leap.Frame} The specified frame; or, if no history
* parameter is specified, the newest frame. If a frame is not available at
* the specified history position, an invalid Frame is returned.
**/
Controller.prototype.frame = function(num) {
return this.history.get(num) || Frame.Invalid;
}
Controller.prototype.loop = function(callback) {
if (callback) {
if (typeof callback === 'function'){
this.on(this.frameEventName, callback);
}else{
// callback is actually of the form: {eventName: callback}
this.setupFrameEvents(callback);
}
}
return this.connect();
}
Controller.prototype.addStep = function(step) {
if (!this.pipeline) this.pipeline = new Pipeline(this);
this.pipeline.addStep(step);
}
// this is run on every deviceFrame
Controller.prototype.processFrame = function(frame) {
if (frame.gestures) {
this.accumulatedGestures = this.accumulatedGestures.concat(frame.gestures);
}
// lastConnectionFrame is used by the animation loop
this.lastConnectionFrame = frame;
this.startAnimationLoop(); // Only has effect if loopWhileDisconnected: false
this.emit('deviceFrame', frame);
}
// on a this.deviceEventName (usually 'animationFrame' in browsers), this emits a 'frame'
Controller.prototype.processFinishedFrame = function(frame) {
this.lastFrame = frame;
if (frame.valid) {
this.lastValidFrame = frame;
}
frame.controller = this;
frame.historyIdx = this.history.push(frame);
if (frame.gestures) {
frame.gestures = this.accumulatedGestures;
this.accumulatedGestures = [];
for (var gestureIdx = 0; gestureIdx != frame.gestures.length; gestureIdx++) {
this.emit("gesture", frame.gestures[gestureIdx], frame);
}
}
if (this.pipeline) {
frame = this.pipeline.run(frame);
if (!frame) frame = Frame.Invalid;
}
this.emit('frame', frame);
this.emitHandEvents(frame);
}
/**
* The controller will emit 'hand' events for every hand on each frame. The hand in question will be passed
* to the event callback.
*
* @param frame
*/
Controller.prototype.emitHandEvents = function(frame){
for (var i = 0; i < frame.hands.length; i++){
this.emit('hand', frame.hands[i]);
}
}
Controller.prototype.setupFrameEvents = function(opts){
if (opts.frame){
this.on('frame', opts.frame);
}
if (opts.hand){
this.on('hand', opts.hand);
}
}
/**
Controller events. The old 'deviceConnected' and 'deviceDisconnected' have been depricated -
use 'deviceStreaming' and 'deviceStopped' instead, except in the case of an unexpected disconnect.
There are 4 pairs of device events recently added/changed:
-deviceAttached/deviceRemoved - called when a device's physical connection to the computer changes
-deviceStreaming/deviceStopped - called when a device is paused or resumed.
-streamingStarted/streamingStopped - called when there is/is no longer at least 1 streaming device.
Always comes after deviceStreaming.
The first of all of the above event pairs is triggered as appropriate upon connection. All of
these events receives an argument with the most recent info about the device that triggered it.
These events will always be fired in the order they are listed here, with reverse ordering for the
matching shutdown call. (ie, deviceStreaming always comes after deviceAttached, and deviceStopped
will come before deviceRemoved).
-deviceConnected/deviceDisconnected - These are considered deprecated and will be removed in
the next revision. In contrast to the other events and in keeping with it's original behavior,
it will only be fired when a device begins streaming AFTER a connection has been established.
It is not paired, and receives no device info. Nearly identical functionality to
streamingStarted/Stopped if you need to port.
*/
Controller.prototype.setupConnectionEvents = function() {
var controller = this;
this.connection.on('frame', function(frame) {
controller.processFrame(frame);
});
// either deviceFrame or animationFrame:
this.on(this.frameEventName, function(frame) {
controller.processFinishedFrame(frame);
});
// here we backfill the 0.5.0 deviceEvents as best possible
// backfill begin streaming events
var backfillStreamingStartedEventsHandler = function(){
if (controller.connection.opts.requestProtocolVersion < 5 && controller.streamingCount == 0){
controller.streamingCount = 1;
var info = {
attached: true,
streaming: true,
type: 'unknown',
id: "Lx00000000000"
};
controller.devices[info.id] = info;
controller.emit('deviceAttached', info);
controller.emit('deviceStreaming', info);
controller.emit('streamingStarted', info);
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
}
}
var backfillStreamingStoppedEvents = function(){
if (controller.streamingCount > 0) {
for (var deviceId in controller.devices){
controller.emit('deviceStopped', controller.devices[deviceId]);
controller.emit('deviceRemoved', controller.devices[deviceId]);
}
// only emit streamingStopped once, with the last device
controller.emit('streamingStopped', controller.devices[deviceId]);
controller.streamingCount = 0;
for (var deviceId in controller.devices){
delete controller.devices[deviceId];
}
}
}
// Delegate connection events
this.connection.on('focus', function() {
if ( controller.loopWhileDisconnected ){
controller.startAnimationLoop();
}
controller.emit('focus');
});
this.connection.on('blur', function() { controller.emit('blur') });
this.connection.on('protocol', function(protocol) {
protocol.on('beforeFrameCreated', function(frameData){
controller.emit('beforeFrameCreated', frameData)
});
protocol.on('afterFrameCreated', function(frame, frameData){
controller.emit('afterFrameCreated', frame, frameData)
});
controller.emit('protocol', protocol);
});
this.connection.on('ready', function() {
if (controller.checkVersion && !controller.inNode){
// show dialog only to web users
controller.checkOutOfDate();
}
controller.emit('ready');
});
this.connection.on('connect', function() {
controller.emit('connect');
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
controller.connection.on('frame', backfillStreamingStartedEventsHandler);
});
this.connection.on('disconnect', function() {
controller.emit('disconnect');
backfillStreamingStoppedEvents();
});
// this does not fire when the controller is manually disconnected
// or for Leap Service v1.2.0+
this.connection.on('deviceConnect', function(evt) {
if (evt.state){
controller.emit('deviceConnected');
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
controller.connection.on('frame', backfillStreamingStartedEventsHandler);
}else{
controller.emit('deviceDisconnected');
backfillStreamingStoppedEvents();
}
});
// Does not fire for Leap Service pre v1.2.0
this.connection.on('deviceEvent', function(evt) {
var info = evt.state,
oldInfo = controller.devices[info.id];
//Grab a list of changed properties in the device info
var changed = {};
for(var property in info) {
//If a property i doesn't exist the cache, or has changed...
if( !oldInfo || !oldInfo.hasOwnProperty(property) || oldInfo[property] != info[property] ) {
changed[property] = true;
}
}
//Update the device list
controller.devices[info.id] = info;
//Fire events based on change list
if(changed.attached) {
controller.emit(info.attached ? 'deviceAttached' : 'deviceRemoved', info);
}
if(!changed.streaming) return;
if(info.streaming) {
controller.streamingCount++;
controller.emit('deviceStreaming', info);
if( controller.streamingCount == 1 ) {
controller.emit('streamingStarted', info);
}
//if attached & streaming both change to true at the same time, that device was streaming
//already when we connected.
if(!changed.attached) {
controller.emit('deviceConnected');
}
}
//Since when devices are attached all fields have changed, don't send events for streaming being false.
else if(!(changed.attached && info.attached)) {
controller.streamingCount--;
controller.emit('deviceStopped', info);
if(controller.streamingCount == 0){
controller.emit('streamingStopped', info);
}
controller.emit('deviceDisconnected');
}
});
this.on('newListener', function(event, listener) {
if( event == 'deviceConnected' || event == 'deviceDisconnected' ) {
console.warn(event + " events are depricated. Consider using 'streamingStarted/streamingStopped' or 'deviceStreaming/deviceStopped' instead");
}
});
};
// Checks if the protocol version is the latest, if if not, shows the dialog.
Controller.prototype.checkOutOfDate = function(){
console.assert(this.connection && this.connection.protocol);
var serviceVersion = this.connection.protocol.serviceVersion;
var protocolVersion = this.connection.protocol.version;
var defaultProtocolVersion = this.connectionType.defaultProtocolVersion;
if (defaultProtocolVersion > protocolVersion){
console.warn("Your Protocol Version is v" + protocolVersion +
", this app was designed for v" + defaultProtocolVersion);
Dialog.warnOutOfDate({
sV: serviceVersion,
pV: protocolVersion
});
return true
}else{
return false
}
};
Controller._pluginFactories = {};
/*
* Registers a plugin, making is accessible to controller.use later on.
*
* @member plugin
* @memberof Leap.Controller.prototype
* @param {String} name The name of the plugin (usually camelCase).
* @param {function} factory A factory method which will return an instance of a plugin.
* The factory receives an optional hash of options, passed in via controller.use.
*
* Valid keys for the object include frame, hand, finger, tool, and pointable. The value
* of each key can be either a function or an object. If given a function, that function
* will be called once for every instance of the object, with that instance injected as an
* argument. This allows decoration of objects with additional data:
*
* ```javascript
* Leap.Controller.plugin('testPlugin', function(options){
* return {
* frame: function(frame){
* frame.foo = 'bar';
* }
* }
* });
* ```
*
* When hand is used, the callback is called for every hand in `frame.hands`. Note that
* hand objects are recreated with every new frame, so that data saved on the hand will not
* persist.
*
* ```javascript
* Leap.Controller.plugin('testPlugin', function(){
* return {
* hand: function(hand){
* console.log('testPlugin running on hand ' + hand.id);
* }
* }
* });
* ```
*
* A factory can return an object to add custom functionality to Frames, Hands, or Pointables.
* The methods are added directly to the object's prototype. Finger and Tool cannot be used here, Pointable
* must be used instead.
* This is encouraged for calculations which may not be necessary on every frame.
* Memoization is also encouraged, for cases where the method may be called many times per frame by the application.
*
* ```javascript
* // This plugin allows hand.usefulData() to be called later.
* Leap.Controller.plugin('testPlugin', function(){
* return {
* hand: {
* usefulData: function(){
* console.log('usefulData on hand', this.id);