-
-
Notifications
You must be signed in to change notification settings - Fork 411
Expand file tree
/
Copy pathindex.js
More file actions
1141 lines (1014 loc) · 34.1 KB
/
index.js
File metadata and controls
1141 lines (1014 loc) · 34.1 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
import macro from 'vtk.js/Sources/macros';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
import Constants from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor/Constants';
const { Axis, Device, Input } = Constants;
const { vtkWarningMacro, vtkErrorMacro, normalizeWheel, vtkOnceErrorMacro } =
macro;
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
const deviceInputMap = {
'xr-standard': {
button: [
Input.Trigger,
Input.Grip,
Input.TrackPad,
Input.Thumbstick,
Input.A,
Input.B,
],
axis: [Axis.TouchpadX, Axis.TouchpadY, Axis.ThumbstickX, Axis.ThumbstickY],
},
};
const handledEvents = [
'StartAnimation',
'Animation',
'EndAnimation',
'MouseEnter',
'MouseLeave',
'StartMouseMove',
'MouseMove',
'EndMouseMove',
'LeftButtonPress',
'LeftButtonRelease',
'MiddleButtonPress',
'MiddleButtonRelease',
'RightButtonPress',
'RightButtonRelease',
'KeyPress',
'KeyDown',
'KeyUp',
'StartMouseWheel',
'MouseWheel',
'EndMouseWheel',
'StartPinch',
'Pinch',
'EndPinch',
'StartPan',
'Pan',
'EndPan',
'StartRotate',
'Rotate',
'EndRotate',
'Button3D',
'Move3D',
'StartPointerLock',
'EndPointerLock',
'StartInteraction',
'Interaction',
'EndInteraction',
];
function preventDefault(event) {
if (event.cancelable) {
event.stopPropagation();
event.preventDefault();
}
return false;
}
// ----------------------------------------------------------------------------
// vtkRenderWindowInteractor methods
// ----------------------------------------------------------------------------
function vtkRenderWindowInteractor(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkRenderWindowInteractor');
// Initialize list of requesters
const animationRequesters = new Set();
// track active event listeners to handle simultaneous button tracking
let activeListenerCount = 0;
// Public API methods
//----------------------------------------------------------------------
publicAPI.start = () => {
// Let the compositing handle the event loop if it wants to.
// if (publicAPI.HasObserver(vtkCommand::StartEvent) && !publicAPI.HandleEventLoop) {
// publicAPI.invokeEvent({ type: 'StartEvent' });
// return;
// }
// As a convenience, initialize if we aren't initialized yet.
if (!model.initialized) {
publicAPI.initialize();
if (!model.initialized) {
return;
}
}
// Pass execution to the subclass which will run the event loop,
// this will not return until TerminateApp is called.
publicAPI.startEventLoop();
};
//----------------------------------------------------------------------
publicAPI.setRenderWindow = (aren) => {
vtkErrorMacro(
'you want to call setView(view) instead of setRenderWindow on a vtk.js interactor'
);
};
//----------------------------------------------------------------------
publicAPI.setInteractorStyle = (style) => {
if (model.interactorStyle !== style) {
if (model.interactorStyle != null) {
model.interactorStyle.setInteractor(null);
}
model.interactorStyle = style;
if (model.interactorStyle != null) {
if (model.interactorStyle.getInteractor() !== publicAPI) {
model.interactorStyle.setInteractor(publicAPI);
}
}
}
};
//---------------------------------------------------------------------
publicAPI.initialize = () => {
model.initialized = true;
publicAPI.enable();
publicAPI.render();
};
publicAPI.enable = () => publicAPI.setEnabled(true);
publicAPI.disable = () => publicAPI.setEnabled(false);
publicAPI.startEventLoop = () => vtkWarningMacro('empty event loop');
function updateCurrentRenderer(x, y) {
if (!model._forcedRenderer) {
model.currentRenderer = publicAPI.findPokedRenderer(x, y);
}
}
publicAPI.getCurrentRenderer = () => {
if (model.currentRenderer) {
return model.currentRenderer;
}
updateCurrentRenderer(0, 0);
return model.currentRenderer;
};
function getScreenEventPositionFor(source) {
const bounds = model.container.getBoundingClientRect();
const canvas = model.view.getCanvas();
const scaleX = canvas.width / bounds.width;
const scaleY = canvas.height / bounds.height;
const position = {
x: scaleX * (source.clientX - bounds.left),
y: scaleY * (bounds.height - source.clientY + bounds.top),
z: 0,
};
updateCurrentRenderer(position.x, position.y);
return position;
}
function getTouchEventPositionsFor(touches) {
const positions = {};
for (let i = 0; i < touches.length; i++) {
const touch = touches[i];
positions[touch.identifier] = getScreenEventPositionFor(touch);
}
return positions;
}
function getModifierKeysFor(event) {
return {
controlKey: event.ctrlKey,
altKey: event.altKey,
shiftKey: event.shiftKey,
};
}
function getKeysFor(event) {
const modifierKeys = getModifierKeysFor(event);
const keys = {
key: event.key,
keyCode: event.charCode,
...modifierKeys,
};
return keys;
}
function interactionRegistration(addListeners, force = false) {
const rootElm = document;
const method = addListeners ? 'addEventListener' : 'removeEventListener';
const invMethod = addListeners ? 'removeEventListener' : 'addEventListener';
if (!force && !addListeners && activeListenerCount > 0) {
--activeListenerCount;
}
// only add/remove listeners when there are no registered listeners
if (!activeListenerCount || force) {
activeListenerCount = 0;
if (model.container) {
model.container[invMethod]('mousemove', publicAPI.handleMouseMove);
}
rootElm[method]('mouseup', publicAPI.handleMouseUp);
rootElm[method]('mousemove', publicAPI.handleMouseMove);
rootElm[method]('touchend', publicAPI.handleTouchEnd, false);
rootElm[method]('touchcancel', publicAPI.handleTouchEnd, false);
rootElm[method]('touchmove', publicAPI.handleTouchMove, false);
}
if (!force && addListeners) {
++activeListenerCount;
}
}
publicAPI.bindEvents = (container) => {
model.container = container;
container.addEventListener('contextmenu', preventDefault);
// container.addEventListener('click', preventDefault); // Avoid stopping event propagation
container.addEventListener('wheel', publicAPI.handleWheel);
container.addEventListener('DOMMouseScroll', publicAPI.handleWheel);
container.addEventListener('mouseenter', publicAPI.handleMouseEnter);
container.addEventListener('mouseleave', publicAPI.handleMouseLeave);
container.addEventListener('mousemove', publicAPI.handleMouseMove);
container.addEventListener('mousedown', publicAPI.handleMouseDown);
document.addEventListener('keypress', publicAPI.handleKeyPress);
document.addEventListener('keydown', publicAPI.handleKeyDown);
document.addEventListener('keyup', publicAPI.handleKeyUp);
document.addEventListener(
'pointerlockchange',
publicAPI.handlePointerLockChange
);
container.addEventListener('touchstart', publicAPI.handleTouchStart, false);
};
publicAPI.unbindEvents = () => {
// force unbinding listeners
interactionRegistration(false, true);
model.container.removeEventListener('contextmenu', preventDefault);
// model.container.removeEventListener('click', preventDefault); // Avoid stopping event propagation
model.container.removeEventListener('wheel', publicAPI.handleWheel);
model.container.removeEventListener(
'DOMMouseScroll',
publicAPI.handleWheel
);
model.container.removeEventListener(
'mouseenter',
publicAPI.handleMouseEnter
);
model.container.removeEventListener(
'mouseleave',
publicAPI.handleMouseLeave
);
model.container.removeEventListener('mousemove', publicAPI.handleMouseMove);
model.container.removeEventListener('mousedown', publicAPI.handleMouseDown);
document.removeEventListener('keypress', publicAPI.handleKeyPress);
document.removeEventListener('keydown', publicAPI.handleKeyDown);
document.removeEventListener('keyup', publicAPI.handleKeyUp);
document.removeEventListener(
'pointerlockchange',
publicAPI.handlePointerLockChange
);
model.container.removeEventListener(
'touchstart',
publicAPI.handleTouchStart
);
model.container = null;
};
publicAPI.handleKeyPress = (event) => {
const data = getKeysFor(event);
publicAPI.keyPressEvent(data);
};
publicAPI.handleKeyDown = (event) => {
const data = getKeysFor(event);
publicAPI.keyDownEvent(data);
};
publicAPI.handleKeyUp = (event) => {
const data = getKeysFor(event);
publicAPI.keyUpEvent(data);
};
publicAPI.handleMouseDown = (event) => {
if (event.button > 2) {
// ignore events from extra mouse buttons such as `back` and `forward`
return;
}
interactionRegistration(true);
preventDefault(event);
const callData = {
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
switch (event.button) {
case 0:
publicAPI.leftButtonPressEvent(callData);
break;
case 1:
publicAPI.middleButtonPressEvent(callData);
break;
case 2:
publicAPI.rightButtonPressEvent(callData);
break;
default:
vtkErrorMacro(`Unknown mouse button pressed: ${event.button}`);
break;
}
};
//----------------------------------------------------------------------
publicAPI.requestPointerLock = () => {
const canvas = publicAPI.getView().getCanvas();
canvas.requestPointerLock();
};
//----------------------------------------------------------------------
publicAPI.exitPointerLock = () => document.exitPointerLock();
//----------------------------------------------------------------------
publicAPI.isPointerLocked = () => !!document.pointerLockElement;
//----------------------------------------------------------------------
publicAPI.handlePointerLockChange = () => {
if (publicAPI.isPointerLocked()) {
publicAPI.startPointerLockEvent();
} else {
publicAPI.endPointerLockEvent();
}
};
//----------------------------------------------------------------------
function forceRender() {
if (model.view && model.enabled && model.enableRender) {
model.inRender = true;
model.view.traverseAllPasses();
model.inRender = false;
}
// outside the above test so that third-party code can redirect
// the render to the appropriate class
publicAPI.invokeRenderEvent();
}
publicAPI.requestAnimation = (requestor) => {
if (requestor === undefined) {
vtkErrorMacro(`undefined requester, can not start animating`);
return;
}
if (animationRequesters.has(requestor)) {
vtkWarningMacro(`requester is already registered for animating`);
return;
}
animationRequesters.add(requestor);
if (animationRequesters.size === 1 && !model.xrAnimation) {
model.lastFrameTime = 0.1;
model.lastFrameStart = Date.now();
model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
publicAPI.startAnimationEvent();
}
};
publicAPI.isAnimating = () =>
model.xrAnimation || model.animationRequest !== null;
publicAPI.cancelAnimation = (requestor, skipWarning = false) => {
if (!animationRequesters.has(requestor)) {
if (!skipWarning) {
const requestStr =
requestor && requestor.getClassName
? requestor.getClassName()
: requestor;
vtkWarningMacro(`${requestStr} did not request an animation`);
}
return;
}
animationRequesters.delete(requestor);
if (model.animationRequest && animationRequesters.size === 0) {
cancelAnimationFrame(model.animationRequest);
model.animationRequest = null;
publicAPI.endAnimationEvent();
publicAPI.render();
}
};
publicAPI.switchToXRAnimation = () => {
// cancel existing animation if any
if (model.animationRequest) {
cancelAnimationFrame(model.animationRequest);
model.animationRequest = null;
}
model.xrAnimation = true;
};
publicAPI.returnFromXRAnimation = () => {
model.xrAnimation = false;
if (animationRequesters.size !== 0) {
model.FrameTime = -1;
model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
}
};
publicAPI.updateXRGamepads = (xrSession, xrFrame, xrRefSpace) => {
// Fire binary events when axis magnitude crosses threshold
const axisThreshold = 0.9;
// watch for when buttons change state and fire events
xrSession.inputSources.forEach((inputSource) => {
const gp = inputSource.gamepad;
if (gp === null) return;
const pose = xrFrame.getPose(inputSource.gripSpace, xrRefSpace);
const hand = inputSource.handedness;
// Init
if (!(gp.index in model.lastGamepadValues)) {
model.lastGamepadValues[gp.index] = {
left: {
buttons: {},
axes: {},
},
right: {
buttons: {},
axes: {},
},
};
}
// Query buttons
for (let b = 0; b < gp.buttons.length; ++b) {
// Init
if (!(b in model.lastGamepadValues[gp.index][hand].buttons)) {
model.lastGamepadValues[gp.index][hand].buttons[b] = false;
}
// State change
if (
model.lastGamepadValues[gp.index][hand].buttons[b] !==
gp.buttons[b].pressed
) {
publicAPI.button3DEvent({
gamepad: gp,
position: pose.transform.position,
orientation: pose.transform.orientation,
pressed: gp.buttons[b].pressed,
device:
hand === 'left' ? Device.LeftController : Device.RightController,
input:
deviceInputMap[gp.mapping] &&
deviceInputMap[gp.mapping]['button'][b]
? deviceInputMap[gp.mapping]['button'][b]
: Input.Trigger,
});
model.lastGamepadValues[gp.index][hand].buttons[b] =
gp.buttons[b].pressed;
}
// State
if (gp.buttons[b].pressed) {
publicAPI.move3DEvent({
gamepad: gp,
position: pose.transform.position,
orientation: pose.transform.orientation,
device:
hand === 'left' ? Device.LeftController : Device.RightController,
input:
deviceInputMap[gp.mapping] &&
deviceInputMap[gp.mapping]['button'][b]
? deviceInputMap[gp.mapping]['button'][b]
: Input.Unknown,
});
}
}
for (let a = 0; a < gp.axes.length; ++a) {
// Init
if (!(a in model.lastGamepadValues[gp.index][hand].axes)) {
model.lastGamepadValues[gp.index][hand].axes[a] = 0.0;
}
// State change
if (
gp.axes[a] > axisThreshold &&
model.lastGamepadValues[gp.index][hand].axes[a] < axisThreshold
) {
}
// State
// TODO debounce
if (gp.axes[a] > axisThreshold) {
//model.rotate3DEvent({
// gamepad: gp,
// position: pose.transform.position,
// orientation: pose.transform.orientation,
// device:
// hand === 'left' ? Device.LeftController : Device.RightController,
// input: deviceInputMap[gp.mapping] && deviceInputMap[gp.mapping]['axis'][a]
// ? deviceInputMap[gp.mapping]['axis'][a]
// : Axis.Unknown,
// value: gp.axes[a],
//});
}
}
});
};
publicAPI.handleMouseMove = (event) => {
// Do not consume event for move
// preventDefault(event);
const callData = {
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
if (model.moveTimeoutID === 0) {
publicAPI.startMouseMoveEvent(callData);
} else {
publicAPI.mouseMoveEvent(callData);
clearTimeout(model.moveTimeoutID);
}
// start a timer to keep us animating while we get mouse move events
model.moveTimeoutID = setTimeout(() => {
publicAPI.endMouseMoveEvent();
model.moveTimeoutID = 0;
}, 200);
};
publicAPI.handleAnimation = () => {
const currTime = Date.now();
if (model.FrameTime === -1.0) {
model.lastFrameTime = 0.1;
} else {
model.lastFrameTime = (currTime - model.lastFrameStart) / 1000.0;
}
model.lastFrameTime = Math.max(0.01, model.lastFrameTime);
model.lastFrameStart = currTime;
publicAPI.animationEvent();
forceRender();
model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
};
publicAPI.handleWheel = (event) => {
preventDefault(event);
/**
* wheel event values can vary significantly across browsers, platforms
* and devices [1]. `normalizeWheel` uses facebook's solution from their
* fixed-data-table repository [2].
*
* [1] https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel
* [2] https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
*
* This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
*/
const callData = {
...normalizeWheel(event),
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
if (model.wheelTimeoutID === 0) {
publicAPI.startMouseWheelEvent(callData);
} else {
publicAPI.mouseWheelEvent(callData);
clearTimeout(model.wheelTimeoutID);
}
// start a timer to keep us animating while we get wheel events
model.wheelTimeoutID = setTimeout(() => {
publicAPI.endMouseWheelEvent();
model.wheelTimeoutID = 0;
}, 200);
};
publicAPI.handleMouseEnter = (event) => {
const callData = {
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
publicAPI.mouseEnterEvent(callData);
};
publicAPI.handleMouseLeave = (event) => {
const callData = {
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
publicAPI.mouseLeaveEvent(callData);
};
publicAPI.handleMouseUp = (event) => {
interactionRegistration(false);
preventDefault(event);
const callData = {
...getModifierKeysFor(event),
position: getScreenEventPositionFor(event),
};
switch (event.button) {
case 0:
publicAPI.leftButtonReleaseEvent(callData);
break;
case 1:
publicAPI.middleButtonReleaseEvent(callData);
break;
case 2:
publicAPI.rightButtonReleaseEvent(callData);
break;
default:
vtkErrorMacro(`Unknown mouse button released: ${event.button}`);
break;
}
};
publicAPI.handleTouchStart = (event) => {
interactionRegistration(true);
preventDefault(event);
// If multitouch
if (model.recognizeGestures && event.touches.length > 1) {
const positions = getTouchEventPositionsFor(event.touches);
// did we just transition to multitouch?
if (event.touches.length === 2) {
const touch = event.touches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.leftButtonReleaseEvent(callData);
}
// handle the gesture
publicAPI.recognizeGesture('TouchStart', positions);
} else {
const touch = event.touches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.leftButtonPressEvent(callData);
}
};
publicAPI.handleTouchMove = (event) => {
preventDefault(event);
if (model.recognizeGestures && event.touches.length > 1) {
const positions = getTouchEventPositionsFor(event.touches);
publicAPI.recognizeGesture('TouchMove', positions);
} else {
const touch = event.touches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.mouseMoveEvent(callData);
}
};
publicAPI.handleTouchEnd = (event) => {
preventDefault(event);
if (model.recognizeGestures) {
// No more fingers down
if (event.touches.length === 0) {
// If just one finger released, consider as left button
if (event.changedTouches.length === 1) {
const touch = event.changedTouches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.leftButtonReleaseEvent(callData);
interactionRegistration(false);
} else {
// If more than one finger released, recognize touchend
const positions = getTouchEventPositionsFor(event.changedTouches);
publicAPI.recognizeGesture('TouchEnd', positions);
interactionRegistration(false);
}
} else if (event.touches.length === 1) {
// If one finger left, end touch and start button press
const positions = getTouchEventPositionsFor(event.changedTouches);
publicAPI.recognizeGesture('TouchEnd', positions);
const touch = event.touches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.leftButtonPressEvent(callData);
} else {
// If more than one finger left, keep touch move
const positions = getTouchEventPositionsFor(event.touches);
publicAPI.recognizeGesture('TouchMove', positions);
}
} else {
const touch = event.changedTouches[0];
const callData = {
position: getScreenEventPositionFor(touch),
shiftKey: false,
altKey: false,
controlKey: false,
};
publicAPI.leftButtonReleaseEvent(callData);
interactionRegistration(false);
}
};
publicAPI.setView = (val) => {
if (model.view === val) {
return;
}
model.view = val;
model.view.getRenderable().setInteractor(publicAPI);
publicAPI.modified();
};
publicAPI.getFirstRenderer = () =>
model.view.getRenderable().getRenderersByReference()[0];
publicAPI.findPokedRenderer = (x = 0, y = 0) => {
if (!model.view) {
return null;
}
// The original order of renderers needs to remain as
// the first one is the one we want to manipulate the camera on.
const rc = model.view.getRenderable().getRenderers();
rc.sort((a, b) => a.getLayer() - b.getLayer());
let interactiveren = null;
let viewportren = null;
let currentRenderer = null;
let count = rc.length;
while (count--) {
const aren = rc[count];
if (model.view.isInViewport(x, y, aren) && aren.getInteractive()) {
currentRenderer = aren;
break;
}
if (interactiveren === null && aren.getInteractive()) {
// Save this renderer in case we can't find one in the viewport that
// is interactive.
interactiveren = aren;
}
if (viewportren === null && model.view.isInViewport(x, y, aren)) {
// Save this renderer in case we can't find one in the viewport that
// is interactive.
viewportren = aren;
}
}
// We must have a value. If we found an interactive renderer before, that's
// better than a non-interactive renderer.
if (currentRenderer === null) {
currentRenderer = interactiveren;
}
// We must have a value. If we found a renderer that is in the viewport,
// that is better than any old viewport (but not as good as an interactive
// one).
if (currentRenderer === null) {
currentRenderer = viewportren;
}
// We must have a value - take anything.
if (currentRenderer == null) {
currentRenderer = rc[0];
}
return currentRenderer;
};
// only render if we are not animating. If we are animating
// then renders will happen naturally anyhow and we definitely
// do not want extra renders as the make the apparent interaction
// rate slower.
publicAPI.render = () => {
if (!publicAPI.isAnimating() && !model.inRender) {
forceRender();
}
};
// create the generic Event methods
handledEvents.forEach((eventName) => {
const lowerFirst = eventName.charAt(0).toLowerCase() + eventName.slice(1);
publicAPI[`${lowerFirst}Event`] = (arg) => {
// Check that interactor enabled
if (!model.enabled) {
return;
}
// Check that a poked renderer exists
const renderer = publicAPI.getCurrentRenderer();
if (!renderer) {
vtkOnceErrorMacro(`
Can not forward events without a current renderer on the interactor.
`);
return;
}
// Pass the eventName and the poked renderer
const callData = {
type: eventName,
pokedRenderer: model.currentRenderer,
firstRenderer: publicAPI.getFirstRenderer(),
// Add the arguments to the call data
...arg,
};
// Call invoke
publicAPI[`invoke${eventName}`](callData);
};
});
// we know we are in multitouch now, so start recognizing
publicAPI.recognizeGesture = (event, positions) => {
// more than two pointers we ignore
if (Object.keys(positions).length > 2) {
return;
}
if (!model.startingEventPositions) {
model.startingEventPositions = {};
}
// store the initial positions
if (event === 'TouchStart') {
Object.keys(positions).forEach((key) => {
model.startingEventPositions[key] = positions[key];
});
// we do not know what the gesture is yet
model.currentGesture = 'Start';
return;
}
// end the gesture if needed
if (event === 'TouchEnd') {
if (model.currentGesture === 'Pinch') {
publicAPI.render();
publicAPI.endPinchEvent();
}
if (model.currentGesture === 'Rotate') {
publicAPI.render();
publicAPI.endRotateEvent();
}
if (model.currentGesture === 'Pan') {
publicAPI.render();
publicAPI.endPanEvent();
}
model.currentGesture = 'Start';
model.startingEventPositions = {};
return;
}
// what are the two pointers we are working with
let count = 0;
const posVals = [];
const startVals = [];
Object.keys(positions).forEach((key) => {
posVals[count] = positions[key];
startVals[count] = model.startingEventPositions[key];
count++;
});
// The meat of the algorithm
// on move events we analyze them to determine what type
// of movement it is and then deal with it.
// calculate the distances
const originalDistance = Math.sqrt(
(startVals[0].x - startVals[1].x) * (startVals[0].x - startVals[1].x) +
(startVals[0].y - startVals[1].y) * (startVals[0].y - startVals[1].y)
);
const newDistance = Math.sqrt(
(posVals[0].x - posVals[1].x) * (posVals[0].x - posVals[1].x) +
(posVals[0].y - posVals[1].y) * (posVals[0].y - posVals[1].y)
);
// calculate rotations
let originalAngle = vtkMath.degreesFromRadians(
Math.atan2(
startVals[1].y - startVals[0].y,
startVals[1].x - startVals[0].x
)
);
let newAngle = vtkMath.degreesFromRadians(
Math.atan2(posVals[1].y - posVals[0].y, posVals[1].x - posVals[0].x)
);
// angles are cyclic so watch for that, 1 and 359 are only 2 apart :)
let angleDeviation = newAngle - originalAngle;
newAngle = newAngle + 180.0 >= 360.0 ? newAngle - 180.0 : newAngle + 180.0;
originalAngle =
originalAngle + 180.0 >= 360.0
? originalAngle - 180.0
: originalAngle + 180.0;
if (Math.abs(newAngle - originalAngle) < Math.abs(angleDeviation)) {
angleDeviation = newAngle - originalAngle;
}
// calculate the translations
const trans = [];
trans[0] =
(posVals[0].x - startVals[0].x + posVals[1].x - startVals[1].x) / 2.0;
trans[1] =
(posVals[0].y - startVals[0].y + posVals[1].y - startVals[1].y) / 2.0;
if (event === 'TouchMove') {
// OK we want to
// - immediately respond to the user
// - allow the user to zoom without panning (saves focal point)
// - allow the user to rotate without panning (saves focal point)
// do we know what gesture we are doing yet? If not
// see if we can figure it out
if (model.currentGesture === 'Start') {
// pinch is a move to/from the center point
// rotate is a move along the circumference
// pan is a move of the center point
// compute the distance along each of these axes in pixels
// the first to break thresh wins
let thresh =
0.01 *
Math.sqrt(
model.container.clientWidth * model.container.clientWidth +
model.container.clientHeight * model.container.clientHeight
);
if (thresh < 15.0) {
thresh = 15.0;
}
const pinchDistance = Math.abs(newDistance - originalDistance);
const rotateDistance =
(newDistance * 3.1415926 * Math.abs(angleDeviation)) / 360.0;
const panDistance = Math.sqrt(
trans[0] * trans[0] + trans[1] * trans[1]
);
if (
pinchDistance > thresh &&
pinchDistance > rotateDistance &&
pinchDistance > panDistance
) {
model.currentGesture = 'Pinch';
const callData = {
scale: 1.0,
touches: positions,
};
publicAPI.startPinchEvent(callData);
} else if (rotateDistance > thresh && rotateDistance > panDistance) {
model.currentGesture = 'Rotate';
const callData = {
rotation: 0.0,
touches: positions,
};
publicAPI.startRotateEvent(callData);
} else if (panDistance > thresh) {
model.currentGesture = 'Pan';
const callData = {
translation: [0, 0],
touches: positions,
};
publicAPI.startPanEvent(callData);
}
} else {