All files / Sources/Rendering/Core/RenderWindowInteractor index.js

41.47% Statements 214/516
22.41% Branches 63/281
43.47% Functions 30/69
41.56% Lines 212/510

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320          1x   1x           1x           1x                     1x                                                                                                                           130x     130x     130x     130x     130x         130x                                       130x             130x 116x 116x 1x   116x 116x 116x 116x             130x 127x 127x 127x     130x   130x   130x     22x 22x       130x 110x 105x   5x 5x       17x 17x 17x 17x 17x             17x 17x   17x       130x     17x                                   17x     130x 131x 7x     124x 124x 124x 124x 124x 124x 124x     124x     124x 124x 124x 124x 124x   124x             124x 124x   124x         130x 124x     124x 124x 124x       130x   109x 109x 109x 109x 109x   109x 109x 109x 109x 109x 109x       109x       109x             109x             109x 109x         109x 109x 109x 109x       109x     130x 102x 102x     130x         130x         130x         130x 16x         16x 16x 16x       130x                       130x                                                                     130x                                           130x                                 130x 1x         1x             1x 1x       130x                                             130x             130x     130x       130x                   299x 291x 291x 291x       299x     130x                                               130x                             130x 448x   130x                                                 130x                 130x               130x                                                                                                                                                                 130x 1x           1x 1x             1x 1x 1x       130x                                                           130x                                                                                                                                       130x                                           130x                                                   130x                             130x                                                                         130x 129x     129x 129x 129x     130x 34x   130x 23x         23x 23x     23x 23x 23x 23x   23x 23x 26x 26x 23x 23x     3x         3x     1x           23x             23x         23x       23x             130x 299x 299x         130x 5070x 5070x   34x         34x 34x               34x                 34x         130x                                                                                                                                                                                                                                                                                                                                                               130x         130x         130x 7x 7x 7x 7x   7x       130x 9x     9x 9x         9x 7x   9x           130x 130x                       1x                                                           130x     130x     130x   130x 130x 5070x       130x                 130x                         130x         130x         1x                
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 { Device, Input } = Constants;
const { vtkWarningMacro, vtkErrorMacro, normalizeWheel, vtkOnceErrorMacro } =
  macro;
 
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
 
const EMPTY_MOUSE_EVENT = {
  ctrlKey: false,
  altKey: false,
  shiftKey: false,
};
 
const deviceInputMap = {
  'xr-standard': [
    Input.Trigger,
    Input.Grip,
    Input.TrackPad,
    Input.Thumbstick,
    Input.A,
    Input.B,
  ],
};
 
const handledEvents = [
  'StartAnimation',
  'Animation',
  'EndAnimation',
  'PointerEnter',
  'PointerLeave',
  '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',
  'AnimationFrameRateUpdate',
];
 
function preventDefault(event) {
  if (event.cancelable) {
    event.preventDefault();
  }
}
 
function pointerCacheToPositions(cache) {
  const positions = Object.create(null);
  cache.forEach(({ pointerId, position }) => {
    positions[pointerId] = position;
  });
  return positions;
}
 
// ----------------------------------------------------------------------------
// vtkRenderWindowInteractor methods
// ----------------------------------------------------------------------------
 
function vtkRenderWindowInteractor(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkRenderWindowInteractor');
 
  // Capture "parentClass" api for internal use
  const superClass = { ...publicAPI };
 
  // Initialize list of requesters
  const animationRequesters = new Set();
 
  // map from pointerId to { pointerId: number, position: [x, y] }
  const pointerCache = new Map();
 
  // Factor to apply on wheel spin.
  let wheelCoefficient = 1;
 
  // 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 canvas = model._view.getCanvas();
    const bounds = canvas.getBoundingClientRect();
    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,
    };
 
    // if multitouch, do not update the current renderer
    if (pointerCache.size <= 1 || !model.currentRenderer) {
      updateCurrentRenderer(position.x, position.y);
    }
    return position;
  }
  // Allow user to override it
  const getScreenEventPositionFor =
    model._getScreenEventPositionFor || _getScreenEventPositionFor;
 
  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 getDeviceTypeFor(event) {
    return event.pointerType || '';
  }
 
  const _bindEvents = () => {
    if (model.container === null) {
      return;
    }
 
    const { container } = model;
    container.addEventListener('contextmenu', preventDefault);
    container.addEventListener('wheel', publicAPI.handleWheel);
    container.addEventListener('DOMMouseScroll', publicAPI.handleWheel);
    container.addEventListener('pointerenter', publicAPI.handlePointerEnter);
    container.addEventListener('pointerleave', publicAPI.handlePointerLeave);
    container.addEventListener('pointermove', publicAPI.handlePointerMove, {
      passive: false,
    });
    container.addEventListener('pointerdown', publicAPI.handlePointerDown, {
      passive: false,
    });
    container.addEventListener('pointerup', publicAPI.handlePointerUp);
    container.addEventListener('pointercancel', publicAPI.handlePointerCancel);
    document.addEventListener('keypress', publicAPI.handleKeyPress);
    document.addEventListener('keydown', publicAPI.handleKeyDown);
    document.addEventListener('keyup', publicAPI.handleKeyUp);
 
    document.addEventListener(
      'pointerlockchange',
      publicAPI.handlePointerLockChange
    );
 
    // using touchAction is more performant than preventDefault
    // in a touchstart handler.
    container.style.touchAction = 'none';
    container.style.userSelect = 'none';
    // disables tap highlight for when cursor is pointer
    container.style.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  };
 
  // For backward compatibility.
  // Necessary for using unbind/bindEvent without calling setContainer.
  publicAPI.bindEvents = (container) => {
    Iif (container === null) {
      return;
    }
    const res = superClass.setContainer(container);
    if (res) {
      _bindEvents();
    }
  };
 
  const _unbindEvents = () => {
    // Clear any previous timeouts and state variables that control mouse / touchpad behavior.
    clearTimeout(model.moveTimeoutID);
    clearTimeout(model.wheelTimeoutID);
    model.moveTimeoutID = 0;
    model.wheelTimeoutID = 0;
    wheelCoefficient = 1.0;
 
    const { container } = model;
    if (container) {
      container.removeEventListener('contextmenu', preventDefault);
      container.removeEventListener('wheel', publicAPI.handleWheel);
      container.removeEventListener('DOMMouseScroll', publicAPI.handleWheel);
      container.removeEventListener(
        'pointerenter',
        publicAPI.handlePointerEnter
      );
      container.removeEventListener(
        'pointerleave',
        publicAPI.handlePointerLeave
      );
      container.removeEventListener(
        'pointermove',
        publicAPI.handlePointerMove,
        {
          passive: false,
        }
      );
      container.removeEventListener(
        'pointerdown',
        publicAPI.handlePointerDown,
        {
          passive: false,
        }
      );
      container.removeEventListener('pointerup', publicAPI.handlePointerUp);
      container.removeEventListener(
        'pointercancel',
        publicAPI.handlePointerCancel
      );
    }
    document.removeEventListener('keypress', publicAPI.handleKeyPress);
    document.removeEventListener('keydown', publicAPI.handleKeyDown);
    document.removeEventListener('keyup', publicAPI.handleKeyUp);
    document.removeEventListener(
      'pointerlockchange',
      publicAPI.handlePointerLockChange
    );
    pointerCache.clear();
  };
 
  publicAPI.unbindEvents = () => {
    _unbindEvents();
    superClass.setContainer(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.handlePointerEnter = (event) => {
    const callData = {
      ...getModifierKeysFor(event),
      position: getScreenEventPositionFor(event),
      deviceType: getDeviceTypeFor(event),
    };
    publicAPI.pointerEnterEvent(callData);
    if (callData.deviceType === 'mouse') {
      publicAPI.mouseEnterEvent(callData);
    }
  };
 
  publicAPI.handlePointerLeave = (event) => {
    const callData = {
      ...getModifierKeysFor(event),
      position: getScreenEventPositionFor(event),
      deviceType: getDeviceTypeFor(event),
    };
    publicAPI.pointerLeaveEvent(callData);
    if (callData.deviceType === 'mouse') {
      publicAPI.mouseLeaveEvent(callData);
    }
  };
 
  publicAPI.handlePointerDown = (event) => {
    if (event.button > 2 || publicAPI.isPointerLocked()) {
      // ignore events from extra mouse buttons such as `back` and `forward`
      return;
    }
    if (model.preventDefaultOnPointerDown) {
      preventDefault(event);
    }
 
    if (event.target.hasPointerCapture(event.pointerId)) {
      event.target.releasePointerCapture(event.pointerId);
    }
    model.container.setPointerCapture(event.pointerId);
 
    if (pointerCache.has(event.pointerId)) {
      vtkWarningMacro('[RenderWindowInteractor] duplicate pointerId detected');
    }
 
    pointerCache.set(event.pointerId, {
      pointerId: event.pointerId,
      position: getScreenEventPositionFor(event),
    });
 
    switch (event.pointerType) {
      case 'pen':
      case 'touch':
        publicAPI.handleTouchStart(event);
        break;
      case 'mouse':
      default:
        publicAPI.handleMouseDown(event);
        break;
    }
  };
 
  publicAPI.handlePointerUp = (event) => {
    if (pointerCache.has(event.pointerId)) {
      if (model.preventDefaultOnPointerUp) {
        preventDefault(event);
      }
 
      pointerCache.delete(event.pointerId);
      model.container.releasePointerCapture(event.pointerId);
 
      switch (event.pointerType) {
        case 'pen':
        case 'touch':
          publicAPI.handleTouchEnd(event);
          break;
        case 'mouse':
        default:
          publicAPI.handleMouseUp(event);
          break;
      }
    }
  };
 
  publicAPI.handlePointerCancel = (event) => {
    if (pointerCache.has(event.pointerId)) {
      pointerCache.delete(event.pointerId);
 
      switch (event.pointerType) {
        case 'pen':
        case 'touch':
          publicAPI.handleTouchEnd(event);
          break;
        case 'mouse':
        default:
          publicAPI.handleMouseUp(event);
          break;
      }
    }
  };
 
  publicAPI.handlePointerMove = (event) => {
    Iif (pointerCache.has(event.pointerId)) {
      const pointer = pointerCache.get(event.pointerId);
      pointer.position = getScreenEventPositionFor(event);
    }
 
    switch (event.pointerType) {
      case 'pen':
      case 'touch':
        publicAPI.handleTouchMove(event);
        break;
      case 'mouse':
      default:
        publicAPI.handleMouseMove(event);
        break;
    }
  };
 
  publicAPI.handleMouseDown = (event) => {
    const callData = {
      ...getModifierKeysFor(event),
      position: getScreenEventPositionFor(event),
      deviceType: getDeviceTypeFor(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 = () => {
    if (model.container) {
      model.container.requestPointerLock();
    }
  };
 
  //----------------------------------------------------------------------
  publicAPI.exitPointerLock = () => document.exitPointerLock?.();
 
  //----------------------------------------------------------------------
  publicAPI.isPointerLocked = () =>
    !!model.container && document.pointerLockElement === model.container;
 
  //----------------------------------------------------------------------
  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 (
      !model.animationRequest &&
      animationRequesters.size === 1 &&
      !model.xrAnimation
    ) {
      model._animationStartTime = Date.now();
      model._animationFrameCount = 0;
      model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
      publicAPI.startAnimationEvent();
    }
  };
 
  // continue animating for at least the specified duration of
  // milliseconds.
  publicAPI.extendAnimation = (duration) => {
    const newEnd = Date.now() + duration;
    model._animationExtendedEnd = Math.max(model._animationExtendedEnd, newEnd);
    if (
      !model.animationRequest &&
      animationRequesters.size === 0 &&
      !model.xrAnimation
    ) {
      model._animationStartTime = Date.now();
      model._animationFrameCount = 0;
      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 &&
      Date.now() > model._animationExtendedEnd
    ) {
      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.recentAnimationFrameRate = 10.0;
      model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
    }
  };
 
  publicAPI.updateXRGamepads = (xrSession, xrFrame, xrRefSpace) => {
    // watch for when buttons change state and fire events
    xrSession.inputSources.forEach((inputSource) => {
      const gripPose =
        inputSource.gripSpace == null
          ? null
          : xrFrame.getPose(inputSource.gripSpace, xrRefSpace);
 
      const targetRayPose =
        inputSource.gripSpace == null
          ? null
          : xrFrame.getPose(inputSource.targetRaySpace, xrRefSpace);
 
      const gamepad = inputSource.gamepad;
      const hand = inputSource.handedness;
 
      if (!gamepad) {
        return;
      }
 
      if (!(gamepad.index in model.lastGamepadValues)) {
        model.lastGamepadValues[gamepad.index] = {
          left: { buttons: {} },
          right: { buttons: {} },
          none: { buttons: {} },
        };
      }
 
      for (let buttonIdx = 0; buttonIdx < gamepad.buttons.length; ++buttonIdx) {
        if (
          !(buttonIdx in model.lastGamepadValues[gamepad.index][hand].buttons)
        ) {
          model.lastGamepadValues[gamepad.index][hand].buttons[
            buttonIdx
          ] = false;
        }
        if (
          model.lastGamepadValues[gamepad.index][hand].buttons[buttonIdx] !==
            gamepad.buttons[buttonIdx].pressed &&
          gripPose != null
        ) {
          publicAPI.button3DEvent({
            gamepad,
            position: gripPose.transform.position,
            orientation: gripPose.transform.orientation,
            targetPosition: targetRayPose.transform.position,
            targetOrientation: targetRayPose.transform.orientation,
            pressed: gamepad.buttons[buttonIdx].pressed,
            device:
              inputSource.handedness === 'left'
                ? Device.LeftController
                : Device.RightController,
            input:
              deviceInputMap[gamepad.mapping] &&
              deviceInputMap[gamepad.mapping][buttonIdx]
                ? deviceInputMap[gamepad.mapping][buttonIdx]
                : Input.Trigger,
          });
          model.lastGamepadValues[gamepad.index][hand].buttons[buttonIdx] =
            gamepad.buttons[buttonIdx].pressed;
        }
        if (
          model.lastGamepadValues[gamepad.index][hand].buttons[buttonIdx] &&
          gripPose != null
        ) {
          publicAPI.move3DEvent({
            gamepad,
            position: gripPose.transform.position,
            orientation: gripPose.transform.orientation,
            targetPosition: targetRayPose.transform.position,
            targetOrientation: targetRayPose.transform.orientation,
            device:
              inputSource.handedness === 'left'
                ? Device.LeftController
                : Device.RightController,
          });
        }
      }
    });
  };
 
  publicAPI.handleMouseMove = (event) => {
    const callData = {
      ...getModifierKeysFor(event),
      position: getScreenEventPositionFor(event),
      deviceType: getDeviceTypeFor(event),
    };
 
    if (model.moveTimeoutID === 0) {
      publicAPI.startMouseMoveEvent(callData);
    } else E{
      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();
    model._animationFrameCount++;
    if (
      currTime - model._animationStartTime > 1000.0 &&
      model._animationFrameCount > 1
    ) {
      model.recentAnimationFrameRate =
        (1000.0 * (model._animationFrameCount - 1)) /
        (currTime - model._animationStartTime);
      model.lastFrameTime = 1.0 / model.recentAnimationFrameRate;
      publicAPI.animationFrameRateUpdateEvent();
      model._animationStartTime = currTime;
      model._animationFrameCount = 1;
    }
    publicAPI.animationEvent();
    forceRender();
    if (
      animationRequesters.size > 0 ||
      Date.now() < model._animationExtendedEnd
    ) {
      model.animationRequest = requestAnimationFrame(publicAPI.handleAnimation);
    } else {
      cancelAnimationFrame(model.animationRequest);
      model.animationRequest = null;
      publicAPI.endAnimationEvent();
      publicAPI.render();
    }
  };
 
  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),
      deviceType: getDeviceTypeFor(event),
    };
 
    // Wheel events are thought to scroll pages (i.e. multiple lines at once).
    // See normalizeWheel() documentation for more context.
    // While trackpad wheel events are many small (<1) wheel spins,
    // mouse wheel events have absolute spin values higher than 1.
    // Here the first spin value is "recorded", and used to normalize
    // all the following mouse wheel events.
    if (model.wheelTimeoutID === 0) {
      // we attempt to distinguish between trackpads and mice
      // .3 will be larger than the first trackpad event,
      // but small enough to detect some common edge case mice
      if (Math.abs(callData.spinY) >= 0.3) {
        // Event is coming from mouse wheel
        wheelCoefficient = Math.abs(callData.spinY);
      } else {
        // Event is coming from trackpad
        wheelCoefficient = 1;
      }
    }
    callData.spinY /= wheelCoefficient;
 
    if (model.wheelTimeoutID === 0) {
      publicAPI.startMouseWheelEvent(callData);
      publicAPI.mouseWheelEvent(callData);
    } else {
      publicAPI.mouseWheelEvent(callData);
      clearTimeout(model.wheelTimeoutID);
    }
 
    if (model.mouseScrollDebounceByPass) {
      publicAPI.extendAnimation(600);
      publicAPI.endMouseWheelEvent();
      model.wheelTimeoutID = 0;
    } else {
      // start a timer to keep us animating while we get wheel events
      model.wheelTimeoutID = setTimeout(() => {
        publicAPI.extendAnimation(600);
        publicAPI.endMouseWheelEvent();
        model.wheelTimeoutID = 0;
      }, 200);
    }
  };
 
  publicAPI.handleMouseUp = (event) => {
    const callData = {
      ...getModifierKeysFor(event),
      position: getScreenEventPositionFor(event),
      deviceType: getDeviceTypeFor(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) => {
    const pointers = [...pointerCache.values()];
    // If multitouch
    if (model.recognizeGestures && pointers.length > 1) {
      const positions = pointerCacheToPositions(pointerCache);
      // did we just transition to multitouch?
      if (pointers.length === 2) {
        const callData = {
          ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
          position: pointers[0].position,
          deviceType: getDeviceTypeFor(event),
        };
        publicAPI.leftButtonReleaseEvent(callData);
      }
      // handle the gesture
      publicAPI.recognizeGesture('TouchStart', positions);
    } else if (pointers.length === 1) {
      const callData = {
        ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
        position: getScreenEventPositionFor(event),
        deviceType: getDeviceTypeFor(event),
      };
      publicAPI.leftButtonPressEvent(callData);
    }
  };
 
  publicAPI.handleTouchMove = (event) => {
    const pointers = [...pointerCache.values()];
    if (model.recognizeGestures && pointers.length > 1) {
      const positions = pointerCacheToPositions(pointerCache);
      publicAPI.recognizeGesture('TouchMove', positions);
    } else if (pointers.length === 1) {
      const callData = {
        ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
        position: pointers[0].position,
        deviceType: getDeviceTypeFor(event),
      };
      publicAPI.mouseMoveEvent(callData);
    }
  };
 
  publicAPI.handleTouchEnd = (event) => {
    const pointers = [...pointerCache.values()];
 
    if (model.recognizeGestures) {
      // No more fingers down
      if (pointers.length === 0) {
        const callData = {
          ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
          position: getScreenEventPositionFor(event),
          deviceType: getDeviceTypeFor(event),
        };
        publicAPI.leftButtonReleaseEvent(callData);
      } else if (pointers.length === 1) {
        // If one finger left, end touch and start button press
        const positions = pointerCacheToPositions(pointerCache);
        publicAPI.recognizeGesture('TouchEnd', positions);
        const callData = {
          ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
          position: pointers[0].position,
          deviceType: getDeviceTypeFor(event),
        };
        publicAPI.leftButtonPressEvent(callData);
      } else {
        // If more than one finger left, keep touch move
        const positions = pointerCacheToPositions(pointerCache);
        publicAPI.recognizeGesture('TouchMove', positions);
      }
    } else if (pointers.length === 1) {
      const callData = {
        ...getModifierKeysFor(EMPTY_MOUSE_EVENT),
        position: pointers[0].position,
        deviceType: getDeviceTypeFor(event),
      };
      publicAPI.leftButtonReleaseEvent(callData);
    }
  };
 
  publicAPI.setView = (val) => {
    Iif (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) => {
    Iif (!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();
    Iif (!rc || rc.length === 0) {
      return null;
    }
    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;
      }
 
      Iif (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.
    Iif (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).
    Iif (currentRenderer === null) {
      currentRenderer = viewportren;
    }
 
    // We must have a value - take anything.
    Iif (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
      Iif (!model.enabled) {
        return;
      }
 
      // Check that a poked renderer exists
      const renderer = publicAPI.getCurrentRenderer();
      Iif (!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 {
        // if we have found a specific type of movement then
        // handle it
        if (model.currentGesture === 'Rotate') {
          const callData = {
            rotation: angleDeviation,
            touches: positions,
          };
          publicAPI.rotateEvent(callData);
        }
 
        if (model.currentGesture === 'Pinch') {
          const callData = {
            scale: newDistance / originalDistance,
            touches: positions,
          };
          publicAPI.pinchEvent(callData);
        }
 
        if (model.currentGesture === 'Pan') {
          const callData = {
            translation: trans,
            touches: positions,
          };
          publicAPI.panEvent(callData);
        }
      }
    }
  };
 
  publicAPI.handleVisibilityChange = () => {
    model._animationStartTime = Date.now();
    model._animationFrameCount = 0;
  };
 
  publicAPI.setCurrentRenderer = (r) => {
    model._forcedRenderer = !!r;
    model.currentRenderer = r;
  };
 
  publicAPI.setContainer = (container) => {
    _unbindEvents();
    const res = superClass.setContainer(container ?? null);
    if (res) {
      _bindEvents();
    }
    return res;
  };
 
  // Stop animating if the renderWindowInteractor is deleted.
  publicAPI.delete = () => {
    while (animationRequesters.size) {
      publicAPI.cancelAnimation(animationRequesters.values().next().value);
    }
    if (typeof document.hidden !== 'undefined') {
      document.removeEventListener(
        'visibilitychange',
        publicAPI.handleVisibilityChange
      );
    }
    if (model.container) {
      publicAPI.setContainer(null);
    }
    superClass.delete();
  };
 
  // Use the Page Visibility API to detect when we switch away from or back to
  // this tab, and reset the animationFrameStart. When tabs are not active, browsers
  // will stop calling requestAnimationFrame callbacks.
  if (typeof document.hidden !== 'undefined') {
    document.addEventListener(
      'visibilitychange',
      publicAPI.handleVisibilityChange,
      false
    );
  }
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  renderWindow: null,
  interactorStyle: null,
  picker: null,
  pickingManager: null,
  initialized: false,
  enabled: false,
  enableRender: true,
  currentRenderer: null,
  lightFollowCamera: true,
  desiredUpdateRate: 30.0,
  stillUpdateRate: 2.0,
  container: null,
  // _view: null,
  recognizeGestures: true,
  currentGesture: 'Start',
  animationRequest: null,
  lastFrameTime: 0.1,
  recentAnimationFrameRate: 10.0,
  wheelTimeoutID: 0,
  moveTimeoutID: 0,
  lastGamepadValues: {},
  preventDefaultOnPointerDown: false,
  preventDefaultOnPointerUp: false,
  mouseScrollDebounceByPass: false,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Object methods
  macro.obj(publicAPI, model);
 
  // run animation at least until this time
  model._animationExtendedEnd = 0;
 
  macro.event(publicAPI, model, 'RenderEvent');
  handledEvents.forEach((eventName) =>
    macro.event(publicAPI, model, eventName)
  );
 
  // Create get-only macros
  macro.get(publicAPI, model, [
    'initialized',
    'interactorStyle',
    'lastFrameTime',
    'recentAnimationFrameRate',
    '_view',
  ]);
 
  // Create get-set macros
  macro.setGet(publicAPI, model, [
    'container',
    'lightFollowCamera',
    'enabled',
    'enableRender',
    'recognizeGestures',
    'desiredUpdateRate',
    'stillUpdateRate',
    'picker',
    'preventDefaultOnPointerDown',
    'preventDefaultOnPointerUp',
    'mouseScrollDebounceByPass',
  ]);
  macro.moveToProtected(publicAPI, model, ['view']);
 
  // For more macro methods, see "Sources/macros.js"
 
  // Object specific methods
  vtkRenderWindowInteractor(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(
  extend,
  'vtkRenderWindowInteractor'
);
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, handledEvents, ...Constants };