All files / Sources/Rendering/OpenGL/RenderWindow index.js

67.83% Statements 291/429
52.52% Branches 156/297
69.11% Functions 47/68
68.17% Lines 287/421

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 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413                            1x   1x               1x                                                                                                                           1x 1x     205x 205x       201x 201x       1x       1x                         208x         261x 205x   261x     208x     208x   208x             208x     720x 624x       311x 311x 311x 311x         720x           720x     720x 404x       720x   208x     208x 878x 439x       439x 439x 439x     439x   439x   439x     469x         208x 439x     205x       205x         205x 205x 205x 205x   205x 205x 205x   205x 205x           205x 205x   205x       208x       208x 509x 202x         202x       202x         509x 408x 408x 205x       205x           408x       208x   208x 139x 7x 7x   139x     208x 37156x 37156x     208x 53x 53x                 53x     208x               261x   261x 261x 261x 261x 261x 261x 261x     261x             261x     208x     208x           208x   1526x 1526x 8x 8x     1518x 1518x             1518x 1518x     208x   1518x 1518x 1518x 1518x       208x 732x 732x 732x         208x         443x 443x       379x           13x   51x               208x           419x 419x   379x   160x       70x     149x     3x   3x                     10x   9x   1x                         27x   26x   1x                                                   208x       208x                           195x 195x 195x 195x 195x     195x   195x 195x 195x 205x 205x   1365x                                         195x 195x 195x     208x       195x     195x 195x 195x   195x             195x 195x 195x 195x 195x 195x                                           195x                                                                                                                             208x   19x 17x     2x 2x   2x   2x     208x 358x 304x   54x   54x 54x 54x 54x   54x     54x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               54x 54x 2538x 2538x 2538x     54x 54x     208x 439x 439x 439x     439x 439x 195x   439x 439x         208x 439x 439x         439x                                 208x   205x 205x                         208x 3757x           208x             208x 202x 202x                                                       208x 7x 7x 7x       202x 202x           208x   202x 201x   202x 202x             208x 94x     208x 208x 104x 104x 104x   104x     208x   120x       120x 120x     208x 302x 302x 182x   120x   120x 120x 120x       208x 254x   208x 120x     120x   120x   120x               208x               208x                                         208x 208x 5824x 55607x       55607x                 1x                                                 208x     208x     208x 208x 208x     208x 208x 208x       208x 208x 208x 208x 208x 208x 208x   208x 208x 208x   208x   208x 208x     208x     208x                 208x                       208x 208x 208x     208x         1x           1x                       1x  
import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import macro from 'vtk.js/Sources/macros';
import { registerViewConstructor } from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkForwardPass from 'vtk.js/Sources/Rendering/OpenGL/ForwardPass';
import vtkOpenGLHardwareSelector from 'vtk.js/Sources/Rendering/OpenGL/HardwareSelector';
import vtkShaderCache from 'vtk.js/Sources/Rendering/OpenGL/ShaderCache';
import vtkOpenGLTextureUnitManager from 'vtk.js/Sources/Rendering/OpenGL/TextureUnitManager';
import vtkOpenGLViewNodeFactory, {
  registerOverride,
} from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory';
import vtkRenderPass from 'vtk.js/Sources/Rendering/SceneGraph/RenderPass';
import vtkRenderWindowViewNode from 'vtk.js/Sources/Rendering/SceneGraph/RenderWindowViewNode';
import { createContextProxyHandler } from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow/ContextProxy';
 
const { vtkDebugMacro, vtkErrorMacro } = macro;
 
const SCREENSHOT_PLACEHOLDER = {
  position: 'absolute',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
};
 
const parentMethodsToProxy = [
  'activateTexture',
  'deactivateTexture',
  'disableCullFace',
  'enableCullFace',
  'get3DContext',
  'getActiveFramebuffer',
  'getContext',
  'getDefaultTextureByteSize',
  'getDefaultTextureInternalFormat',
  'getDefaultToWebgl2',
  'getGLInformations',
  'getGraphicsMemoryInfo',
  'getGraphicsResourceForObject',
  'getHardwareMaximumLineWidth',
  'getPixelData',
  'getShaderCache',
  'getTextureUnitForTexture',
  'getTextureUnitManager',
  'getWebgl2',
  'makeCurrent',
  'releaseGraphicsResources',
  'registerGraphicsResourceUser',
  'unregisterGraphicsResourceUser',
  'restoreContext',
  'setActiveFramebuffer',
  'setContext',
  'setDefaultToWebgl2',
  'setGraphicsResourceForObject',
];
 
function checkRenderTargetSupport(gl, format, type) {
  // create temporary frame buffer and texture
  const framebuffer = gl.createFramebuffer();
  const texture = gl.createTexture();
 
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, format, 2, 2, 0, format, type, null);
 
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  gl.framebufferTexture2D(
    gl.FRAMEBUFFER,
    gl.COLOR_ATTACHMENT0,
    gl.TEXTURE_2D,
    texture,
    0
  );
 
  // check frame buffer status
  const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
 
  // clean up
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.bindTexture(gl.TEXTURE_2D, null);
 
  return status === gl.FRAMEBUFFER_COMPLETE;
}
 
// ----------------------------------------------------------------------------
// Monitor the usage of GL context across vtkOpenGLRenderWindow instances
// ----------------------------------------------------------------------------
 
let GL_CONTEXT_COUNT = 0;
const GL_CONTEXT_LISTENERS = [];
 
function createGLContext() {
  GL_CONTEXT_COUNT++;
  GL_CONTEXT_LISTENERS.forEach((cb) => cb(GL_CONTEXT_COUNT));
}
 
function deleteGLContext() {
  GL_CONTEXT_COUNT--;
  GL_CONTEXT_LISTENERS.forEach((cb) => cb(GL_CONTEXT_COUNT));
}
 
export function pushMonitorGLContextCount(cb) {
  GL_CONTEXT_LISTENERS.push(cb);
}
 
export function popMonitorGLContextCount(cb) {
  return GL_CONTEXT_LISTENERS.pop();
}
 
function _preventDefault(e) {
  e.preventDefault();
}
 
// ----------------------------------------------------------------------------
// vtkOpenGLRenderWindow methods
// ----------------------------------------------------------------------------
 
function vtkOpenGLRenderWindow(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLRenderWindow');
 
  // Only create a cachingContextHandler if needed
  let cachingContextHandler;
  function getCachingContextHandler() {
    if (!cachingContextHandler) {
      cachingContextHandler = createContextProxyHandler();
    }
    return cachingContextHandler;
  }
 
  publicAPI.getViewNodeFactory = () => model.myFactory;
 
  // prevent default context lost handler
  model.canvas.addEventListener('webglcontextlost', _preventDefault, false);
 
  model.canvas.addEventListener(
    'webglcontextrestored',
    publicAPI.restoreContext,
    false
  );
 
  // Auto update style
  const previousSize = [0, 0];
  function updateWindow() {
    // Canvas size
    if (model.renderable) {
      if (
        model.size[0] !== previousSize[0] ||
        model.size[1] !== previousSize[1]
      ) {
        previousSize[0] = model.size[0];
        previousSize[1] = model.size[1];
        model.canvas.setAttribute('width', model.size[0]);
        model.canvas.setAttribute('height', model.size[1]);
      }
    }
 
    // ImageStream size
    Iif (model.viewStream) {
      // If same size that's a NoOp
      model.viewStream.setSize(model.size[0], model.size[1]);
    }
 
    // Offscreen ?
    model.canvas.style.display = model.useOffScreen ? 'none' : 'block';
 
    // Cursor type
    if (model.el) {
      model.el.style.cursor = model.cursorVisibility ? model.cursor : 'none';
    }
 
    // Invalidate cached DOM container size
    model.containerSize = null;
  }
  publicAPI.onModified(updateWindow);
 
  // Builds myself.
  publicAPI.buildPass = (prepass) => {
    if (prepass) {
      Iif (!model.renderable) {
        return;
      }
 
      publicAPI.prepareNodes();
      publicAPI.addMissingNodes(model.renderable.getRenderersByReference());
      publicAPI.addMissingNodes(
        model.renderable.getChildRenderWindowsByReference()
      );
      publicAPI.removeUnusedNodes();
 
      publicAPI.initialize();
 
      model.children.forEach((child) => {
        // Children can be openGl renderer or openGl render windows
        // Only openGl renderers have a method setOpenGLRenderWindow
        child.setOpenGLRenderWindow?.(publicAPI);
      });
    }
  };
 
  publicAPI.initialize = () => {
    if (!model.initialized) {
      // Set root parent if there is one
      // Some methods of the root parent are proxied (see parentMethodsToProxy)
      model.rootOpenGLRenderWindow = publicAPI.getLastAncestorOfType(
        'vtkOpenGLRenderWindow'
      );
 
      Iif (model.rootOpenGLRenderWindow) {
        // Initialize a 2D context that will copy the content of the root parent
        model.context2D = publicAPI.get2DContext();
      } else {
        // Initialize a 3D context that may be used by child render windows
        model.context = publicAPI.get3DContext();
        publicAPI.resizeFromChildRenderWindows();
        if (model.context) {
          createGLContext();
        }
        model.textureUnitManager = vtkOpenGLTextureUnitManager.newInstance();
        model.textureUnitManager.setContext(model.context);
        model.shaderCache.setContext(model.context);
        // initialize blending for transparency
        const gl = model.context;
        gl.blendFuncSeparate(
          gl.SRC_ALPHA,
          gl.ONE_MINUS_SRC_ALPHA,
          gl.ONE,
          gl.ONE_MINUS_SRC_ALPHA
        );
        gl.depthFunc(gl.LEQUAL);
        gl.enable(gl.BLEND);
      }
      model.initialized = true;
    }
  };
 
  publicAPI.makeCurrent = () => {
    model.context.makeCurrent();
  };
 
  publicAPI.setContainer = (el) => {
    if (model.el && model.el !== el) {
      Iif (model.canvas.parentNode !== model.el) {
        vtkErrorMacro('Error: canvas parent node does not match container');
      }
 
      // Remove canvas from previous container
      model.el.removeChild(model.canvas);
 
      // If the renderer has previously added
      // a background image, remove it from the DOM.
      Iif (model.el.contains(model.bgImage)) {
        model.el.removeChild(model.bgImage);
      }
    }
 
    if (model.el !== el) {
      model.el = el;
      if (model.el) {
        model.el.appendChild(model.canvas);
 
        // If the renderer is set to use a background
        // image, attach it to the DOM.
        Iif (model.useBackgroundImage) {
          model.el.appendChild(model.bgImage);
        }
      }
 
      // Trigger modified()
      publicAPI.modified();
    }
  };
 
  publicAPI.getContainer = () => model.el;
 
  publicAPI.getContainerSize = () => {
    if (!model.containerSize && model.el) {
      const { width, height } = model.el.getBoundingClientRect();
      model.containerSize = [width, height];
    }
    return model.containerSize || model.size;
  };
 
  publicAPI.getFramebufferSize = () => {
    const fbSize = model.activeFramebuffer?.getSize();
    return fbSize || model.size;
  };
 
  publicAPI.getPixelData = (x1, y1, x2, y2) => {
    const pixels = new Uint8Array((x2 - x1 + 1) * (y2 - y1 + 1) * 4);
    model.context.readPixels(
      x1,
      y1,
      x2 - x1 + 1,
      y2 - y1 + 1,
      model.context.RGBA,
      model.context.UNSIGNED_BYTE,
      pixels
    );
    return pixels;
  };
 
  publicAPI.get3DContext = (
    options = {
      preserveDrawingBuffer: false,
      depth: true,
      alpha: true,
      powerPreference: 'high-performance',
    }
  ) => {
    let result = null;
 
    const webgl2Supported = typeof WebGL2RenderingContext !== 'undefined';
    model.webgl2 = false;
    if (model.defaultToWebgl2 && webgl2Supported) {
      result = model.canvas.getContext('webgl2', options);
      if (result) {
        model.webgl2 = true;
        vtkDebugMacro('using webgl2');
      }
    }
    Iif (!result) {
      vtkDebugMacro('using webgl1');
      result =
        model.canvas.getContext('webgl', options) ||
        model.canvas.getContext('experimental-webgl', options);
    }
 
    return new Proxy(result, getCachingContextHandler());
  };
 
  publicAPI.get2DContext = (options = {}) =>
    model.canvas.getContext('2d', options);
 
  publicAPI.restoreContext = () => {
    const rp = vtkRenderPass.newInstance();
    rp.setCurrentOperation('Release');
    rp.traverse(publicAPI, null);
  };
 
  publicAPI.activateTexture = (texture) => {
    // Only add if it isn't already there
    const result = model._textureResourceIds.get(texture);
    if (result !== undefined) {
      model.context.activeTexture(model.context.TEXTURE0 + result);
      return;
    }
 
    const activeUnit = publicAPI.getTextureUnitManager().allocate();
    Iif (activeUnit < 0) {
      vtkErrorMacro(
        'Hardware does not support the number of textures defined.'
      );
      return;
    }
 
    model._textureResourceIds.set(texture, activeUnit);
    model.context.activeTexture(model.context.TEXTURE0 + activeUnit);
  };
 
  publicAPI.deactivateTexture = (texture) => {
    // Only deactivate if it isn't already there
    const result = model._textureResourceIds.get(texture);
    if (result !== undefined) {
      publicAPI.getTextureUnitManager().free(result);
      model._textureResourceIds.delete(texture);
    }
  };
 
  publicAPI.getTextureUnitForTexture = (texture) => {
    const result = model._textureResourceIds.get(texture);
    if (result !== undefined) {
      return result;
    }
    return -1;
  };
 
  publicAPI.getDefaultTextureByteSize = (
    vtkType,
    oglNorm16Ext = null,
    useHalfFloat = false
  ) => {
    if (model.webgl2) {
      switch (vtkType) {
        case VtkDataTypes.CHAR:
        case VtkDataTypes.SIGNED_CHAR:
        case VtkDataTypes.UNSIGNED_CHAR:
          return 1;
        case oglNorm16Ext:
        case useHalfFloat:
        case VtkDataTypes.UNSIGNED_SHORT:
        case VtkDataTypes.SHORT:
        case VtkDataTypes.VOID: // Used for unsigned int depth
          return 2;
        default: // For all other cases, assume float
          return 4;
      }
    }
 
    // webgl1 type support is limited to 1 byte
    return 1;
  };
 
  publicAPI.getDefaultTextureInternalFormat = (
    vtktype,
    numComps,
    oglNorm16Ext = null,
    useHalfFloat = false
  ) => {
    if (model.webgl2) {
      switch (vtktype) {
        case VtkDataTypes.UNSIGNED_CHAR:
          switch (numComps) {
            case 1:
              return model.context.R8;
            case 2:
              return model.context.RG8;
            case 3:
              return model.context.RGB8;
            case 4:
            default:
              return model.context.RGBA8;
          }
        case oglNorm16Ext && !useHalfFloat && VtkDataTypes.UNSIGNED_SHORT:
          switch (numComps) {
            case 1:
              return oglNorm16Ext.R16_EXT;
            case 2:
              return oglNorm16Ext.RG16_EXT;
            case 3:
              return oglNorm16Ext.RGB16_EXT;
            case 4:
            default:
              return oglNorm16Ext.RGBA16_EXT;
          }
        // prioritize norm16 over float
        case oglNorm16Ext && !useHalfFloat && VtkDataTypes.SHORT:
          switch (numComps) {
            case 1:
              return oglNorm16Ext.R16_SNORM_EXT;
            case 2:
              return oglNorm16Ext.RG16_SNORM_EXT;
            case 3:
              return oglNorm16Ext.RGB16_SNORM_EXT;
            case 4:
            default:
              return oglNorm16Ext.RGBA16_SNORM_EXT;
          }
        case VtkDataTypes.UNSIGNED_SHORT:
        case VtkDataTypes.SHORT:
        case VtkDataTypes.FLOAT:
        default:
          // useHalfFloat tells us if the texture can be accurately
          // rendered with 16 bits or not.
          switch (numComps) {
            case 1:
              return useHalfFloat ? model.context.R16F : model.context.R32F;
            case 2:
              return useHalfFloat ? model.context.RG16F : model.context.RG32F;
            case 3:
              return useHalfFloat ? model.context.RGB16F : model.context.RGB32F;
            case 4:
            default:
              return useHalfFloat
                ? model.context.RGBA16F
                : model.context.RGBA32F;
          }
      }
    }
 
    // webgl1 only supports four types
    switch (numComps) {
      case 1:
        return model.context.LUMINANCE;
      case 2:
        return model.context.LUMINANCE_ALPHA;
      case 3:
        return model.context.RGB;
      case 4:
      default:
        return model.context.RGBA;
    }
  };
 
  publicAPI.setBackgroundImage = (img) => {
    model.bgImage.src = img.src;
  };
 
  publicAPI.setUseBackgroundImage = (value) => {
    model.useBackgroundImage = value;
 
    // Add or remove the background image from the
    // DOM as specified.
    if (model.useBackgroundImage && !model.el.contains(model.bgImage)) {
      model.el.appendChild(model.bgImage);
    } else if (!model.useBackgroundImage && model.el.contains(model.bgImage)) {
      model.el.removeChild(model.bgImage);
    }
  };
 
  function getCanvasDataURL(format = model.imageFormat) {
    // Copy current canvas to not modify the original
    const temporaryCanvas = document.createElement('canvas');
    const temporaryContext = temporaryCanvas.getContext('2d');
    temporaryCanvas.width = model.canvas.width;
    temporaryCanvas.height = model.canvas.height;
    temporaryContext.drawImage(model.canvas, 0, 0);
 
    // Get current client rect to place canvas
    const mainBoundingClientRect = model.canvas.getBoundingClientRect();
 
    const renderWindow = model.renderable;
    const renderers = renderWindow.getRenderers();
    renderers.forEach((renderer) => {
      const viewProps = renderer.getViewProps();
      viewProps.forEach((viewProp) => {
        // Check if the prop has a container that should have canvas
        Iif (viewProp.getContainer) {
          const container = viewProp.getContainer();
          const canvasList = container.getElementsByTagName('canvas');
          // Go throughout all canvas and copy it into temporary main canvas
          for (let i = 0; i < canvasList.length; i++) {
            const currentCanvas = canvasList[i];
            const boundingClientRect = currentCanvas.getBoundingClientRect();
            const newXPosition =
              boundingClientRect.x - mainBoundingClientRect.x;
            const newYPosition =
              boundingClientRect.y - mainBoundingClientRect.y;
            temporaryContext.drawImage(
              currentCanvas,
              newXPosition,
              newYPosition
            );
          }
        }
      });
    });
 
    const screenshot = temporaryCanvas.toDataURL(format);
    temporaryCanvas.remove();
    publicAPI.invokeImageReady(screenshot);
  }
 
  publicAPI.captureNextImage = (
    format = 'image/png',
    { resetCamera = false, size = null, scale = 1 } = {}
  ) => {
    Iif (model.deleted) {
      return null;
    }
    model.imageFormat = format;
    const previous = model.notifyStartCaptureImage;
    model.notifyStartCaptureImage = true;
 
    model._screenshot = {
      size:
        !!size || scale !== 1
          ? size || model.size.map((val) => val * scale)
          : null,
    };
 
    return new Promise((resolve, reject) => {
      const subscription = publicAPI.onImageReady((imageURL) => {
        if (model._screenshot.size === null) {
          model.notifyStartCaptureImage = previous;
          subscription.unsubscribe();
          Iif (model._screenshot.placeHolder) {
            // resize the main canvas back to its original size and show it
            model.size = model._screenshot.originalSize;
 
            // process the resize
            publicAPI.modified();
 
            // restore the saved camera parameters, if applicable
            if (model._screenshot.cameras) {
              model._screenshot.cameras.forEach(({ restoreParamsFn, arg }) =>
                restoreParamsFn(arg)
              );
            }
 
            // Trigger a render at the original size
            publicAPI.traverseAllPasses();
 
            // Remove and clean up the placeholder, revealing the original
            model.el.removeChild(model._screenshot.placeHolder);
            model._screenshot.placeHolder.remove();
            model._screenshot = null;
          }
          resolve(imageURL);
        } else E{
          // Create a placeholder image overlay while we resize and render
          const tmpImg = document.createElement('img');
          tmpImg.style = SCREENSHOT_PLACEHOLDER;
          tmpImg.src = imageURL;
          model._screenshot.placeHolder = model.el.appendChild(tmpImg);
 
          // hide the main canvas
          model.canvas.style.display = 'none';
 
          // remember the main canvas original size, then resize it
          model._screenshot.originalSize = model.size;
          model.size = model._screenshot.size;
          model.rootOpenGLRenderWindow?.resizeFromChildRenderWindows();
          model._screenshot.size = null;
 
          // process the resize
          publicAPI.modified();
 
          if (resetCamera) {
            const isUserResetCamera = resetCamera !== true;
 
            // If resetCamera was requested, we first save camera parameters
            // from all the renderers, so we can restore them later
            model._screenshot.cameras = model.renderable
              .getRenderers()
              .map((renderer) => {
                const camera = renderer.getActiveCamera();
                const params = camera.get(
                  'focalPoint',
                  'position',
                  'parallelScale'
                );
 
                return {
                  resetCameraArgs: isUserResetCamera ? { renderer } : undefined,
                  resetCameraFn: isUserResetCamera
                    ? resetCamera
                    : renderer.resetCamera,
                  restoreParamsFn: camera.set,
                  // "clone" the params so we don't keep refs to properties
                  arg: JSON.parse(JSON.stringify(params)),
                };
              });
 
            // Perform the resetCamera() on each renderer only after capturing
            // the params from all active cameras, in case there happen to be
            // linked cameras among the renderers.
            model._screenshot.cameras.forEach(
              ({ resetCameraFn, resetCameraArgs }) =>
                resetCameraFn(resetCameraArgs)
            );
          }
 
          // Trigger a render at the custom size
          publicAPI.traverseAllPasses();
        }
      });
    });
  };
 
  let hardwareMaximumLineWidth;
  publicAPI.getHardwareMaximumLineWidth = () => {
    // We cache the result of this function because `getParameter` is slow
    if (hardwareMaximumLineWidth != null) {
      return hardwareMaximumLineWidth;
    }
 
    const gl = publicAPI.get3DContext();
    const lineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE);
 
    hardwareMaximumLineWidth = lineWidthRange[1];
 
    return lineWidthRange[1];
  };
 
  publicAPI.getGLInformations = () => {
    if (model._glInformation) {
      return model._glInformation;
    }
    const gl = publicAPI.get3DContext();
 
    const glTextureFloat = gl.getExtension('OES_texture_float');
    const glTextureHalfFloat = gl.getExtension('OES_texture_half_float');
    const glDebugRendererInfo = gl.getExtension('WEBGL_debug_renderer_info');
    const glDrawBuffers = gl.getExtension('WEBGL_draw_buffers');
    const glAnisotropic =
      gl.getExtension('EXT_texture_filter_anisotropic') ||
      gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
 
    const params = [
      [
        'Max Vertex Attributes',
        'MAX_VERTEX_ATTRIBS',
        gl.getParameter(gl.MAX_VERTEX_ATTRIBS),
      ],
      [
        'Max Varying Vectors',
        'MAX_VARYING_VECTORS',
        gl.getParameter(gl.MAX_VARYING_VECTORS),
      ],
      [
        'Max Vertex Uniform Vectors',
        'MAX_VERTEX_UNIFORM_VECTORS',
        gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS),
      ],
      [
        'Max Fragment Uniform Vectors',
        'MAX_FRAGMENT_UNIFORM_VECTORS',
        gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS),
      ],
      [
        'Max Fragment Texture Image Units',
        'MAX_TEXTURE_IMAGE_UNITS',
        gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS),
      ],
      [
        'Max Vertex Texture Image Units',
        'MAX_VERTEX_TEXTURE_IMAGE_UNITS',
        gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
      ],
      [
        'Max Combined Texture Image Units',
        'MAX_COMBINED_TEXTURE_IMAGE_UNITS',
        gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
      ],
      [
        'Max 2D Texture Size',
        'MAX_TEXTURE_SIZE',
        gl.getParameter(gl.MAX_TEXTURE_SIZE),
      ],
      [
        'Max Cube Texture Size',
        'MAX_CUBE_MAP_TEXTURE_SIZE',
        gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE),
      ],
      [
        'Max Texture Anisotropy',
        'MAX_TEXTURE_MAX_ANISOTROPY_EXT',
        glAnisotropic &&
          gl.getParameter(glAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT),
      ],
      [
        'Point Size Range',
        'ALIASED_POINT_SIZE_RANGE',
        gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE).join(' - '),
      ],
      [
        'Line Width Range',
        'ALIASED_LINE_WIDTH_RANGE',
        gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE).join(' - '),
      ],
      [
        'Max Viewport Dimensions',
        'MAX_VIEWPORT_DIMS',
        gl.getParameter(gl.MAX_VIEWPORT_DIMS).join(' - '),
      ],
      [
        'Max Renderbuffer Size',
        'MAX_RENDERBUFFER_SIZE',
        gl.getParameter(gl.MAX_RENDERBUFFER_SIZE),
      ],
      ['Framebuffer Red Bits', 'RED_BITS', gl.getParameter(gl.RED_BITS)],
      ['Framebuffer Green Bits', 'GREEN_BITS', gl.getParameter(gl.GREEN_BITS)],
      ['Framebuffer Blue Bits', 'BLUE_BITS', gl.getParameter(gl.BLUE_BITS)],
      ['Framebuffer Alpha Bits', 'ALPHA_BITS', gl.getParameter(gl.ALPHA_BITS)],
      ['Framebuffer Depth Bits', 'DEPTH_BITS', gl.getParameter(gl.DEPTH_BITS)],
      [
        'Framebuffer Stencil Bits',
        'STENCIL_BITS',
        gl.getParameter(gl.STENCIL_BITS),
      ],
      [
        'Framebuffer Subpixel Bits',
        'SUBPIXEL_BITS',
        gl.getParameter(gl.SUBPIXEL_BITS),
      ],
      ['MSAA Samples', 'SAMPLES', gl.getParameter(gl.SAMPLES)],
      [
        'MSAA Sample Buffers',
        'SAMPLE_BUFFERS',
        gl.getParameter(gl.SAMPLE_BUFFERS),
      ],
      [
        'Supported Formats for UByte Render Targets     ',
        'UNSIGNED_BYTE RENDER TARGET FORMATS',
        [
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.RGBA, gl.UNSIGNED_BYTE)
            ? 'RGBA'
            : '',
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.RGB, gl.UNSIGNED_BYTE)
            ? 'RGB'
            : '',
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.LUMINANCE, gl.UNSIGNED_BYTE)
            ? 'LUMINANCE'
            : '',
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.ALPHA, gl.UNSIGNED_BYTE)
            ? 'ALPHA'
            : '',
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE)
            ? 'LUMINANCE_ALPHA'
            : '',
        ].join(' '),
      ],
      [
        'Supported Formats for Half Float Render Targets',
        'HALF FLOAT RENDER TARGET FORMATS',
        [
          glTextureHalfFloat &&
          checkRenderTargetSupport(
            gl,
            gl.RGBA,
            glTextureHalfFloat.HALF_FLOAT_OES
          )
            ? 'RGBA'
            : '',
          glTextureHalfFloat &&
          checkRenderTargetSupport(
            gl,
            gl.RGB,
            glTextureHalfFloat.HALF_FLOAT_OES
          )
            ? 'RGB'
            : '',
          glTextureHalfFloat &&
          checkRenderTargetSupport(
            gl,
            gl.LUMINANCE,
            glTextureHalfFloat.HALF_FLOAT_OES
          )
            ? 'LUMINANCE'
            : '',
          glTextureHalfFloat &&
          checkRenderTargetSupport(
            gl,
            gl.ALPHA,
            glTextureHalfFloat.HALF_FLOAT_OES
          )
            ? 'ALPHA'
            : '',
          glTextureHalfFloat &&
          checkRenderTargetSupport(
            gl,
            gl.LUMINANCE_ALPHA,
            glTextureHalfFloat.HALF_FLOAT_OES
          )
            ? 'LUMINANCE_ALPHA'
            : '',
        ].join(' '),
      ],
      [
        'Supported Formats for Full Float Render Targets',
        'FLOAT RENDER TARGET FORMATS',
        [
          glTextureFloat && checkRenderTargetSupport(gl, gl.RGBA, gl.FLOAT)
            ? 'RGBA'
            : '',
          glTextureFloat && checkRenderTargetSupport(gl, gl.RGB, gl.FLOAT)
            ? 'RGB'
            : '',
          glTextureFloat && checkRenderTargetSupport(gl, gl.LUMINANCE, gl.FLOAT)
            ? 'LUMINANCE'
            : '',
          glTextureFloat && checkRenderTargetSupport(gl, gl.ALPHA, gl.FLOAT)
            ? 'ALPHA'
            : '',
          glTextureFloat &&
          checkRenderTargetSupport(gl, gl.LUMINANCE_ALPHA, gl.FLOAT)
            ? 'LUMINANCE_ALPHA'
            : '',
        ].join(' '),
      ],
      [
        'Max Multiple Render Targets Buffers',
        'MAX_DRAW_BUFFERS_WEBGL',
        glDrawBuffers
          ? gl.getParameter(glDrawBuffers.MAX_DRAW_BUFFERS_WEBGL)
          : 0,
      ],
      [
        'High Float Precision in Vertex Shader',
        'HIGH_FLOAT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Medium Float Precision in Vertex Shader',
        'MEDIUM_FLOAT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT)
            .rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT)
            .rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Low Float Precision in Vertex Shader',
        'LOW_FLOAT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'High Float Precision in Fragment Shader',
        'HIGH_FLOAT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT)
            .rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT)
            .rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Medium Float Precision in Fragment Shader',
        'MEDIUM_FLOAT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT)
            .rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT)
            .rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Low Float Precision in Fragment Shader',
        'LOW_FLOAT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT)
            .rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT)
            .rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'High Int Precision in Vertex Shader',
        'HIGH_INT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Medium Int Precision in Vertex Shader',
        'MEDIUM_INT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Low Int Precision in Vertex Shader',
        'LOW_INT VERTEX_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'High Int Precision in Fragment Shader',
        'HIGH_INT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Medium Int Precision in Fragment Shader',
        'MEDIUM_INT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT)
            .precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT)
            .rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT)
            .rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Low Int Precision in Fragment Shader',
        'LOW_INT FRAGMENT_SHADER',
        [
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).precision,
          ' (-2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMin,
          '</sup> - 2<sup>',
          gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMax,
          '</sup>)',
        ].join(''),
      ],
      [
        'Supported Extensions',
        'EXTENSIONS',
        gl.getSupportedExtensions().join('<br/>\t\t\t\t\t    '),
      ],
      ['WebGL Renderer', 'RENDERER', gl.getParameter(gl.RENDERER)],
      ['WebGL Vendor', 'VENDOR', gl.getParameter(gl.VENDOR)],
      ['WebGL Version', 'VERSION', gl.getParameter(gl.VERSION)],
      [
        'Shading Language Version',
        'SHADING_LANGUAGE_VERSION',
        gl.getParameter(gl.SHADING_LANGUAGE_VERSION),
      ],
      [
        'Unmasked Renderer',
        'UNMASKED_RENDERER',
        glDebugRendererInfo &&
          gl.getParameter(glDebugRendererInfo.UNMASKED_RENDERER_WEBGL),
      ],
      [
        'Unmasked Vendor',
        'UNMASKED_VENDOR',
        glDebugRendererInfo &&
          gl.getParameter(glDebugRendererInfo.UNMASKED_VENDOR_WEBGL),
      ],
      ['WebGL Version', 'WEBGL_VERSION', model.webgl2 ? 2 : 1],
    ];
 
    const result = {};
    while (params.length) {
      const [label, key, value] = params.pop();
      if (key) {
        result[key] = { label, value };
      }
    }
    model._glInformation = result;
    return result;
  };
 
  publicAPI.traverseAllPasses = () => {
    if (model.renderPasses) {
      for (let index = 0; index < model.renderPasses.length; ++index) {
        model.renderPasses[index].traverse(publicAPI, null);
      }
    }
    publicAPI.copyParentContent();
    if (model.notifyStartCaptureImage) {
      getCanvasDataURL();
    }
    const childrenRW = model.renderable.getChildRenderWindowsByReference();
    for (let i = 0; i < childrenRW.length; ++i) {
      publicAPI.getViewNodeFor(childrenRW[i])?.traverseAllPasses();
    }
  };
 
  publicAPI.copyParentContent = () => {
    const rootParent = model.rootOpenGLRenderWindow;
    if (
      !rootParent ||
      !model.context2D ||
      model.children.some((oglRenderer) => !!oglRenderer.getSelector?.())
    ) {
      return;
    }
    const parentCanvas = rootParent.getCanvas();
    const selfCanvas = model.canvas;
    model.context2D.drawImage(
      parentCanvas,
      0,
      parentCanvas.height - selfCanvas.height, // source y axis is inverted
      selfCanvas.width,
      selfCanvas.height,
      0,
      0,
      selfCanvas.width,
      selfCanvas.height
    );
  };
 
  publicAPI.resizeFromChildRenderWindows = () => {
    // Adapt the size of the parent render window to the child render windows
    const childrenRW = model.renderable.getChildRenderWindowsByReference();
    Iif (childrenRW.length > 0) {
      const maxSize = [0, 0];
      for (let i = 0; i < childrenRW.length; ++i) {
        const childSize = publicAPI.getViewNodeFor(childrenRW[i])?.getSize();
        if (childSize) {
          maxSize[0] = childSize[0] > maxSize[0] ? childSize[0] : maxSize[0];
          maxSize[1] = childSize[1] > maxSize[1] ? childSize[1] : maxSize[1];
        }
      }
      publicAPI.setSize(...maxSize);
    }
  };
 
  publicAPI.disableCullFace = () => {
    Iif (model.cullFaceEnabled) {
      model.context.disable(model.context.CULL_FACE);
      model.cullFaceEnabled = false;
    }
  };
 
  publicAPI.enableCullFace = () => {
    if (!model.cullFaceEnabled) {
      model.context.enable(model.context.CULL_FACE);
      model.cullFaceEnabled = true;
    }
  };
 
  publicAPI.setViewStream = (stream) => {
    if (model.viewStream === stream) {
      return false;
    }
    if (model.subscription) {
      model.subscription.unsubscribe();
      model.subscription = null;
    }
    model.viewStream = stream;
    if (model.viewStream) {
      // Force background to be transparent + render
      const mainRenderer = model.renderable.getRenderers()[0];
      mainRenderer.getBackgroundByReference()[3] = 0;
 
      // Enable display of the background image
      publicAPI.setUseBackgroundImage(true);
 
      // Bind to remote stream
      model.subscription = model.viewStream.onImageReady((e) =>
        publicAPI.setBackgroundImage(e.image)
      );
      model.viewStream.setSize(model.size[0], model.size[1]);
      model.viewStream.invalidateCache();
      model.viewStream.render();
 
      publicAPI.modified();
    }
    return true;
  };
 
  publicAPI.createSelector = () => {
    const ret = vtkOpenGLHardwareSelector.newInstance();
    ret.setOpenGLRenderWindow(publicAPI);
    return ret;
  };
 
  function clearEvents() {
    model.canvas.removeEventListener('webglcontextlost', _preventDefault);
    model.canvas.removeEventListener(
      'webglcontextrestored',
      publicAPI.restoreContext
    );
  }
 
  publicAPI.delete = macro.chain(
    () => {
      if (model.context) {
        deleteGLContext();
      }
      publicAPI.setContainer();
      publicAPI.setViewStream();
    },
    clearEvents,
    publicAPI.delete
  );
 
  // Do not trigger modified for performance reasons
  publicAPI.setActiveFramebuffer = (newActiveFramebuffer) => {
    model.activeFramebuffer = newActiveFramebuffer;
  };
 
  const superSetSize = publicAPI.setSize;
  publicAPI.setSize = (width, height) => {
    const modified = superSetSize(width, height);
    if (modified) {
      publicAPI.invokeWindowResizeEvent({ width, height });
    }
    return modified;
  };
 
  publicAPI.registerGraphicsResourceUser = (coreObject, newUser) => {
    // Try to create the graphics resource if it doesn't exist
    Iif (!model._graphicsResources.has(coreObject)) {
      publicAPI.setGraphicsResourceForObject(coreObject, null, null);
    }
    // Add newUser to the set of users
    const sharedResource = model._graphicsResources.get(coreObject);
    sharedResource?.users.add(newUser);
  };
 
  publicAPI.unregisterGraphicsResourceUser = (coreObject, oldUser) => {
    const sharedResource = model._graphicsResources.get(coreObject);
    if (!sharedResource) {
      return;
    }
    sharedResource.users.delete(oldUser);
    // Release graphics resources when the number of users reaches 0
    if (!sharedResource.users.size) {
      sharedResource.oglObject?.releaseGraphicsResources(publicAPI);
      model._graphicsResources.delete(coreObject);
    }
  };
 
  publicAPI.getGraphicsResourceForObject = (coreObject) =>
    model._graphicsResources.get(coreObject);
 
  publicAPI.setGraphicsResourceForObject = (coreObject, oglObject, hash) => {
    Iif (!coreObject) {
      return;
    }
    const sharedResource = model._graphicsResources.get(coreObject);
    // Release the old resource
    sharedResource?.oglObject?.releaseGraphicsResources(publicAPI);
    // Keep the same users that have registered for this coreObject
    model._graphicsResources.set(coreObject, {
      coreObject,
      oglObject,
      hash,
      users: sharedResource?.users ?? new Set(),
    });
  };
 
  publicAPI.getGraphicsMemoryInfo = () => {
    let memUsed = 0;
    model._graphicsResources.forEach(({ oglObject }) => {
      memUsed += oglObject.getAllocatedGPUMemoryInBytes();
    });
    return memUsed;
  };
 
  publicAPI.releaseGraphicsResources = () => {
    // Clear the shader cache
    if (model.shaderCache !== null) {
      model.shaderCache.releaseGraphicsResources(publicAPI);
    }
    // Free cached graphics resources at the context level
    model._graphicsResources.forEach(({ oglObject }) => {
      oglObject.releaseGraphicsResources(publicAPI);
    });
    model._graphicsResources.clear();
    if (model.textureUnitManager !== null) {
      model.textureUnitManager.freeAll();
    }
    // Finally, ask the renderers to release prop resources
    model.renderable.getRenderersByReference().forEach((ren) => {
      const glRen = publicAPI.getViewNodeFor(ren);
      glRen?.releaseGraphicsResources();
    });
  };
 
  // Proxy some methods if needed
  const publicAPIBeforeProxy = { ...publicAPI };
  parentMethodsToProxy.forEach((methodName) => {
    publicAPI[methodName] = (...args) => {
      Iif (model.rootOpenGLRenderWindow) {
        // Proxy only methods when the render window has a parent
        return model.rootOpenGLRenderWindow[methodName](...args);
      }
      return publicAPIBeforeProxy[methodName](...args);
    };
  });
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  cullFaceEnabled: false,
  shaderCache: null,
  initialized: false,
  context: null,
  context2D: null,
  canvas: null,
  cursorVisibility: true,
  cursor: 'pointer',
  textureUnitManager: null,
  textureResourceIds: null,
  containerSize: null,
  renderPasses: [],
  notifyStartCaptureImage: false,
  webgl2: false,
  defaultToWebgl2: true, // attempt webgl2 on by default
  activeFramebuffer: null,
  imageFormat: 'image/png',
  useOffScreen: false,
  useBackgroundImage: false,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Inheritance
  vtkRenderWindowViewNode.extend(publicAPI, model, initialValues);
 
  // Create internal instances
  if (!model.canvas) {
    model.canvas = document.createElement('canvas');
    model.canvas.style.width = '100%';
  }
 
  if (!model.selector) {
    model.selector = vtkOpenGLHardwareSelector.newInstance();
    model.selector.setOpenGLRenderWindow(publicAPI);
  }
 
  // Create internal bgImage
  model.bgImage = new Image();
  model.bgImage.style.position = 'absolute';
  model.bgImage.style.left = '0';
  model.bgImage.style.top = '0';
  model.bgImage.style.width = '100%';
  model.bgImage.style.height = '100%';
  model.bgImage.style.zIndex = '-1';
 
  model._textureResourceIds = new Map();
  model._graphicsResources = new Map();
  model._glInformation = null;
 
  model.myFactory = vtkOpenGLViewNodeFactory.newInstance();
 
  model.shaderCache = vtkShaderCache.newInstance();
  model.shaderCache.setOpenGLRenderWindow(publicAPI);
 
  // setup default forward pass rendering
  model.renderPasses[0] = vtkForwardPass.newInstance();
 
  // Build VTK API
  macro.get(publicAPI, model, [
    'shaderCache',
    'textureUnitManager',
    'webgl2',
    'useBackgroundImage',
    'activeFramebuffer',
    'rootOpenGLRenderWindow',
  ]);
 
  macro.setGet(publicAPI, model, [
    'initialized',
    'context',
    'context2D',
    'canvas',
    'renderPasses',
    'notifyStartCaptureImage',
    'defaultToWebgl2',
    'cursor',
    'useOffScreen',
  ]);
 
  macro.setGetArray(publicAPI, model, ['size'], 2);
  macro.event(publicAPI, model, 'imageReady');
  macro.event(publicAPI, model, 'windowResizeEvent');
 
  // Object methods
  vtkOpenGLRenderWindow(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkOpenGLRenderWindow');
 
// ----------------------------------------------------------------------------
// Register API specific RenderWindow implementation
// ----------------------------------------------------------------------------
 
registerViewConstructor('WebGL', newInstance);
 
// ----------------------------------------------------------------------------
 
export default {
  newInstance,
  extend,
  pushMonitorGLContextCount,
  popMonitorGLContextCount,
};
 
// Register ourself to OpenGL backend if imported
registerOverride('vtkRenderWindow', newInstance);