forked from leapmotion/leapjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leap.js
6878 lines (6261 loc) · 204 KB
/
leap.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
;(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 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,
port: 6437,
enableHeartbeat: true,
heartbeatInterval: 100,
requestProtocolVersion: 3
});
this.host = this.opts.host;
this.port = this.opts.port;
this.on('ready', function() {
this.enableGestures(this.opts.enableGestures);
if (this.opts.enableHeartbeat) this.startHeartbeat();
});
this.on('disconnect', function() {
if (this.opts.enableHeartbeat) this.stopHeartbeat();
});
this.heartbeatTimer = null;
}
BaseConnection.prototype.getUrl = function() {
return "ws://" + this.host + ":" + this.port + "/v" + this.opts.requestProtocolVersion + ".json";
}
BaseConnection.prototype.sendHeartbeat = function() {
if (this.protocol) {
this.setHeartbeatState(true);
this.protocol.sendHeartbeat(this);
}
}
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() {
if (!this.connected) return;
this.disconnect();
this.startReconnection();
}
BaseConnection.prototype.startReconnection = function() {
var connection = this;
this.reconnectionTimer = setInterval(function() { connection.reconnect() }, 1000);
}
BaseConnection.prototype.disconnect = function() {
if (!this.socket) return;
this.socket.close();
delete this.socket;
delete this.protocol;
if (this.connected) {
this.connected = false;
this.emit('disconnect');
}
}
BaseConnection.prototype.reconnect = function() {
if (this.connected) {
clearInterval(this.reconnectionTimer);
} else {
this.disconnect();
this.connect();
}
}
BaseConnection.prototype.handleData = function(data) {
var message = JSON.parse(data);
var messageEvent;
if (this.protocol === undefined) {
messageEvent = this.protocol = chooseProtocol(message);
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.stopHeartbeat = function() {
if (!this.heartbeatTimer) return;
clearInterval(this.heartbeatTimer);
delete this.heartbeatTimer;
this.setHeartbeatState(false);
};
BaseConnection.prototype.setHeartbeatState = function(state) {
if (this.heartbeatState === state) return;
this.heartbeatState = state;
this.emit(this.heartbeatState ? 'focus' : 'blur');
};
_.extend(BaseConnection.prototype, EventEmitter.prototype);
},{"./protocol":12,"events":17,"underscore":20}],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 Connection = module.exports = require('./base_connection')
Connection.prototype.setupSocket = function() {
var connection = this;
var socket = new WebSocket(this.getUrl());
socket.onopen = function() { connection.handleOpen() };
socket.onmessage = function(message) { connection.handleData(message.data) };
socket.onclose = function() { connection.handleClose() };
return socket;
}
Connection.prototype.startHeartbeat = function() {
if (!this.protocol.sendHeartbeat || this.heartbeatTimer) 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;
}
var windowVisible = true;
var focusListener = window.addEventListener('focus', function(e) { windowVisible = true; });
var blurListener = window.addEventListener('blur', function(e) { windowVisible = false; });
this.on('disconnect', function() {
if (connection.heartbeatTimer) {
clearTimeout(connection.heartbeatTimer);
delete connection.heartbeatTimer;
}
window.removeEventListener('focus', focusListener);
window.removeEventListener('blur', blurListener);
});
this.heartbeatTimer = setInterval(function() {
var isVisible = propertyName === undefined ? true : document[propertyName] === false;
if (isVisible && windowVisible) {
connection.sendHeartbeat();
} else {
connection.setHeartbeatState(false);
}
}, this.opts.heartbeatInterval);
}
},{"./base_connection":1}],4:[function(require,module,exports){
(function(process){var Frame = require('./frame')
, CircularBuffer = require("./circular_buffer")
, Pipeline = require("./pipeline")
, EventEmitter = require('events').EventEmitter
, gestureListener = require('./gesture').gestureListener
, _ = 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.
*/
var Controller = module.exports = function(opts) {
var inNode = typeof(process) !== 'undefined' && process.title === 'node';
opts = _.defaults(opts || {}, {
inNode: inNode
});
this.inNode = opts.inNode;
opts = _.defaults(opts || {}, {
frameEventName: this.useAnimationLoop() ? 'animationFrame' : 'deviceFrame',
suppressAnimationLoop: false
});
this.suppressAnimationLoop = opts.suppressAnimationLoop;
this.frameEventName = opts.frameEventName;
this.history = new CircularBuffer(200);
this.lastFrame = Frame.Invalid;
this.lastValidFrame = Frame.Invalid;
this.lastConnectionFrame = Frame.Invalid;
this.accumulatedGestures = [];
if (opts.connectionType === undefined) {
this.connectionType = (this.inBrowser() ? require('./connection') : require('./node_connection'));
} else {
this.connectionType = opts.connectionType;
}
this.connection = new this.connectionType(opts);
this.setupConnectionEvents();
}
Controller.prototype.gesture = function(type, cb) {
var creator = gestureListener(this, type);
if (cb !== undefined) {
creator.stop(cb);
}
return creator;
}
Controller.prototype.inBrowser = function() {
return !this.inNode;
}
Controller.prototype.useAnimationLoop = function() {
return this.inBrowser() && typeof(chrome) === "undefined";
}
Controller.prototype.connect = function() {
var controller = this;
if (this.connection.connect() && this.inBrowser() && !controller.suppressAnimationLoop) {
var callback = function() {
controller.emit('animationFrame', controller.lastConnectionFrame);
window.requestAnimationFrame(callback);
}
window.requestAnimationFrame(callback);
}
}
Controller.prototype.disconnect = function() {
this.connection.disconnect();
}
/**
* 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) {
switch (callback.length) {
case 1:
this.on(this.frameEventName, callback);
break;
case 2:
var controller = this;
var scheduler = null;
var immediateRunnerCallback = function(frame) {
callback(frame, function() {
if (controller.lastFrame != frame) {
immediateRunnerCallback(controller.lastFrame);
} else {
controller.once(controller.frameEventName, immediateRunnerCallback);
}
});
}
this.once(this.frameEventName, immediateRunnerCallback);
break;
}
this.connect();
}
Controller.prototype.addStep = function(step) {
if (!this.pipeline) this.pipeline = new Pipeline(this);
this.pipeline.addStep(step);
}
Controller.prototype.processFrame = function(frame) {
if (frame.gestures) {
this.accumulatedGestures = this.accumulatedGestures.concat(frame.gestures);
}
if (this.pipeline) {
frame = this.pipeline.run(frame);
if (!frame) frame = Frame.Invalid;
}
this.lastConnectionFrame = frame;
this.emit('deviceFrame', 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);
}
}
this.emit('frame', frame);
}
Controller.prototype.setupConnectionEvents = function() {
var controller = this;
this.connection.on('frame', function(frame) {
controller.processFrame(frame);
});
this.on(this.frameEventName, function(frame) {
controller.processFinishedFrame(frame);
});
// Delegate connection events
this.connection.on('disconnect', function() { controller.emit('disconnect'); });
this.connection.on('ready', function() { controller.emit('ready'); });
this.connection.on('connect', function() { controller.emit('connect'); });
this.connection.on('focus', function() { controller.emit('focus') });
this.connection.on('blur', function() { controller.emit('blur') });
this.connection.on('protocol', function(protocol) { controller.emit('protocol', protocol); });
this.connection.on('deviceConnect', function(evt) { controller.emit(evt.state ? 'deviceConnected' : 'deviceDisconnected'); });
}
_.extend(Controller.prototype, EventEmitter.prototype);
})(require("__browserify_process"))
},{"./circular_buffer":2,"./connection":3,"./frame":5,"./gesture":6,"./node_connection":16,"./pipeline":10,"__browserify_process":18,"events":17,"underscore":20}],5:[function(require,module,exports){
var Hand = require("./hand")
, Pointable = require("./pointable")
, createGesture = require("./gesture").createGesture
, glMatrix = require("gl-matrix")
, mat3 = glMatrix.mat3
, vec3 = glMatrix.vec3
, InteractionBox = require("./interaction_box")
, _ = require("underscore");
/**
* Constructs a Frame object.
*
* Frame instances created with this constructor are invalid.
* Get valid Frame objects by calling the
* [Controller.frame]{@link Leap.Controller#frame}() function.
*<C-D-Space>
* @class Frame
* @memberof Leap
* @classdesc
* The Frame class represents a set of hand and finger tracking data detected
* in a single frame.
*
* The Leap detects hands, fingers and tools within the tracking area, reporting
* their positions, orientations and motions in frames at the Leap frame rate.
*
* Access Frame objects using the [Controller.frame]{@link Leap.Controller#frame}() function.
*/
var Frame = module.exports = function(data) {
/**
* Reports whether this Frame instance is valid.
*
* A valid Frame is one generated by the Controller object that contains
* tracking data for all detected entities. An invalid Frame contains no
* actual tracking data, but you can call its functions without risk of a
* undefined object exception. The invalid Frame mechanism makes it more
* convenient to track individual data across the frame history. For example,
* you can invoke:
*
* ```javascript
* var finger = controller.frame(n).finger(fingerID);
* ```
*
* for an arbitrary Frame history value, "n", without first checking whether
* frame(n) returned a null object. (You should still check that the
* returned Finger instance is valid.)
*
* @member valid
* @memberof Leap.Frame.prototype
* @type {Boolean}
*/
this.valid = true;
/**
* A unique ID for this Frame. Consecutive frames processed by the Leap
* have consecutive increasing values.
* @member id
* @memberof Leap.Frame.prototype
* @type {String}
*/
this.id = data.id;
/**
* The frame capture time in microseconds elapsed since the Leap started.
* @member timestamp
* @memberof Leap.Frame.prototype
* @type {number}
*/
this.timestamp = data.timestamp;
/**
* The list of Hand objects detected in this frame, given in arbitrary order.
* The list can be empty if no hands are detected.
*
* @member hands[]
* @memberof Leap.Frame.prototype
* @type {Leap.Hand}
*/
this.hands = [];
this.handsMap = {};
/**
* The list of Pointable objects (fingers and tools) detected in this frame,
* given in arbitrary order. The list can be empty if no fingers or tools are
* detected.
*
* @member pointables[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.pointables = [];
/**
* The list of Tool objects detected in this frame, given in arbitrary order.
* The list can be empty if no tools are detected.
*
* @member tools[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.tools = [];
/**
* The list of Finger objects detected in this frame, given in arbitrary order.
* The list can be empty if no fingers are detected.
* @member fingers[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.fingers = [];
if (data.interactionBox) {
this.interactionBox = new InteractionBox(data.interactionBox);
}
this.gestures = [];
this.pointablesMap = {};
this._translation = data.t;
this._rotation = _.flatten(data.r);
this._scaleFactor = data.s;
this.data = data;
this.type = 'frame'; // used by event emitting
this.currentFrameRate = data.currentFrameRate;
var handMap = {};
for (var handIdx = 0, handCount = data.hands.length; handIdx != handCount; handIdx++) {
var hand = new Hand(data.hands[handIdx]);
hand.frame = this;
this.hands.push(hand);
this.handsMap[hand.id] = hand;
handMap[hand.id] = handIdx;
}
for (var pointableIdx = 0, pointableCount = data.pointables.length; pointableIdx != pointableCount; pointableIdx++) {
var pointable = new Pointable(data.pointables[pointableIdx]);
pointable.frame = this;
this.pointables.push(pointable);
this.pointablesMap[pointable.id] = pointable;
(pointable.tool ? this.tools : this.fingers).push(pointable);
if (pointable.handId !== undefined && handMap.hasOwnProperty(pointable.handId)) {
var hand = this.hands[handMap[pointable.handId]];
hand.pointables.push(pointable);
(pointable.tool ? hand.tools : hand.fingers).push(pointable);
}
}
if (data.gestures) {
/**
* The list of Gesture objects detected in this frame, given in arbitrary order.
* The list can be empty if no gestures are detected.
*
* Circle and swipe gestures are updated every frame. Tap gestures
* only appear in the list for a single frame.
* @member gestures[]
* @memberof Leap.Frame.prototype
* @type {Leap.Gesture}
*/
for (var gestureIdx = 0, gestureCount = data.gestures.length; gestureIdx != gestureCount; gestureIdx++) {
this.gestures.push(createGesture(data.gestures[gestureIdx]));
}
}
}
/**
* The tool with the specified ID in this frame.
*
* Use the Frame tool() function to retrieve a tool from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Pointable object, but if no tool
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a tool is lost and subsequently
* regained, the new Pointable object representing that tool may have a
* different ID than that representing the tool in an earlier frame.
*
* @method tool
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Tool object from a previous frame.
* @returns {Leap.Pointable} The tool with the
* matching ID if one exists in this frame; otherwise, an invalid Pointable object
* is returned.
*/
Frame.prototype.tool = function(id) {
var pointable = this.pointable(id);
return pointable.tool ? pointable : Pointable.Invalid;
}
/**
* The Pointable object with the specified ID in this frame.
*
* Use the Frame pointable() function to retrieve the Pointable object from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Pointable object, but if no finger or tool
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a finger or tool is lost and subsequently
* regained, the new Pointable object representing that finger or tool may have
* a different ID than that representing the finger or tool in an earlier frame.
*
* @method pointable
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Pointable object from a previous frame.
* @returns {Leap.Pointable} The Pointable object with
* the matching ID if one exists in this frame;
* otherwise, an invalid Pointable object is returned.
*/
Frame.prototype.pointable = function(id) {
return this.pointablesMap[id] || Pointable.Invalid;
}
/**
* The finger with the specified ID in this frame.
*
* Use the Frame finger() function to retrieve the finger from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Finger object, but if no finger
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a finger is lost and subsequently
* regained, the new Pointable object representing that physical finger may have
* a different ID than that representing the finger in an earlier frame.
*
* @method finger
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a finger from a previous frame.
* @returns {Leap.Pointable} The finger with the
* matching ID if one exists in this frame; otherwise, an invalid Pointable
* object is returned.
*/
Frame.prototype.finger = function(id) {
var pointable = this.pointable(id);
return !pointable.tool ? pointable : Pointable.Invalid;
}
/**
* The Hand object with the specified ID in this frame.
*
* Use the Frame hand() function to retrieve the Hand object from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Hand object, but if no hand
* with the specified ID is present, an invalid Hand object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a hand is lost and subsequently
* regained, the new Hand object representing that physical hand may have
* a different ID than that representing the physical hand in an earlier frame.
*
* @method hand
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Hand object from a previous frame.
* @returns {Leap.Hand} The Hand object with the matching
* ID if one exists in this frame; otherwise, an invalid Hand object is returned.
*/
Frame.prototype.hand = function(id) {
return this.handsMap[id] || Hand.Invalid;
}
/**
* The angle of rotation around the rotation axis derived from the overall
* rotational motion between the current frame and the specified frame.
*
* The returned angle is expressed in radians measured clockwise around
* the rotation axis (using the right-hand rule) between the start and end frames.
* The value is always between 0 and pi radians (0 and 180 degrees).
*
* The Leap derives frame rotation from the relative change in position and
* orientation of all objects detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, then the
* angle of rotation is zero.
*
* @method rotationAngle
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative rotation.
* @param {number[]} [axis] The axis to measure rotation around.
* @returns {number} A positive value containing the heuristically determined
* rotational change between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.rotationAngle = function(sinceFrame, axis) {
if (!this.valid || !sinceFrame.valid) return 0.0;
var rot = this.rotationMatrix(sinceFrame);
var cs = (rot[0] + rot[4] + rot[8] - 1.0)*0.5
var angle = Math.acos(cs);
angle = isNaN(angle) ? 0.0 : angle;
if (axis !== undefined) {
var rotAxis = this.rotationAxis(sinceFrame);
angle *= vec3.dot(rotAxis, vec3.normalize(vec3.create(), axis));
}
return angle;
}
/**
* The axis of rotation derived from the overall rotational motion between
* the current frame and the specified frame.
*
* The returned direction vector is normalized.
*
* The Leap derives frame rotation from the relative change in position and
* orientation of all objects detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, or if no
* rotation is detected between the two frames, a zero vector is returned.
*
* @method rotationAxis
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative rotation.
* @returns {number[]} A normalized direction vector representing the axis of the heuristically determined
* rotational change between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.rotationAxis = function(sinceFrame) {
if (!this.valid || !sinceFrame.valid) return vec3.create();
return vec3.normalize(vec3.create(), [
this._rotation[7] - sinceFrame._rotation[5],
this._rotation[2] - sinceFrame._rotation[6],
this._rotation[3] - sinceFrame._rotation[1]
]);
}
/**
* The transform matrix expressing the rotation derived from the overall
* rotational motion between the current frame and the specified frame.
*
* The Leap derives frame rotation from the relative change in position and
* orientation of all objects detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, then
* this method returns an identity matrix.
*
* @method rotationMatrix
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative rotation.
* @returns {number[]} A transformation matrix containing the heuristically determined
* rotational change between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.rotationMatrix = function(sinceFrame) {
if (!this.valid || !sinceFrame.valid) return mat3.create();
var transpose = mat3.transpose(mat3.create(), this._rotation)
return mat3.multiply(mat3.create(), sinceFrame._rotation, transpose);
}
/**
* The scale factor derived from the overall motion between the current frame and the specified frame.
*
* The scale factor is always positive. A value of 1.0 indicates no scaling took place.
* Values between 0.0 and 1.0 indicate contraction and values greater than 1.0 indicate expansion.
*
* The Leap derives scaling from the relative inward or outward motion of all
* objects detected in the field of view (independent of translation and rotation).
*
* If either this frame or sinceFrame is an invalid Frame object, then this method returns 1.0.
*
* @method scaleFactor
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative scaling.
* @returns {number} A positive value representing the heuristically determined
* scaling change ratio between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.scaleFactor = function(sinceFrame) {
if (!this.valid || !sinceFrame.valid) return 1.0;
return Math.exp(this._scaleFactor - sinceFrame._scaleFactor);
}
/**
* The change of position derived from the overall linear motion between the
* current frame and the specified frame.
*
* The returned translation vector provides the magnitude and direction of the
* movement in millimeters.
*
* The Leap derives frame translation from the linear motion of all objects
* detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, then this
* method returns a zero vector.
*
* @method translation
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative translation.
* @returns {number[]} A vector representing the heuristically determined change in
* position of all objects between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.translation = function(sinceFrame) {
if (!this.valid || !sinceFrame.valid) return vec3.create();
return vec3.subtract(vec3.create(), this._translation, sinceFrame._translation);
}
/**
* A string containing a brief, human readable description of the Frame object.
*
* @method toString
* @memberof Leap.Frame.prototype
* @returns {String} A brief description of this frame.
*/
Frame.prototype.toString = function() {
var str = "Frame [ id:"+this.id+" | timestamp:"+this.timestamp+" | Hand count:("+this.hands.length+") | Pointable count:("+this.pointables.length+")";
if (this.gestures) str += " | Gesture count:("+this.gestures.length+")";
str += " ]";
return str;
}
/**
* Returns a JSON-formatted string containing the hands, pointables and gestures
* in this frame.
*
* @method dump
* @memberof Leap.Frame.prototype
* @returns {String} A JSON-formatted string.
*/
Frame.prototype.dump = function() {
var out = '';
out += "Frame Info:<br/>";
out += this.toString();
out += "<br/><br/>Hands:<br/>"
for (var handIdx = 0, handCount = this.hands.length; handIdx != handCount; handIdx++) {
out += " "+ this.hands[handIdx].toString() + "<br/>";
}
out += "<br/><br/>Pointables:<br/>";
for (var pointableIdx = 0, pointableCount = this.pointables.length; pointableIdx != pointableCount; pointableIdx++) {
out += " "+ this.pointables[pointableIdx].toString() + "<br/>";
}
if (this.gestures) {
out += "<br/><br/>Gestures:<br/>";
for (var gestureIdx = 0, gestureCount = this.gestures.length; gestureIdx != gestureCount; gestureIdx++) {
out += " "+ this.gestures[gestureIdx].toString() + "<br/>";
}
}
out += "<br/><br/>Raw JSON:<br/>";
out += JSON.stringify(this.data);
return out;
}
/**
* An invalid Frame object.
*
* You can use this invalid Frame in comparisons testing
* whether a given Frame instance is valid or invalid. (You can also check the
* [Frame.valid]{@link Leap.Frame#valid} property.)
*
* @static
* @type {Leap.Frame}
* @name Invalid
* @memberof Leap.Frame
*/
Frame.Invalid = {
valid: false,
hands: [],
fingers: [],
tools: [],
gestures: [],
pointables: [],
pointable: function() { return Pointable.Invalid },
finger: function() { return Pointable.Invalid },
hand: function() { return Hand.Invalid },
toString: function() { return "invalid frame" },
dump: function() { return this.toString() },
rotationAngle: function() { return 0.0; },
rotationMatrix: function() { return mat3.create(); },
rotationAxis: function() { return vec3.create(); },
scaleFactor: function() { return 1.0; },
translation: function() { return vec3.create(); }
};
},{"./gesture":6,"./hand":7,"./interaction_box":9,"./pointable":11,"gl-matrix":19,"underscore":20}],6:[function(require,module,exports){
var glMatrix = require("gl-matrix")
, vec3 = glMatrix.vec3
, EventEmitter = require('events').EventEmitter
, _ = require('underscore');
/**
* Constructs a new Gesture object.
*
* An uninitialized Gesture object is considered invalid. Get valid instances
* of the Gesture class, which will be one of the Gesture subclasses, from a
* Frame object.
*
* @class Gesture
* @abstract
* @memberof Leap
* @classdesc
* The Gesture class represents a recognized movement by the user.
*
* The Leap watches the activity within its field of view for certain movement
* patterns typical of a user gesture or command. For example, a movement from side to
* side with the hand can indicate a swipe gesture, while a finger poking forward
* can indicate a screen tap gesture.
*
* When the Leap recognizes a gesture, it assigns an ID and adds a
* Gesture object to the frame gesture list. For continuous gestures, which
* occur over many frames, the Leap updates the gesture by adding
* a Gesture object having the same ID and updated properties in each
* subsequent frame.
*
* **Important:** Recognition for each type of gesture must be enabled;
* otherwise **no gestures are recognized or reported**.
*
* Subclasses of Gesture define the properties for the specific movement patterns
* recognized by the Leap.
*
* The Gesture subclasses for include:
*
* * CircleGesture -- A circular movement by a finger.
* * SwipeGesture -- A straight line movement by the hand with fingers extended.
* * ScreenTapGesture -- A forward tapping movement by a finger.
* * KeyTapGesture -- A downward tapping movement by a finger.
*
* Circle and swipe gestures are continuous and these objects can have a
* state of start, update, and stop.
*
* The screen tap gesture is a discrete gesture. The Leap only creates a single
* ScreenTapGesture object appears for each tap and it always has a stop state.
*
* Get valid Gesture instances from a Frame object. You can get a list of gestures
* from the Frame gestures array. You can also use the Frame gesture() method
* to find a gesture in the current frame using an ID value obtained in a
* previous frame.
*
* Gesture objects can be invalid. For example, when you get a gesture by ID
* using Frame.gesture(), and there is no gesture with that ID in the current
* frame, then gesture() returns an Invalid Gesture object (rather than a null
* value). Always check object validity in situations where a gesture might be
* invalid.
*/
var createGesture = exports.createGesture = function(data) {
var gesture;
switch (data.type) {
case 'circle':
gesture = new CircleGesture(data);
break;
case 'swipe':
gesture = new SwipeGesture(data);
break;
case 'screenTap':
gesture = new ScreenTapGesture(data);
break;
case 'keyTap':
gesture = new KeyTapGesture(data);
break;
default:
throw "unkown gesture type";
}
/**
* The gesture ID.
*
* All Gesture objects belonging to the same recognized movement share the
* same ID value. Use the ID value with the Frame::gesture() method to
* find updates related to this Gesture object in subsequent frames.
*
* @member id
* @memberof Leap.Gesture.prototype
* @type {number}
*/
gesture.id = data.id;
/**
* The list of hands associated with this Gesture, if any.
*
* If no hands are related to this gesture, the list is empty.
*
* @member handIds
* @memberof Leap.Gesture.prototype
* @type {Array}
*/
gesture.handIds = data.handIds;
/**
* The list of fingers and tools associated with this Gesture, if any.
*
* If no Pointable objects are related to this gesture, the list is empty.
*
* @member pointableIds
* @memberof Leap.Gesture.prototype
* @type {Array}
*/
gesture.pointableIds = data.pointableIds;
/**
* The elapsed duration of the recognized movement up to the
* frame containing this Gesture object, in microseconds.
*
* The duration reported for the first Gesture in the sequence (with the
* start state) will typically be a small positive number since
* the movement must progress far enough for the Leap to recognize it as
* an intentional gesture.
*
* @member duration
* @memberof Leap.Gesture.prototype
* @type {number}
*/
gesture.duration = data.duration;
/**
* The gesture ID.
*
* Recognized movements occur over time and have a beginning, a middle,
* and an end. The 'state()' attribute reports where in that sequence this
* Gesture object falls.
*
* Possible values for the state field are:
*
* * start
* * update
* * stop
*
* @member state
* @memberof Leap.Gesture.prototype
* @type {String}
*/
gesture.state = data.state;
/**
* The gesture type.
*
* Possible values for the type field are:
*
* * circle
* * swipe
* * screenTap
* * keyTap
*
* @member type
* @memberof Leap.Gesture.prototype
* @type {String}