-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.js
More file actions
executable file
·2523 lines (2222 loc) · 102 KB
/
object.js
File metadata and controls
executable file
·2523 lines (2222 loc) · 102 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
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
// eslint-disable-next-line no-unused-vars
/* global workerId */
/**
* @fileOverview
*
* object.js provides the SpatialInterface API, forming a bridge between the
* tool and the containing user interface. Calling a method on the
* SpatialInterface usually calls postMessage to send a message from the tool
* iframe to the user interface which will then take an action on behalf of the
* tool.
*/
(function(exports) {
/* eslint no-inner-declarations: "off" */
// makes sure this only gets loaded once per iframe
if (typeof exports.spatialObject !== 'undefined') {
return;
}
// Hardcoded for now, host of the internet of screens.
var iOSHost = 'https://localhost:5000';
// Keeps track of all state related to this frame and its API interactions
var spatialObject = {
alreadyLoaded: false,
node: '',
frame: '',
object: '',
publicData: {},
modelViewMatrix: [],
serverIp: '127.0.0.1',
serverPort: '8080',
matrices: {
modelView: [],
projection: [],
groundPlane: [],
anchoredModelView: [],
devicePose: [],
allObjects: {}
},
projectionMatrix: [],
visibility: 'visible',
sendMatrix: false,
sendMatrices: {
modelView: false,
devicePose: false,
groundPlane: false,
anchoredModelView: false,
allObjects: false
},
sendScreenPosition: false,
sendDeviceDistance: false,
sendAcceleration: false,
sendFullScreen: false,
sendScreenObject: false,
sendObjectPositions: {},
fullscreenZPosition: 0,
sendSticky: false,
isFullScreenExclusive: false,
attachesTo: null,
wasToolJustCreated: null,
isPinned: true,
alwaysFaceCamera: false,
height: '100%',
width: '100%',
socketIoScript: {},
socketIoRequest: {},
socketIoUrl: '',
style: document.createElement('style'),
messageCallBacks: {},
interface: 'gui',
version: 170,
moveDelay: 400,
visibilityDistance: 2.0,
customInteractionMode: false, // this is how frames used to respond to touches. change to true and add class realityInteraction to certain divs to make only some divs interactable
invertedInteractionMode: false, // if true, inverts the behavior of customInteractionMode. divs with realityInteraction are the only ones that can move the frame, all others are interactable
eventObject: {
version: null,
object: null,
frame: null,
node: null,
x: 0,
y: 0,
type: null},
touchDecider: null,
touchDeciderRegistered: false,
unacceptedTouchInProgress: false,
ignoreAllTouches: false,
// onFullScreenEjected: null,
onload: null
};
/**
* Generates a random 12 character unique identifier using uppercase, lowercase, and numbers (e.g. "OXezc4urfwja")
* @return {string}
*/
function uuidTime () {
var dateUuidTime = new Date();
var abcUuidTime = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stampUuidTime = parseInt(Math.floor((Math.random() * 199) + 1) + '' + dateUuidTime.getTime()).toString(36);
while (stampUuidTime.length < 11) stampUuidTime = abcUuidTime.charAt(Math.floor(Math.random() * abcUuidTime.length)) + stampUuidTime;
return '_' + stampUuidTime;
}
var sessionUuid = uuidTime(); // prevents this application from sending itself data
console.log('fullscreen reset for new frame ' + spatialObject.sendFullScreen);
// adding css styles nessasary for acurate 3D transformations.
spatialObject.style.type = 'text/css';
spatialObject.style.innerHTML = '* {-webkit-user-select: none; -webkit-touch-callout: none;} body, html{ height: 100%; margin:0; padding:0; overflow: hidden;}';
document.getElementsByTagName('head')[0].appendChild(spatialObject.style);
// this will be initialized once the frame creates a new SpatialInterface()
var realityInterface = null;
/**
* Network configuration loaded in loadObjectSocketIO from window.location
* based on the /n/:networkId/s/:secret/i/:destinationId format
*/
let urlObj = {
n: null, // Network identifier
i: null, // Destination identifier
s: null, // Network secret used for write access
};
/**
* Given a normal socket io title (message topic), adds all available
* network specifiers to the title.
*
* These include network id (n), secret (s), and destination id (i).
*
* For example, "/object/readPublicData" becomes
* "/n/asdf/s/secret/i/destId/object/readPublicData"
*
* @param {string} title
* @return {string} title with additional information from urlObj prepended
*/
function getIoTitle (title) {
if (urlObj.n) {
if (title.charAt(0) !== '/') title = '/' + title;
let network = null;
let destinationIdentifier = null;
let secret = null;
if (urlObj.n) network = urlObj.n;
if (urlObj.s) secret = urlObj.s;
if (urlObj.i) destinationIdentifier = urlObj.i;
let returnUrl = '';
if (network) returnUrl += '/n/' + network;
if (destinationIdentifier) returnUrl += '/i/' + destinationIdentifier;
if (secret) returnUrl += '/s/' + secret;
if (title) returnUrl += title;
return returnUrl;
} else {
return title;
}
}
/**
* automatically injects the socket.io script into the page once the editor has posted frame info into the page
* @param {{ip: string}} object - data object containing the server IP of the object
*/
function loadObjectSocketIo(object) {
var script = document.createElement('script');
script.type = 'text/javascript';
let defaultPort = '8080';
if (object.hasOwnProperty('port')) defaultPort = object.port;
var url = null;
let urlSplit = null;
if (parseInt(Number(defaultPort))) {
if (object.ip === spatialObject.serverIp) {
url = location.protocol + '//localhost:' + defaultPort;
} else {
url = location.protocol + '//' + object.ip + ':' + defaultPort;
}
} else {
urlSplit = location.pathname.split('/');
for (let i = 0; i < urlSplit.length; i++) {
if (['n', 'i', 's'].includes(urlSplit[i])) {
if (urlSplit[i + 1])
urlObj[urlSplit[i]] = urlSplit[i + 1];
i++;
}
}
url = location.protocol + '//' + object.ip + ':';
if (location.protocol === 'https:' || location.protocol === 'wss:') url += '' + 443; else url += '' + 80;
if (urlObj.n) url += '/n/' + urlObj.n;
if (urlObj.i) url += '/i/' + urlObj.i;
if (urlObj.s) url += '/s/' + urlObj.s;
}
spatialObject.serverPort = defaultPort;
spatialObject.socketIoUrl = url;
script.src = url + '/objectDefaultFiles/toolsocket.js';
script.addEventListener('load', function() {
if (realityInterface) {
// adds the API methods related to sending/receiving socket messages
realityInterface.injectSocketIoAPI();
}
});
document.body.appendChild(script);
}
/**
* Triggers all messageCallbacks functions.
* spatialObject.messageCallBacks.mainCall is the primary function always triggered by this, but additional
* messageCallbacks are added by calling the methods in realityInterface.injectMessageListenerAPI
*/
window.addEventListener('message', function (MSG) {
if (!MSG.data) { return; }
if (typeof MSG.data !== 'string') { return; }
var msgContent = JSON.parse(MSG.data);
for (var key in spatialObject.messageCallBacks) {
spatialObject.messageCallBacks[key](msgContent);
}
}, false);
// TODO: DEBUG what this really does and why it's needed
function tryResend() {
var windowMatches = window.location.search.match(/nodeKey=([^&]+)/);
if (!windowMatches) {
return;
}
var nodeKey = windowMatches[1];
parent.postMessage(JSON.stringify({resendOnElementLoad: true, nodeKey: nodeKey}), '*');
}
tryResend();
/**
* Helper function that posts entire basic state of spatialObject to parent
*/
function postAllDataToParent() {
console.log('check: ' + spatialObject.frame + ' fullscreen = ' + spatialObject.sendFullScreen);
if (typeof spatialObject.node !== 'undefined' || typeof spatialObject.frame !== 'undefined') {
parent.postMessage(JSON.stringify(
{
version: spatialObject.version,
node: spatialObject.node,
frame: spatialObject.frame,
object: spatialObject.object,
height: spatialObject.height,
width: spatialObject.width,
sendMatrix: spatialObject.sendMatrix,
sendMatrices: spatialObject.sendMatrices,
sendScreenPosition: spatialObject.sendScreenPosition,
sendAcceleration: spatialObject.sendAcceleration,
fullScreen: spatialObject.sendFullScreen,
fullscreenZPosition: spatialObject.fullscreenZPosition,
stickiness: spatialObject.sendSticky,
sendScreenObject: spatialObject.sendScreenObject,
moveDelay: spatialObject.moveDelay
}), '*'); // this needs to contain the final interface source
}
}
/**
* Helper function that posts object/frame/node/version to parent along with whatever custom properties you want to send
* @param {object} additionalProperties - JSON object containing any additional key/value pairs to send
*/
function postDataToParent(additionalProperties) {
if (typeof spatialObject.node !== 'undefined' || typeof spatialObject.frame !== 'undefined') {
var dataToSend = {
version: spatialObject.version,
node: spatialObject.node,
frame: spatialObject.frame,
object: spatialObject.object
};
if (additionalProperties) {
for (var key in additionalProperties) {
dataToSend[key] = additionalProperties[key];
}
}
parent.postMessage(JSON.stringify(dataToSend), '*');
}
}
/**
* receives POST messages from parent to change spatialObject state
* @param {object} msgContent - JSON contents received by the iframe's contentWindow.postMessage listener
*/
spatialObject.messageCallBacks.mainCall = function (msgContent) {
if (typeof msgContent.sendMessageToFrame !== 'undefined') {
return; // TODO: fix this bug in a cleaner way (github issue #17)
}
// Adds the socket.io connection and adds the related API methods
if (msgContent.objectData) { // objectData contains the IP necessary to load the socket script
if (!spatialObject.socketIoUrl) {
loadObjectSocketIo(msgContent.objectData);
}
}
if (typeof msgContent.firstInitialization !== 'undefined') {
spatialObject.wasToolJustCreated = msgContent.firstInitialization;
}
// initialize spatialObject for frames and add additional API methods
if (typeof msgContent.node !== 'undefined') {
if (!spatialObject.alreadyLoaded) {
if (spatialObject.sendFullScreen === false) {
spatialObject.height = document.body.scrollHeight;
spatialObject.width = document.body.scrollWidth;
}
spatialObject.node = msgContent.node;
spatialObject.frame = msgContent.frame;
spatialObject.object = msgContent.object;
// Post the default state of this frame to the parent application
postAllDataToParent();
if (realityInterface) {
// adds the API methods not reliant on the socket.io connection
realityInterface.injectAllNonSocketAPIs();
}
// triggers the onRealityInterfaceLoaded function
if (spatialObject.onload) {
spatialObject.onload();
spatialObject.onload = null;
}
}
if (spatialObject.sendScreenObject) {
if (realityInterface) {
realityInterface.activateScreenObject(); // make sure it gets sent with updated object,frame,node
}
}
spatialObject.alreadyLoaded = true;
// initialize spatialObject for logic block settings menus, which declare a new RealityLogic()
} else if (typeof msgContent.logic !== 'undefined') {
parent.postMessage(JSON.stringify(
{
version: spatialObject.version,
block: msgContent.block,
logic: msgContent.logic,
frame: msgContent.frame,
object: msgContent.object,
publicData: msgContent.publicData
}
)
// this needs to contain the final interface source
, '*');
spatialObject.block = msgContent.block;
spatialObject.logic = msgContent.logic;
spatialObject.frame = msgContent.frame;
spatialObject.object = msgContent.object;
spatialObject.publicData = msgContent.publicData;
if (spatialObject.sendScreenObject) {
if (realityInterface) {
realityInterface.activateScreenObject(); // make sure it gets sent with updated object,frame,node
}
}
}
// Add some additional message listeners which keep the spatialObject updated with application state
// TODO: should these only be added when specific message listeners have been registered via the API?
if (typeof msgContent.modelViewMatrix !== 'undefined') {
spatialObject.modelViewMatrix = msgContent.modelViewMatrix;
spatialObject.matrices.modelView = msgContent.modelViewMatrix;
}
if (typeof msgContent.projectionMatrix !== 'undefined') {
spatialObject.projectionMatrix = msgContent.projectionMatrix;
spatialObject.matrices.projection = msgContent.projectionMatrix;
}
if (typeof msgContent.allObjects !== 'undefined') {
spatialObject.matrices.allObjects = msgContent.allObjects;
}
if (typeof msgContent.devicePose !== 'undefined') {
spatialObject.matrices.devicePose = msgContent.devicePose;
}
if (typeof msgContent.groundPlaneMatrix !== 'undefined') {
spatialObject.matrices.groundPlane = msgContent.groundPlaneMatrix;
}
if (typeof msgContent.anchoredModelView !== 'undefined') {
spatialObject.matrices.anchoredModelView = msgContent.anchoredModelView;
}
// receives visibility state (changes when guiState changes or frame gets unloaded due to outside of view)
if (typeof msgContent.visibility !== 'undefined') {
spatialObject.visibility = msgContent.visibility;
// reload public data when it becomes visible
if (realityInterface && spatialObject.ioObject) {
realityInterface.reloadPublicData();
}
// ensure sticky fullscreen state gets sent to parent when it becomes visible
if (spatialObject.visibility === 'visible') {
if (typeof spatialObject.node !== 'undefined') {
if (spatialObject.sendSticky) {
// postAllDataToParent();
postDataToParent({
fullScreen: spatialObject.sendFullScreen,
fullscreenZPosition: spatialObject.fullscreenZPosition,
stickiness: spatialObject.sendSticky
});
}
}
}
}
// receives the guiState / "mode" that the app is in, e.g. ui, node, logic, etc...
if (typeof msgContent.interface !== 'undefined') {
spatialObject.interface = msgContent.interface;
}
// can be triggered by real-time system to refresh public data when editor received a message from another client
if (typeof msgContent.reloadPublicData !== 'undefined') {
realityInterface.reloadPublicData();
}
// handle synthetic touch events and pass them into the page contents
if (typeof msgContent.event !== 'undefined' && typeof msgContent.event.pointerId !== 'undefined') {
// eventData looks like {type: "pointerdown", pointerId: 29887780, pointerType: "touch", x: 334, y: 213}
var eventData = msgContent.event;
var event = new PointerEvent(eventData.type, {
view: window,
bubbles: true,
cancelable: true,
pointerId: eventData.pointerId,
pointerType: eventData.pointerType,
x: eventData.x,
y: eventData.y,
clientX: eventData.x,
clientY: eventData.y,
pageX: eventData.x,
pageY: eventData.y,
screenX: eventData.x,
screenY: eventData.y,
button: eventData.button,
});
if (typeof eventData.projectedZ !== 'undefined') {
event.projectedZ = eventData.projectedZ;
}
if (typeof eventData.worldIntersectPoint !== 'undefined') {
event.worldIntersectPoint = eventData.worldIntersectPoint;
}
// send unacceptedTouch message if this interface wants touches to pass through it
if (spatialObject.touchDeciderRegistered && eventData.type === 'pointerdown') {
var touchAccepted = spatialObject.touchDecider(eventData);
if (!touchAccepted) {
// console.log('didn\'t touch anything acceptable... propagate to next frame (if any)');
postDataToParent({
unacceptedTouch: eventData
});
spatialObject.unacceptedTouchInProgress = true;
return;
}
}
if (spatialObject.touchDeciderRegistered && spatialObject.unacceptedTouchInProgress) {
postDataToParent({
unacceptedTouch: eventData
});
if (eventData.type === 'pointerup') {
spatialObject.unacceptedTouchInProgress = false;
}
return;
}
// if it wasn't unaccepted, dispatch a touch event into the page contents
var elt = document.elementFromPoint(eventData.x, eventData.y) || document.body;
function forElementAndParentsRecursively(element, callback) {
callback(element);
if (element.parentNode && element.parentNode.tagName !== 'HTML' && element.parentNode !== document) {
forElementAndParentsRecursively(element.parentNode, callback);
}
}
function elementOrRecursiveParentIsOfClass(element, className) {
var foundClassOnAnyElement = false;
forElementAndParentsRecursively(element, function(thatElement) {
if (thatElement.classList.contains(className)) {
foundClassOnAnyElement = true;
}
});
return foundClassOnAnyElement;
}
// see if it is a realityInteraction div
if (eventData.type === 'pointerdown') {
if (spatialObject.customInteractionMode) {
if (!spatialObject.invertedInteractionMode) {
if (elementOrRecursiveParentIsOfClass(elt, 'realityInteraction')) {
// if (elt.classList.contains('realityInteraction')) {
if (elt) elt.dispatchEvent(event);
postDataToParent({
pointerDownResult: 'interaction'
});
} else {
postDataToParent({
pointerDownResult: 'nonInteraction'
});
}
} else {
// do the opposite for each condition
if (elementOrRecursiveParentIsOfClass(elt, 'realityInteraction')) {
postDataToParent({
pointerDownResult: 'nonInteraction'
});
} else {
if (elt) elt.dispatchEvent(event);
postDataToParent({
pointerDownResult: 'interaction'
});
}
}
} else {
if (elt) elt.dispatchEvent(event);
}
} else {
if (elt) elt.dispatchEvent(event);
}
// send acceptedTouch message to stop the touch propagation
if (eventData.type === 'pointerdown') {
postDataToParent({
acceptedTouch: eventData
});
}
}
// can be triggered by real-time system to refresh public data when editor received a message from another client
if (typeof msgContent.workerId !== 'undefined') {
console.log('set workerId to ' + msgContent.workerId);
// eslint-disable-next-line no-global-assign
workerId = msgContent.workerId;
}
};
/**
* Defines the SpatialInterface object
* A reality interface provides a SocketIO API, a Post Message API, and several other APIs
* All supported methods are listed in this constructor, but the implementation of most methods are separated
* into each category (socket, post message, listener, etc) in subsequent SpatialInterface "inject__API" functions
* @constructor
*/
function SpatialInterface() {
this.publicData = spatialObject.publicData;
this.pendingSends = [];
this.pendingIos = [];
this.iosObject = undefined;
this.ioCallback = undefined;
var self = this;
this.spatialInterfaceLoadedCallbacks = [];
/**
* Adds an onload callback that will wait until this SpatialInterfaces receives its object/frame data
* @param {function} callback
*/
this.onRealityInterfaceLoaded = function(callback) {
if (spatialObject.object && spatialObject.frame) {
callback();
} else {
this.spatialInterfaceLoadedCallbacks.push(callback);
}
};
this.onSpatialInterfaceLoaded = this.onRealityInterfaceLoaded;
spatialObject.onload = () => this.spatialInterfaceLoadedCallbacks.forEach(cb => cb());
// Adds the API functions that allow a frame to send and receive socket messages (e.g. write and addReadListener)
if (typeof io !== 'undefined') {
this.injectSocketIoAPI();
} else {
this.ioObject = {
on: function() {
console.log('ioObject.on stub called, please don\'t');
}
};
/**
* If you call a SocketIO API function before that API has been initialized, it will get queued up as a stub
* and executed as soon as that API is fully loaded
* @param {string} name - the name of the function that should be called
* @return {Function}
*/
function makeIoStub(name) {
return function() {
self.pendingIos.push({name: name, args: arguments});
};
}
// queue-up calls to function stubs that will get called for real when the socket is created
this.write = makeIoStub('write');
this.addReadListener = makeIoStub('addReadListener');
this.readPublicData = makeIoStub('readPublicData');
this.addReadPublicDataListener = makeIoStub('addReadPublicDataListener');
this.writePublicData = makeIoStub('writePublicData');
this.reloadPublicData = makeIoStub('reloadPublicData');
this.addScreenObjectListener = makeIoStub('addScreenObjectListener');
this.addScreenObjectReadListener = makeIoStub('addScreenObjectReadListener');
// deprecated or unimplemented methods
this.read = makeIoStub('read');
this.readRequest = makeIoStub('readRequest');
this.writePrivateData = makeIoStub('writePrivateData');
/**
* Internet of Screens APIs
*/
{
this.setIOCallback = makeIoStub('setIOCallback');
this.setIOSInterface = makeIoStub('setIOSInterface');
}
}
if (spatialObject.object) {
// Adds the additional API functions that aren't dependent on the socket
this.injectAllNonSocketAPIs();
} else {
/**
* If you call a Post Message API function before that API has been initialized, it will get queued up as a stub
* and executed as soon as that API is fully loaded
* @param {string} name - the name of the function that should be called
* @return {Function}
*/
function makeSendStub(name) {
return function() {
self.pendingSends.push({name: name, args: arguments});
};
}
/**
* Post Message APIs
*/
{
this.sendGlobalMessage = makeSendStub('sendGlobalMessage');
this.sendMessageToFrame = makeSendStub('sendMessageToFrame');
this.sendMessageToTool = makeSendStub('sendMessageToTool');
this.sendEnvelopeMessage = makeSendStub('sendEnvelopeMessage');
this.initNodeWithOptions = makeSendStub('initNodeWithOptions');
this.initNode = makeSendStub('initNode');
this.sendCreateNode = makeSendStub('sendCreateNode');
this.sendMoveNode = makeSendStub('sendMoveNode');
this.sendResetNodes = makeSendStub('sendResetNodes');
this.subscribeToMatrix = makeSendStub('subscribeToMatrix');
this.subscribeToModelAndView = makeSendStub('subscribeToModelAndView');
this.subscribeToScreenPosition = makeSendStub('subscribeToScreenPosition');
this.subscribeToDevicePoseMatrix = makeSendStub('subscribeToDevicePoseMatrix');
this.subscribeToAllMatrices = makeSendStub('subscribeToAllMatrices');
this.subscribeToGroundPlaneMatrix = makeSendStub('subscribeToGroundPlaneMatrix');
this.subscribeToAnchoredModelView = makeSendStub('subscribeToAnchoredModelView');
this.subscribeToDeviceDistance = makeSendStub('subscribeToDeviceDistance');
this.subscribeToAcceleration = makeSendStub('subscribeToAcceleration');
this.setFullScreenOn = makeSendStub('setFullScreenOn');
this.setFullScreenOff = makeSendStub('setFullScreenOff');
this.setStickyFullScreenOn = makeSendStub('setStickyFullScreenOn');
this.setStickinessOff = makeSendStub('setStickinessOff');
this.setExclusiveFullScreenOn = makeSendStub('setExclusiveFullScreenOn');
this.setExclusiveFullScreenOff = makeSendStub('setExclusiveFullScreenOff');
this.isExclusiveFullScreenOccupied = makeSendStub('isExclusiveFullScreenOccupied');
this.stickNodeToScreen = makeSendStub('stickNodeToScreen');
this.unstickNodeFromScreen = makeSendStub('unstickNodeFromScreen');
this.setAlwaysFaceCamera = makeSendStub('setAlwaysFaceCamera');
this.startVideoRecording = makeSendStub('startVideoRecording');
this.stopVideoRecording = makeSendStub('stopVideoRecording');
this.createVideoPlayback = makeSendStub('createVideoPlayback');
this.disposeVideoPlayback = makeSendStub('disposeVideoPlayback');
this.setVideoPlaybackCurrentTime = makeSendStub('setVideoPlaybackCurrentTime');
this.playVideoPlayback = makeSendStub('playVideoPlayback');
this.pauseVideoPlayback = makeSendStub('pauseVideoPlayback');
this.startVirtualizerRecording = makeSendStub('startVirtualizerRecording');
this.stopVirtualizerRecording = makeSendStub('stopVirtualizerRecording');
this.getScreenshotBase64 = makeSendStub('getScreenshotBase64');
this.openKeyboard = makeSendStub('openKeyboard');
this.closeKeyboard = makeSendStub('closeKeyboard');
this.onKeyboardClosed = makeSendStub('onKeyboardClosed');
this.onKeyUp = makeSendStub('onKeyUp');
this.setMoveDelay = makeSendStub('setMoveDelay');
this.setVisibilityDistance = makeSendStub('setVisibilityDistance');
this.activateScreenObject = makeSendStub('activateScreenObject');
this.enableCustomInteractionMode = makeSendStub('enableCustomInteractionMode');
this.enableCustomInteractionModeInverted = makeSendStub('enableCustomInteractionModeInverted');
this.setInteractableDivs = makeSendStub('setInteractableDivs');
this.disableCustomInteractionMode = makeSendStub('disableCustomInteractionMode');
this.subscribeToFrameCreatedEvents = makeSendStub('subscribeToFrameCreatedEvents');
this.subscribeToFrameDeletedEvents = makeSendStub('subscribeToFrameDeletedEvents');
this.subscribeToToolCreatedEvents = makeSendStub('subscribeToToolCreatedEvents');
this.subscribeToToolDeletedEvents = makeSendStub('subscribeToToolDeletedEvents');
this.announceVideoPlay = makeSendStub('announceVideoPlay');
this.subscribeToVideoPauseEvents = makeSendStub('subscribeToVideoPauseEvents');
this.ignoreAllTouches = makeSendStub('ignoreAllTouches');
this.changeFrameSize = makeSendStub('changeFrameSize');
this.changeToolSize = makeSendStub('changeToolSize');
this.onWindowResized = makeSendStub('onWindowResized');
this.prefersAttachingToWorld = makeSendStub('prefersAttachingToWorld');
this.prefersAttachingToObjects = makeSendStub('prefersAttachingToObjects');
this.subscribeToWorldId = makeSendStub('subscribeToWorldId');
this.subscribeToPositionInWorld = makeSendStub('subscribeToPositionInWorld');
this.getPositionInWorld = makeSendStub('getPositionInWorld');
this.subscribeToObjectsOfType = makeSendStub('subscribeToObjectsOfType');
this.errorNotification = makeSendStub('errorNotification');
this.useWebGlWorker = makeSendStub('useWebGlWorker');
this.wasToolJustCreated = makeSendStub('wasToolJustCreated');
this.setPinned = makeSendStub('setPinned');
this.promptForArea = makeSendStub('promptForArea');
this.getEnvironmentVariables = makeSendStub('getEnvironmentVariables');
this.getUserDetails = makeSendStub('getUserDetails');
this.analyticsOpen = makeSendStub('analyticsOpen');
this.analyticsClose = makeSendStub('analyticsClose');
this.analyticsFocus = makeSendStub('analyticsFocus');
this.analyticsBlur = makeSendStub('analyticsBlur');
this.analyticsSetCursorTime = makeSendStub('analyticsSetCursorTime');
this.analyticsSetHighlightRegion = makeSendStub('analyticsSetHighlightRegion');
this.analyticsSetDisplayRegion = makeSendStub('analyticsSetDisplayRegion');
this.analyticsHydrateRegionCards = makeSendStub('analyticsHydrateRegionCards');
this.analyticsSetLens = makeSendStub('analyticsSetLens');
this.analyticsSetLensDetail = makeSendStub('analyticsSetLensDetail');
this.analyticsSetSpaghettiAttachPoint = makeSendStub('analyticsSetSpaghettiAttachPoint');
this.analyticsSetSpaghettiVisible = makeSendStub('analyticsSetSpaghettiVisible');
this.analyticsSetAllClonesVisible = makeSendStub('analyticsSetAllClonesVisible');
// deprecated methods
this.sendToBackground = makeSendStub('sendToBackground');
}
/**
* Message Listener APIs
*/
{
this.addGlobalMessageListener = makeSendStub('addGlobalMessageListener');
this.addFrameMessageListener = makeSendStub('addFrameMessageListener');
this.addToolMessageListener = makeSendStub('addToolMessageListener');
this.addMatrixListener = makeSendStub('addMatrixListener');
this.addModelAndViewListener = makeSendStub('addModelAndViewListener');
this.addAllObjectMatricesListener = makeSendStub('addAllObjectMatricesListener');
this.addDevicePoseMatrixListener = makeSendStub('addDevicePoseMatrixListener');
this.addGroundPlaneMatrixListener = makeSendStub('addGroundPlaneMatrixListener');
this.addAnchoredModelViewListener = makeSendStub('addAnchoredModelViewListener');
this.addScreenPositionListener = makeSendStub('addScreenPositionListener');
this.cancelScreenPositionListener = makeSendStub('cancelScreenPositionListener');
this.addVisibilityListener = makeSendStub('addVisibilityListener');
this.addInterfaceListener = makeSendStub('addInterfaceListener');
this.addIsMovingListener = makeSendStub('addIsMovingListener');
// deprecated or unimplemented methods
this.addAccelerationListener = makeSendStub('addAccelerationListener');
}
/**
* Setter/Getter APIs
*/
{
// Getters
this.getVisibility = makeSendStub('getVisibility'); // TODO: getters don't make sense as stubs
this.getInterface = makeSendStub('getInterface'); // TODO: but maybe OK to keep here for consistency
this.getPositionX = makeSendStub('getPositionX');
this.getPositionY = makeSendStub('getPositionY');
this.getPositionZ = makeSendStub('getPositionZ');
this.getProjectionMatrix = makeSendStub('getProjectionMatrix');
this.getModelViewMatrix = makeSendStub('getModelViewMatrix');
this.getGroundPlaneMatrix = makeSendStub('getGroundPlaneMatrix');
this.getAnchoredModelView = makeSendStub('getAnchoredModelView');
this.getDevicePoseMatrix = makeSendStub('getDevicePoseMatrix');
this.getAllObjectMatrices = makeSendStub('getAllObjectMatrices');
this.getUnitValue = makeSendStub('getUnitValue');
this.getScreenDimensions = makeSendStub('getScreenDimensions');
this.getMoveDelay = makeSendStub('getMoveDelay');
// deprecated getters
this.search = makeSendStub('search');
// Setters
this.registerTouchDecider = makeSendStub('registerTouchDecider');
this.unregisterTouchDecider = makeSendStub('unregisterTouchDecider');
}
}
realityInterface = this;
}
SpatialInterface.prototype.injectAllNonSocketAPIs = function() {
// Adds the API functions that allow a frame to post messages to its parent (e.g. setFullScreenOn and subscribeToMatrix)
this.injectPostMessageAPI();
// Adds the API functions that allow a frame to add message listeners (e.g. addGlobalMessageListener and addMatrixListener)
this.injectMessageListenerAPI();
// Adds the API functions that only change or retrieve values from spatialObject (e.g. getVisibility and registerTouchDecider)
this.injectSetterGetterAPI();
for (var i = 0; i < this.pendingSends.length; i++) {
var pendingSend = this.pendingSends[i];
this[pendingSend.name].apply(this, pendingSend.args);
}
this.pendingSends = [];
// console.log('All non-socket APIs are loaded and injected into the object.js API');
};
SpatialInterface.prototype.injectSocketIoAPI = function() {
var self = this;
this.ioObject = io.connect(spatialObject.socketIoUrl);
// Adds the custom API functions that allow a frame to connect to the Internet of Screens application
this.injectInternetOfScreensAPI();
// keeps track of previous values of nodes so we don't re-send unnecessarily
this.oldNumberList = {};
// reload a frame if its socket reconnects
this.ioObject.on('reconnect', function() {
console.log('reconnect');
window.location.reload();
// notify the containing application that a frame socket reconnected, for additional optional behavior (e.g. make the screen reload)
if (spatialObject.object && spatialObject.frame) {
parent.postMessage(JSON.stringify({
version: spatialObject.version,
node: spatialObject.node,
frame: spatialObject.frame,
object: spatialObject.object,
socketReconnect: true
}), '*');
}
});
this.ioObject.on('close', function() {
console.log('frame socket closed');
});
/**
* Subscribes this socket to data values being written to nodes on this frame
*/
this.sendRealityEditorSubscribe = function () {
var timeoutFunction = function() {
if (spatialObject.object) {
// console.log('emit sendRealityEditorSubscribe');
self.ioObject.emit(getIoTitle('/subscribe/realityEditor'), JSON.stringify({
object: spatialObject.object,
frame: spatialObject.frame,
protocol: spatialObject.protocol
}));
}
};
// Call it a few times to help ensure it succeeds
setTimeout(timeoutFunction, 10);
setTimeout(timeoutFunction, 50);
setTimeout(timeoutFunction, 100);
setTimeout(timeoutFunction, 1000);
};
this.sendRealityEditorSubscribe();
/**
* @param {string} node - the name of the node
* @param {number} value - the new value you are writing to it
* @param mode - optional
* @param unit - optional
* @param unitMin - optional
* @param unitMax - optional
* @param {boolean|undefined} forceWrite - optional. if true, sends the value even if it hasn't changed since the last write
*/
this.write = function (node, value, mode, unit, unitMin, unitMax, forceWrite) {
mode = mode || 'f';
unit = unit || false;
unitMin = unitMin || 0;
unitMax = unitMax || 1;
var data = {value: value, mode: mode, unit: unit, unitMin: unitMin, unitMax: unitMax};
if (!(node in self.oldNumberList)) {
self.oldNumberList[node] = null;
}
if (self.oldNumberList[node] !== value || forceWrite) {
self.ioObject.emit(getIoTitle('object'), JSON.stringify({
object: spatialObject.object,
frame: spatialObject.frame,
node: spatialObject.frame + node,
data: data
}));
}
self.oldNumberList[node] = value;
};
/**
* Adds a callback function for when new data arrives at the specified node
* @param {string} node - node name
* @param {function} callback
*/
this.addReadListener = function (node, callback) {
// TODO: add getIoTitle?
self.ioObject.on('object', function (msg) {
var thisMsg = JSON.parse(msg);
if (typeof thisMsg.node !== 'undefined') {
if (thisMsg.node === spatialObject.frame + node) {
if (thisMsg.data) {
callback(thisMsg.data);
}
}
}
});
};
/**
* Returns the current value of this node's publicData (without making a new network request)
* @param {string} node - node name
* @param {string} valueName - name of the property to read
* @param {*|undefined} value - default value for the property if it doesn't exist yet
* @return {*}
*/
this.readPublicData = function (node, valueName, value) {
if (!value) value = 0;
if (typeof spatialObject.publicData[node] === 'undefined') {
spatialObject.publicData[node] = {};
}
if (typeof spatialObject.publicData[node][valueName] === 'undefined') {
spatialObject.publicData[node][valueName] = value;
return value;
} else {
return spatialObject.publicData[node][valueName];
}
};
// TODO: this function implementation is different in the server and the userinterface... standardize it
/**
* Adds a callback function that will be triggered whenever the specified property of the node's publicData
* is written to (and also when a /subscribe/realityEditorPublicData message is sent)
* @param {string} node
* @param {string} valueName
* @param {function} callback
*/
this.addReadPublicDataListener = function (node, valueName, callback) {
// TODO: add getIoTitle?
self.ioObject.on('object/publicData', function (msg) {
var thisMsg = JSON.parse(msg);
if (typeof thisMsg.sessionUuid !== 'undefined') {
if (thisMsg.sessionUuid === sessionUuid) {
console.log('ignoring message sent by self (publicData)');
return;
}
}
if (typeof thisMsg.publicData === 'undefined') return;
if (thisMsg.node !== spatialObject.frame + node) return;
if (typeof thisMsg.publicData[node] === 'undefined') {
// convert format if possible, otherwise return
if (typeof thisMsg.publicData[valueName] !== 'undefined') {
var publicDataKeys = Object.keys(thisMsg.publicData);
thisMsg.publicData[node] = {};
publicDataKeys.forEach(function(existingKey) {
thisMsg.publicData[node][existingKey] = thisMsg.publicData[existingKey];
});
// console.warn('converted incorrect publicData format in object/publicData listener');
} else {
return;
}
}
if (typeof thisMsg.publicData[node][valueName] === 'undefined') return;
var isUnset = (typeof spatialObject.publicData[node] === 'undefined') ||
(typeof spatialObject.publicData[node][valueName] === 'undefined');
// only trigger the callback if there is new public data, otherwise infinite loop possible
if (isUnset || JSON.stringify(thisMsg.publicData[node][valueName]) !== JSON.stringify(spatialObject.publicData[node][valueName])) {
if (typeof spatialObject.publicData[node] === 'undefined') {