All files / src GLViewer.ts

0.09% Statements 2/2089
0% Branches 0/698
0% Functions 0/208
0.1% Lines 2/1951

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 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932                                                    18x 18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
//a molecular viewer based on GLMol
 
import { Geometry, CC, Renderer, Camera, Raycaster, Projector, Light, Fog, Scene, Coloring, FrontSide } from "./WebGL";
import { Vector3, Matrix4, Matrix3, Quaternion } from "./WebGL/math";
import { MeshLambertMaterial, Object3D, Mesh, LineBasicMaterial, Line } from "./WebGL";
import { getColorFromStyle, elementColors } from "./colors";
import { extend, getExtent, makeFunction, getPropertyRange, isEmptyObject, adjustVolumeStyle, mergeGeos, PausableTimer } from "./utilities";
import { Gradient } from "./Gradient";
import { GLModel } from "./GLModel";
import { Label } from "./Label";
import { GLShape, splitMesh } from "./GLShape";
import { VolumeData } from "./VolumeData";
import { ProteinSurface, SurfaceType, syncSurface } from "./ProteinSurface4";
import { GLVolumetricRender } from "./VolumetricRender";
 
declare var $: any;
declare var UPNG: any;
 
/**
 * WebGL-based 3Dmol.js viewer
 * Note: The preferred method of instantiating a GLViewer is through {@link $3Dmol.createViewer}
 *
 * @class
*/
export class GLViewer {
    // private class variables
    private static numWorkers = 4; // number of threads for surface generation
    private static maxVolume = 64000; // how much to break up surface calculations
 
    private callback: any;
    private defaultcolors: any;
    private config: any;
    private nomouse = false;
    private bgColor: any;
    private camerax: number;
    private _viewer: GLViewer;
    private glDOM: any = null;
    private ui: any = null;
 
    private models = []; // atomistic molecular models
    private surfaces: any = {};
    private shapes = []; // Generic shapes
    private labels = [];
    private fixed_labels = [];
    private clickables = []; //things you can click on
    private hoverables = []; //things you can hover over
    private contextMenuEnabledAtoms = []; // atoms with context menu
    private current_hover: any = null;
    private hoverDuration = 500;
    private viewer_frame = 0;
    private WIDTH: number;
    private HEIGHT: number;
    private viewChangeCallback: any = null;
    private stateChangeCallback: any = null;
 
    private NEAR = 1;
    private FAR = 800;
    private CAMERA_Z = 150;
    private fov = 20;
 
    private linkedViewers = [];
    private renderer: any = null;
 
    private row: number;
    private col: number;
    private cols: number;
    private rows: number;
    private viewers: any;
    private control_all = false;
 
    private ASPECT: any;
    private camera: Camera;
    private lookingAt: Vector3;
 
    private raycaster: Raycaster;
    private projector: Projector;
 
    private scene: any = null;
    private rotationGroup: any = null; // which contains modelGroup
    private modelGroup: any = null;
 
    private fogStart = 0.4;
    private slabNear = -50; // relative to the center of rotationGroup
    private slabFar = 50;
 
    public container: any;
 
    surfaceTypeMap = {
        "VDW": SurfaceType.VDW,
        "MS": SurfaceType.MS,
        "SAS": SurfaceType.SAS,
        "SES": SurfaceType.SES
    };
 
 
    // UI variables
    private cq = new Quaternion(0, 0, 0, 1);
    private dq = new Quaternion(0, 0, 0, 1);
    private animated = 0;
    private animationTimers = new Set<PausableTimer>();
    private isDragging = false;
    private mouseStartX = 0;
    private mouseStartY = 0;
    private touchDistanceStart = 0;
    private touchHold = false;
    private currentModelPos = 0;
    private cz = 0;
    private cslabNear = 0;
    private cslabFar = 0;
 
    private mouseButton: any;
    private hoverTimeout: any;
 
    private divwatcher: any;
    private spinInterval: any;
 
 
    //reimplement jquery getwidth/height
    private getRect() {
        let div = this.container[0];
        let rect = div.getBoundingClientRect();
        Iif (rect.width == 0 && rect.height == 0 && div.style.display === 'none') {
            let oldpos = div.style.position;
            let oldvis = div.style.visibility;
            div.style.display = 'block';
            div.style.visibility = 'hidden';
            div.style.position = 'absolute';
            rect = div.getBoundingClientRect();
            div.style.display = 'none';
            div.style.visibility = oldvis;
            div.style.position = oldpos;
        }
        return rect;
    };
 
    private getWidth() {
        return this.getRect().width;
    };
 
    private getHeight() {
        return this.getRect().height;
    };
 
    private setupRenderer() {
 
        this.renderer = new Renderer({
            antialias: this.config.antialias,
            preserveDrawingBuffer: true, //so we can export images
            premultipliedAlpha: false,/* more traditional compositing with background */
            id: this.config.id,
            row: this.config.row,
            col: this.config.col,
            rows: this.config.rows,
            cols: this.config.cols,
            canvas: this.config.canvas,
            //cannot initialize with zero size
            containerWidth: this.WIDTH || 1,
            containerHeight: this.HEIGHT || 1,
        });
        this.renderer.domElement.style.width = "100%";
        this.renderer.domElement.style.height = "100%";
        this.renderer.domElement.style.padding = "0";
        this.renderer.domElement.style.position = "absolute"; //TODO: get rid of this
        this.renderer.domElement.style.top = "0px";
        this.renderer.domElement.style.left = "0px";
        this.renderer.domElement.style.zIndex = "0";
    }
 
    private initializeScene() {
 
        this.scene = new Scene();
        this.scene.fog = new Fog(this.bgColor, 100, 200);
 
        this.modelGroup = new Object3D();
        this.rotationGroup = new Object3D();
        this.rotationGroup.useQuaternion = true;
        this.rotationGroup.quaternion = new Quaternion(0, 0, 0, 1);
        this.rotationGroup.add(this.modelGroup);
 
        this.scene.add(this.rotationGroup);
 
        // setup lights
        var directionalLight = new Light(0xFFFFFF);
        directionalLight.position = new Vector3(0.2, 0.2, 1)
            .normalize();
        directionalLight.intensity = 1.0;
        this.scene.add(directionalLight);
    };
 
    private initContainer(element) {
        this.container = element;
        this.WIDTH = this.getWidth();
        this.HEIGHT = this.getHeight();
        this.ASPECT = this.renderer.getAspect(this.WIDTH, this.HEIGHT);
        this.renderer.setSize(this.WIDTH, this.HEIGHT);
        this.container.append(this.renderer.domElement);
        this.glDOM = $(this.renderer.domElement);
 
        Iif (!this.nomouse) {
            // user can request that the mouse handlers not be installed
            this.glDOM.on('mousedown touchstart', this._handleMouseDown.bind(this));
            this.glDOM.on('wheel', this._handleMouseScroll.bind(this));
            this.glDOM.on('mousemove touchmove', this._handleMouseMove.bind(this));
 
            this.glDOM.on("contextmenu", this._handleContextMenu.bind(this));
        }
 
    };
 
    private decAnim() {
        //decrement the number of animations currently
        this.animated--;
        Iif (this.animated < 0) this.animated = 0;
    };
 
    private incAnim() {
        this.animated++;
    };
 
    private nextSurfID() {
        //compute the next highest surface id directly from surfaces
        //this is necessary to support linking of model data
        var max = 0;
        for (let i in this.surfaces) { // this is an object with possible holes
            Iif (!this.surfaces.hasOwnProperty(i)) continue;
            var val = parseInt(i);
            Iif (!isNaN(val)) {
                Iif (val > max)
                    max = val;
            }
        }
        return max + 1;
    };
 
    private setSlabAndFog() {
 
        let center = this.camera.position.z - this.rotationGroup.position.z;
        Iif (center < 1)
            center = 1;
        this.camera.near = center + this.slabNear;
        Iif (this.camera.near < 1)
            this.camera.near = 1;
        this.camera.far = center + this.slabFar;
        Iif (this.camera.near + 1 > this.camera.far)
            this.camera.far = this.camera.near + 1;
 
        this.camera.fov = this.fov;
        this.camera.right = center * Math.tan(Math.PI / 180 * this.fov);
        this.camera.left = -this.camera.right;
        this.camera.top = this.camera.right / this.ASPECT;
        this.camera.bottom = -this.camera.top;
 
        this.camera.updateProjectionMatrix();
 
        this.scene.fog.near = this.camera.near + this.fogStart * (this.camera.far - this.camera.near);
        // if (scene.fog.near > center) scene.fog.near = center;
        this.scene.fog.far = this.camera.far;
 
        Iif (this.config.disableFog) {
            this.scene.fog.near = this.scene.fog.far;
        }
    };
 
    // display scene
    //if nolink is set/true, don't propagate changes to linked viewers
    private show(nolink?) {
        this.renderer.setViewport();
        Iif (!this.scene)
            return;
        // var time = new Date();
        this.setSlabAndFog();
        this.renderer.render(this.scene, this.camera);
        // console.log("rendered in " + (+new Date() - time) + "ms");
 
        //have any scene change trigger a callback
        Iif (this.viewChangeCallback) this.viewChangeCallback(this._viewer.getView());
 
        Iif (!nolink && this.linkedViewers.length > 0) {
            var view = this._viewer.getView();
            for (var i = 0; i < this.linkedViewers.length; i++) {
                var other = this.linkedViewers[i];
                other.setView(view, true);
            }
        }
    };
 
 
    //regenerate the list of clickables
    //also updates hoverables
    private updateClickables() {
        this.clickables.splice(0, this.clickables.length);
        this.hoverables.splice(0, this.hoverables.length);
        this.contextMenuEnabledAtoms.splice(0, this.contextMenuEnabledAtoms.length);
 
        for (let i = 0, il = this.models.length; i < il; i++) {
            var model = this.models[i];
            Iif (model) {
                let atoms = model.selectedAtoms({
                    clickable: true
                });
 
                let hoverable_atoms = model.selectedAtoms({
                    hoverable: true
                });
 
                let contextMenuEnabled_atom = model.selectedAtoms({ contextMenuEnabled: true });
                // Array.prototype.push.apply(hoverables,hoverable_atoms);
                for (let n = 0; n < hoverable_atoms.length; n++) {
                    this.hoverables.push(hoverable_atoms[n]);
                }
 
                // Array.prototype.push.apply(clickables, atoms); //add atoms into clickables
                for (let m = 0; m < atoms.length; m++) {
                    this.clickables.push(atoms[m]);
                }
 
                // add atoms into contextMenuEnabledAtoms
                for (let m = 0; m < contextMenuEnabled_atom.length; m++) {
                    this.contextMenuEnabledAtoms.push(contextMenuEnabled_atom[m]);
                }
 
            }
        }
        for (let i = 0, il = this.shapes.length; i < il; i++) {
 
            let shape = this.shapes[i];
            Iif (shape && shape.clickable) {
                this.clickables.push(shape);
            }
            Iif (shape && shape.hoverable) {
                this.hoverables.push(shape);
            }
        }
    };
 
    // Checks for selection intersects on mousedown
    private handleClickSelection(mouseX, mouseY, event) {
        let intersects = this.targetedObjects(mouseX, mouseY, this.clickables);
        // console.log('handleClickSelection', mouseX, mouseY, intersects);
        Iif (intersects.length) {
            var selected = intersects[0].clickable;
            Iif (selected.callback !== undefined) {
                Iif (typeof (selected.callback) != "function") {
                    selected.callback = makeFunction(selected.callback);
                }
                Iif (typeof (selected.callback) === "function") {
                    selected.callback(selected, this._viewer, event, this.container);
                }
            }
        }
    };
 
 
    //return offset of container
    private canvasOffset() {
        let canvas = this.glDOM.get(0);
        let rect = canvas.getBoundingClientRect();
        let doc = canvas.ownerDocument;
        let docElem = doc.documentElement;
        let win = doc.defaultView;
        return {
            top: rect.top + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft
        };
    };
 
    //set current_hover to sel (which can be null), calling appropraite callbacks
    private setHover(selected, event?) {
        Iif (this.current_hover == selected) return;
        Iif (this.current_hover) {
            Iif (typeof (this.current_hover.unhover_callback) != "function") {
                this.current_hover.unhover_callback = makeFunction(this.current_hover.unhover_callback);
            }
            this.current_hover.unhover_callback(this.current_hover, this._viewer, event, this.container);
        }
        this.current_hover = selected;
 
        Iif (selected && selected.hover_callback !== undefined) {
            Iif (typeof (selected.hover_callback) != "function") {
                selected.hover_callback = makeFunction(selected.hover_callback);
            }
            Iif (typeof (selected.hover_callback) === "function") {
                selected.hover_callback(selected, this._viewer, event, this.container);
            }
        }
 
    };
 
    //checks for selection intersects on hover
    private handleHoverSelection(mouseX, mouseY) {
        Iif (this.hoverables.length == 0) return;
        let intersects = this.targetedObjects(mouseX, mouseY, this.hoverables);
        if (intersects.length) {
            var selected = intersects[0].clickable;
            this.setHover(selected);
            this.current_hover = selected;
        }
        else {
            this.setHover(null);
        }
    };
 
    //sees if the mouse is still on the object that invoked a hover event and if not then the unhover callback is called
    private handleHoverContinue(mouseX, mouseY) {
        let intersects = this.targetedObjects(mouseX, mouseY, this.hoverables);
        Iif (intersects.length == 0 || intersects[0] === undefined) {
            this.setHover(null);
        }
        Iif (intersects[0] !== undefined && intersects[0].clickable !== this.current_hover) {
            this.setHover(null);
        }
    };
 
    private calcTouchDistance(ev) { // distance between first two
        // fingers
        var xdiff = ev.originalEvent.targetTouches[0].pageX -
            ev.originalEvent.targetTouches[1].pageX;
        var ydiff = ev.originalEvent.targetTouches[0].pageY -
            ev.originalEvent.targetTouches[1].pageY;
        return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
    };
 
    //check targetTouches as well
    private getX(ev) {
        var x = ev.pageX;
        Iif (x == undefined) x = ev.originalEvent.pageX; //firefox
        if (ev.originalEvent.targetTouches &&
            ev.originalEvent.targetTouches[0]) {
            x = ev.originalEvent.targetTouches[0].pageX;
        }
        else Iif (ev.originalEvent.changedTouches &&
            ev.originalEvent.changedTouches[0]) {
            x = ev.originalEvent.changedTouches[0].pageX;
        }
        return x;
    };
 
    private getY(ev) {
        var y = ev.pageY;
        Iif (y == undefined) y = ev.originalEvent.pageY;
        if (ev.originalEvent.targetTouches &&
            ev.originalEvent.targetTouches[0]) {
            y = ev.originalEvent.targetTouches[0].pageY;
        }
        else Iif (ev.originalEvent.changedTouches &&
            ev.originalEvent.changedTouches[0]) {
            y = ev.originalEvent.changedTouches[0].pageY;
        }
        return y;
    };
 
    //for grid viewers, return true if point is in this viewer
    private isInViewer(x, y) {
        Iif (this.viewers != undefined && !this.control_all) {
            var width = this.WIDTH / this.cols;
            var height = this.HEIGHT / this.rows;
            var offset = this.canvasOffset();
            var relx = (x - offset.left);
            var rely = (y - offset.top);
 
            var r = this.rows - Math.floor(rely / height) - 1;
            var c = Math.floor(relx / width);
 
            Iif (r != this.row || c != this.col)
                return false;
        }
        return true;
    };
 
    //if the user has specify zoom limits, readjust to fit within them
    //also, make sure we don't go past CAMERA_Z
    private adjustZoomToLimits(z) {
        //a lower limit of 0 is at CAMERA_Z
        Iif (this.config.lowerZoomLimit && this.config.lowerZoomLimit > 0) {
            var lower = this.CAMERA_Z - this.config.lowerZoomLimit;
            Iif (z > lower) z = lower;
        }
 
        Iif (this.config.upperZoomLimit && this.config.upperZoomLimit > 0) {
            var upper = this.CAMERA_Z - this.config.upperZoomLimit;
            Iif (z < upper) z = upper;
        }
 
        Iif (z > this.CAMERA_Z) {
            z = this.CAMERA_Z * 0.999; //avoid getting stuck
        }
        return z;
    };
    //interpolate between two normalized quaternions (t between 0 and 1)
    //https://en.wikipedia.org/wiki/Slerp
    private static slerp(v0, v1, t) {
        // Compute the cosine of the angle between the two vectors.
        //dot product
        if (t == 1) return v1;
        else Iif (t == 0) return v0;
        var dot = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z + v0.w * v1.w;
        Iif (dot > 0.9995) {
            // If the inputs are too close for comfort, linearly interpolate
            // and normalize the result.
            var result = new Quaternion(
                v0.x + t * (v1.x - v0.x),
                v0.y + t * (v1.y - v0.y),
                v0.z + t * (v1.z - v0.z),
                v0.w + t * (v1.w - v0.w));
 
            result.normalize();
            return result;
        }
 
        // If the dot product is negative, the quaternions
        // have opposite handed-ness and slerp won't take
        // the shorted path. Fix by reversing one quaternion.
        Iif (dot < 0.0) {
            v1 = v1.clone().multiplyScalar(-1);
            dot = -dot;
        }
 
        if (dot > 1) dot = 1.0;
        else Iif (dot < -1) dot = -1.0;
 
        var theta_0 = Math.acos(dot);  // theta_0 = angle between input vectors
        var theta = theta_0 * t;    // theta = angle between v0 and result
 
        var v2 = v1.clone();
        v2.sub(v0.clone().multiplyScalar(dot));
        v2.normalize();              // { v0, v2 } is now an orthonormal basis
 
        var c = Math.cos(theta);
        var s = Math.sin(theta);
        var ret = new Quaternion(
            v0.x * c + v2.x * s,
            v0.y * c + v2.y * s,
            v0.z * c + v2.z * s,
            v0.w * c + v2.w * s
        );
        ret.normalize();
        return ret;
    };
 
 
    /* @param {Object} element HTML element within which to create viewer
     * @param {ViewerSpec} config Object containing optional configuration for the viewer
     */
    constructor(element, c) {
        // set variables
        this.config = c || {};
        this.callback = this.config.callback;
        this.defaultcolors = this.config.defaultcolors;
        Iif (!this.defaultcolors)
            this.defaultcolors = elementColors.defaultColors;
        this.nomouse = this.config.nomouse;
        this.bgColor = 0;
        this.config.backgroundColor = this.config.backgroundColor || "#ffffff";
        Iif (typeof (this.config.backgroundColor) != 'undefined') {
            this.bgColor = CC.color(this.config.backgroundColor).getHex();
        }
        this.config.backgroundAlpha = this.config.backgroundAlpha == undefined ? 1.0 : this.config.backgroundAlpha;
 
        this.camerax = 0;
        Iif (typeof (this.config.camerax) != 'undefined') {
            this.camerax = parseFloat(this.config.camerax);
        }
        this._viewer = this;
        this.container = $(element); //we expect container to be jquery
 
        Iif (this.config.hoverDuration != undefined) {
            this.hoverDuration = this.config.hoverDuration;
        }
        Iif (this.config.antialias === undefined) this.config.antialias = true;
        Iif (this.config.cartoonQuality === undefined) this.config.cartoonQuality = 10;
 
        this.WIDTH = this.getWidth();
        this.HEIGHT = this.getHeight();
 
        this.setupRenderer();
 
        this.row = this.config.row;
        this.col = this.config.col;
        this.cols = this.config.cols;
        this.rows = this.config.rows;
        this.viewers = this.config.viewers;
        this.control_all = this.config.control_all;
 
        this.ASPECT = this.renderer.getAspect(this.WIDTH, this.HEIGHT);
 
        this.camera = new Camera(this.fov, this.ASPECT, this.NEAR, this.FAR, this.config.orthographic);
        this.camera.position = new Vector3(this.camerax, 0, this.CAMERA_Z);
        this.lookingAt = new Vector3();
        this.camera.lookAt(this.lookingAt);
 
        this.raycaster = new Raycaster(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
        this.projector = new Projector();
 
        this.initializeScene();
        this.renderer.setClearColorHex(this.bgColor, this.config.backgroundAlpha);
        this.scene.fog.color = CC.color(this.bgColor);
 
        // this event is bound to the body element, not the container,
        // so no need to put it inside initContainer()
        $('body').on('mouseup touchend', this._handleMouseUp.bind(this));
 
        this.initContainer(this.container);
        Iif (this.config.style) { //enable setting style in constructor
            this.setViewStyle(this.config);
        }
 
        $(window).resize(this.resize.bind(this));
 
        Iif (typeof (window.ResizeObserver) !== "undefined") {
            this.divwatcher = new window.ResizeObserver(this.resize.bind(this));
            this.divwatcher.observe(this.container[0]);
        }
 
        try {
            Iif (typeof (this.callback) === "function")
                this.callback(this);
        } catch (e) {
            // errors in callback shouldn't invalidate the viewer
            console.log("error with glviewer callback: " + e);
        }
 
        this.ui = new $3Dmol.StateManager(this._viewer, this.config); // Creates the UI state management tool
 
    };
 
    /**
    * Return a list of objects that intersect that at the specified viewer position.
    *
    * @function $3Dmol.GLViewer#targetedObjects
    * @param {x} - x position in screen coordinates
    * @param {y} - y position in screen coordinates
    * @param {Object[]} - list of objects or selection object specifying what object to check for targeting
    */
    public targetedObjects(x, y, objects) {
        var mouse = {
            x: x,
            y: y,
            z: -1.0
        };
        Iif (!Array.isArray(objects)) { //assume selection object
            objects = this.selectedAtoms(objects);
        }
        Iif (objects.length == 0) return [];
        this.raycaster.setFromCamera(mouse, this.camera);
        return this.raycaster.intersectObjects(this.modelGroup, objects);
    };
 
    /** Convert model coordinates to screen coordinates.
     * @function $3Dmol.GLViewer#modelToScreen
     * @param {object | list} - an object or list of objects with x,y,z attributes (e.g. an atom)
     * @return {object | list} - and object or list of {x: screenX, y: screenY}
     */
    public modelToScreen(coords) {
        let returnsingle = false;
        Iif (!Array.isArray(coords)) {
            coords = [coords];
            returnsingle = true;
        }
 
        let results = [];
        let offset = this.canvasOffset();
        coords.forEach(coord => {
            let t = new Vector3(coord.x, coord.y, coord.z);
            t.applyMatrix4(this.modelGroup.matrixWorld);
            this.projector.projectVector(t, this.camera);
            let screenX = this.WIDTH * (t.x + 1) / 2.0 + offset.left;
            let screenY = -this.HEIGHT * (t.y - 1) / 2.0 + offset.top;
            results.push({ x: screenX, y: screenY });
        });
        Iif (returnsingle) results = results[0];
        return results;
    };
 
    /**
     * For a given screen (x,y) displacement return model displacement
     * @param{x} x displacement in screen coordinates
     * @param{y} y displacement in screen corodinates
     * @param{modelz} z coordinate in model coordinates to compute offset for, default is model axis
     * @function $3Dmol.GLViewer#screenOffsetToModel
    */
    public screenOffsetToModel(x, y, modelz?) {
        var dx = x / this.WIDTH;
        var dy = y / this.HEIGHT;
        var zpos = (modelz === undefined ? this.rotationGroup.position.z : modelz);
        var q = this.rotationGroup.quaternion;
        var t = new Vector3(0, 0, zpos);
        this.projector.projectVector(t, this.camera);
        t.x += dx * 2;
        t.y -= dy * 2;
        this.projector.unprojectVector(t, this.camera);
        t.z = 0;
        t.applyQuaternion(q);
        return t;
    };
 
    /**
     * Distance from screen coordinate to model coordinate assuming screen point
     * is projected to the same depth as model coordinate
     * @param{screen} xy screen coordinate
     * @param{model} xyz model coordinate
     * @function $3Dmol.GLViewer#screenToModelDistance
    */
    public screenToModelDistance(screen, model) {
        let offset = this.canvasOffset();
 
        //convert model to screen to get screen z
        let mvec = new Vector3(model.x, model.y, model.z);
        mvec.applyMatrix4(this.modelGroup.matrixWorld);
        let m = mvec.clone();
        this.projector.projectVector(mvec, this.camera);
 
        let t = new Vector3((screen.x - offset.left) * 2 / this.WIDTH - 1, (screen.y - offset.top) * 2 / -this.HEIGHT + 1, mvec.z);
        this.projector.unprojectVector(t, this.camera);
 
        return t.distanceTo(m);
    };
 
    /**
     * Set a callback to call when the view has potentially changed.
     *
     * @function $3Dmol.GLViewer#setViewChangeCallback
    */
    public setViewChangeCallback(callback) {
        Iif (typeof (callback) === 'function' || callback == null)
            this.viewChangeCallback = callback;
    };
 
    /**
     * Set a callback to call when the view has potentially changed.
     *
     * @function $3Dmol.GLViewer#setStateChangeCallback
    */
    public setStateChangeCallback(callback) {
        Iif (typeof (callback) === 'function' || callback == null)
            this.stateChangeCallback = callback;
    };
 
    /**
     * Return configuration of viewer
     */
    public getConfig() {
        return this.config;
    };
 
    /**
     * Set the configuration object.  Note that some setting may only
     * have an effect at viewer creation time.
     */
    public setConfig(c) {
        this.config = c;
    };
 
    /**
     * Return object representing internal state of
     * the viewer appropriate for passing to setInternalState
     *
     * @function $3Dmol.GLViewer#getInternalState
    */
    public getInternalState() {
        var ret = { 'models': [], 'surfaces': [], 'shapes': [], 'labels': [] };
        for (let i = 0; i < this.models.length; i++) {
            Iif (this.models[i]) {
                ret.models[i] = this.models[i].getInternalState();
            }
        }
 
        //todo: labels, shapes, surfaces
 
        return ret;
    };
 
    /**
     * Overwrite internal state of the viewer with passed  object
     * which should come from getInternalState.
     *
     * @function $3Dmol.GLViewer#setInternalState
    */
    public setInternalState(state) {
 
        //clear out current viewer
        this.clear();
 
        //set model state
        var newm = state.models;
        for (let i = 0; i < newm.length; i++) {
            Iif (newm[i]) {
                this.models[i] = new GLModel(i);
                this.models[i].setInternalState(newm[i]);
            }
        }
 
        //todo: labels, shapes, surfaces
        this.render();
    };
 
    /**
     * Set lower and upper limit stops for zoom.
     *
     * @function $3Dmol.GLViewer#setZoomLimits
     * @param {lower} - limit on zoom in (positive number).  Default 0.
     * @param {upper} - limit on zoom out (positive number).  Default infinite.
     * @example
      $.get("data/set1_122_complex.mol2", function(moldata) {
            var m = viewer.addModel(moldata);
            viewer.setStyle({stick:{colorscheme:"Jmol"}});
            viewer.setZoomLimits(100,200);
            viewer.zoomTo();
            viewer.zoom(10); //will not zoom all the way
            viewer.render();
        });
    */
    public setZoomLimits(lower, upper) {
        Iif (typeof (lower) !== 'undefined') this.config.lowerZoomLimit = lower;
        Iif (upper) this.config.upperZoomLimit = upper;
        this.rotationGroup.position.z = this.adjustZoomToLimits(this.rotationGroup.position.z);
        this.show();
    };
 
    /**
     * Set camera parameters (distance to the origin and field of view)
     *
     * @function $3Dmol.GLViewer#setCameraParameters
     * @param {parameters} - new camera parameters, with possible fields
     *                       being fov for the field of view, z for the
     *                       distance to the origin, and orthographic (boolean)
     *                       for kind of projection (default false).
     * @example
      $.get("data/set1_122_complex.mol2", function(data) {
            var m = viewer.addModel(data);
            viewer.setStyle({stick:{}});
            viewer.zoomTo();
            viewer.setCameraParameters({ fov: 10 , z: 300 });
            viewer.render();
        });
    */
    public setCameraParameters(parameters) {
        Iif (parameters.fov !== undefined) {
            this.fov = parameters.fov;
            this.camera.fov = this.fov;
        }
 
        Iif (parameters.z !== undefined) {
            this.CAMERA_Z = parameters.z;
            this.camera.z = this.CAMERA_Z;
        }
        Iif (parameters.orthographic !== undefined) {
            this.camera.ortho = parameters.orthographic;
        }
    };
 
    public _handleMouseDown(ev) {
        ev.preventDefault();
        Iif (!this.scene)
            return;
        var x = this.getX(ev);
        var y = this.getY(ev);
        Iif (x === undefined)
            return;
        this.isDragging = true;
        this.mouseButton = ev.which;
        this.mouseStartX = x;
        this.mouseStartY = y;
        this.touchHold = true;
        this.touchDistanceStart = 0;
        Iif (ev.originalEvent.targetTouches &&
            ev.originalEvent.targetTouches.length == 2) {
            this.touchDistanceStart = this.calcTouchDistance(ev);
        }
        this.cq = this.rotationGroup.quaternion.clone();
        this.cz = this.rotationGroup.position.z;
        this.currentModelPos = this.modelGroup.position.clone();
        this.cslabNear = this.slabNear;
        this.cslabFar = this.slabFar;
 
        let self = this;
        setTimeout(function () {
            Iif (ev.originalEvent.targetTouches) {
                if (self.touchHold == true) {
                    // console.log('Touch hold', x,y);
                    self.glDOM = $(self.renderer.domElement);
                    self.glDOM.trigger('contextmenu');
                }
                else {
                    // console.log('Touch hold ended earlier');
 
                }
            }
        }, 1000);
 
        // Exiting context menu on next mouse event
        this.ui.exitContextMenu();
    };
 
    public _handleMouseUp(ev) {
        // handle touch
        this.touchHold = false;
 
        // handle selection
        Iif (this.isDragging && this.scene) { //saw mousedown, haven't moved
            var x = this.getX(ev);
            var y = this.getY(ev);
            Iif (x == this.mouseStartX && y == this.mouseStartY) {
                var offset = this.canvasOffset();
                var mouseX = ((x - offset.left) / this.WIDTH) * 2 - 1;
                var mouseY = -((y - offset.top) / this.HEIGHT) * 2 + 1;
                this.handleClickSelection(mouseX, mouseY, ev);
            }
        }
 
        this.isDragging = false;
    }
 
    public _handleMouseScroll(ev) { // Zoom
        ev.preventDefault();
        Iif (!this.scene)
            return;
 
        var x = this.getX(ev);
        var y = this.getY(ev);
        Iif (x === undefined)
            return;
        Iif (!this.isInViewer(x, y)) {
            return;
        }
 
        var scaleFactor = (this.CAMERA_Z - this.rotationGroup.position.z) * 0.85;
        var mult = 1.0;
        Iif (ev.originalEvent.ctrlKey) {
            mult = -1.0; //this is a pinch event turned into a wheel event (or they're just holding down the ctrl)
        }
        if (ev.originalEvent.detail) {
            this.rotationGroup.position.z += mult * scaleFactor * ev.originalEvent.detail / 10;
        } else Iif (ev.originalEvent.wheelDelta) {
            this.rotationGroup.position.z -= mult * scaleFactor * ev.originalEvent.wheelDelta / 400;
        }
        this.rotationGroup.position.z = this.adjustZoomToLimits(this.rotationGroup.position.z);
        this.show();
 
        // Exiting context menu on next mouse event
        this.ui.exitContextMenu();
    };
    /**
     * Return image URI of viewer contents (base64 encoded).
     * @function $3Dmol.GLViewer#pngURI
     *
     */
    public pngURI() {
        return this.getCanvas().toDataURL('image/png');
    };
 
    /**
     * Return a promise that resolves to an animated PNG image URI of 
     viewer contents (base64 encoded) for nframes of viewer changes.
     * @function $3Dmol.GLViewer#apngURI
     * @return {Promise}
     */
    public apngURI(nframes) {
        let viewer = this;
        nframes = nframes ? nframes : 1;
        return new Promise(function (resolve) {
            let framecnt = 0;
            let oldcb = viewer.viewChangeCallback;
            let bufpromise = [];
            let delays = [];
            let lasttime = Date.now();
            viewer.viewChangeCallback = function () {
                delays.push(Date.now() - lasttime);
                lasttime = Date.now();
                bufpromise.push(new Promise(resolve => {
                    viewer.getCanvas().toBlob(function (blob) {
                        blob.arrayBuffer().then(resolve);
                    }, "image/png");
                }));
                framecnt += 1;
                Iif (framecnt == nframes) {
                    viewer.viewChangeCallback = oldcb;
 
                    Promise.all(bufpromise).then((buffers) => {
                        //convert to apng
                        let rgbas = [];
                        //have to convert png to rgba, before creating the apng
                        for (let i = 0; i < buffers.length; i++) {
                            let img = UPNG.decode(buffers[i]);
                            rgbas.push(UPNG.toRGBA8(img)[0]);
                        }
                        let width = viewer.getCanvas().width;
                        let height = viewer.getCanvas().height;
                        let apng = UPNG.encode(rgbas, width, height, 0, delays);
                        let blob = new Blob([apng], { type: 'image/png' });
                        let fr = new FileReader();
                        fr.onload = function (e) {
                            resolve(e.target.result);
                        };
                        fr.readAsDataURL(blob);
                    });
                }
            };
        });
 
    };
 
 
    /**
     * Return underlying canvas element.
     */
    public getCanvas() {
        return this.glDOM.get(0);
    };
 
    /**
     * Return renderer element.
     */
    public getRenderer() {
        return this.renderer;
    };
 
    /**
         * Set the duration of the hover delay
         *
         * @function $3Dmol.GLViewer#setHoverDuration
         * @param {number}
         *            [hoverDuration] - an optional parameter that denotes
         *            the duration of the hover delay (in milliseconds) before the hover action is called
         *
     */
    public setHoverDuration(duration) {
        this.hoverDuration = duration;
    };
 
    public _handleMouseMove(ev) { // touchmove
 
        clearTimeout(this.hoverTimeout);
        var offset = this.canvasOffset();
        var mouseX = ((this.getX(ev) - offset.left) / this.WIDTH) * 2 - 1;
        var mouseY = -((this.getY(ev) - offset.top) / this.HEIGHT) * 2 + 1;
        let self = this;
        // hover timeout
        Iif (this.current_hover !== null) {
            this.handleHoverContinue(mouseX, mouseY);
        }
 
        Iif (this.hoverables.length > 0) {
            this.hoverTimeout = setTimeout(
                function () {
                    self.handleHoverSelection(mouseX, mouseY);
                },
                this.hoverDuration);
        }
 
        ev.preventDefault();
        Iif (!this.scene)
            return;
        Iif (!this.isDragging)
            return;
        var mode = 0;
 
        var x = this.getX(ev);
        var y = this.getY(ev);
        Iif (x === undefined)
            return;
 
        Iif (!this.isInViewer(x, y)) {
            return;
        }
 
 
        var dx = (x - this.mouseStartX) / this.WIDTH;
        var dy = (y - this.mouseStartY) / this.HEIGHT;
        // check for pinch
        if (this.touchDistanceStart != 0 &&
            ev.originalEvent.targetTouches &&
            ev.originalEvent.targetTouches.length == 2) {
            var newdist = this.calcTouchDistance(ev);
            // change to zoom
            mode = 2;
            dy = (newdist - this.touchDistanceStart) * 2 / (this.WIDTH + this.HEIGHT);
        } else Iif (ev.originalEvent.targetTouches &&
            ev.originalEvent.targetTouches.length == 3) {
            // translate
            mode = 1;
        }
        var ratioX = this.renderer.getXRatio();
        var ratioY = this.renderer.getYRatio();
        dx *= ratioX;
        dy *= ratioY;
        var r = Math.sqrt(dx * dx + dy * dy);
        var scaleFactor;
        if (mode == 3 || (this.mouseButton == 3 && ev.ctrlKey)) { // Slab
            this.slabNear = this.cslabNear + dx * 100;
            this.slabFar = this.cslabFar - dy * 100;
        } else if (mode == 2 || this.mouseButton == 3 || ev.shiftKey) { // Zoom
            scaleFactor = (this.CAMERA_Z - this.rotationGroup.position.z) * 0.85;
            Iif (scaleFactor < 80)
                scaleFactor = 80;
            this.rotationGroup.position.z = this.cz + dy * scaleFactor;
            this.rotationGroup.position.z = this.adjustZoomToLimits(this.rotationGroup.position.z);
        } else if (mode == 1 || this.mouseButton == 2 || ev.ctrlKey) { // Translate
            var t = this.screenOffsetToModel(ratioX * (x - this.mouseStartX), ratioY * (y - this.mouseStartY));
            this.modelGroup.position.addVectors(this.currentModelPos, t);
 
        } else Iif ((mode === 0 || this.mouseButton == 1) && r !== 0) { // Rotate
            var rs = Math.sin(r * Math.PI) / r;
            this.dq.x = Math.cos(r * Math.PI);
            this.dq.y = 0;
            this.dq.z = rs * dx;
            this.dq.w = -rs * dy;
            this.rotationGroup.quaternion.set(1, 0, 0, 0);
            this.rotationGroup.quaternion.multiply(this.dq);
            this.rotationGroup.quaternion.multiply(this.cq);
        }
        this.show();
    };
 
    private handleContextMenuSelection(mouseX, mouseY) {
        let intersects = this.targetedObjects(mouseX, mouseY, this.contextMenuEnabledAtoms);
        // console.log('Intersected Objects',mouseX, mouseY, contextMenuEnabledAtoms,  intersects[0]);
        var selected = null;
        Iif (intersects.length) {
            selected = intersects[0].clickable;
            // console.log('intersects and selected', selected);
        }
 
        var offset = this.canvasOffset();
        var x = this.mouseStartX - offset.left;
        var y = this.mouseStartY - offset.top;
        this.ui.openContextMenu(selected, x, y);
    };
 
    public _handleContextMenu(ev) {
        ev.preventDefault();
        var newX = this.getX(ev);
        var newY = this.getY(ev);
 
        if (newX != this.mouseStartX || newY != this.mouseStartY) {
            return;
        } else {
            // console.log('Context Menu Called', ev);
            var x = this.mouseStartX;
            var y = this.mouseStartY;
            var offset = this.canvasOffset();
            var mouseX = ((x - offset.left) / this.WIDTH) * 2 - 1;
            var mouseY = -((y - offset.top) / this.HEIGHT) * 2 + 1;
            this.handleContextMenuSelection(mouseX, mouseY);
        }
 
    };
 
 
    /**
     * Change the viewer's container element
     * Also useful if the original container element was removed from the DOM.
     *
     * @function $3Dmol.GLViewer#setContainer
     *
     * @param {Object | string} element
     *            Either HTML element or string identifier. Defaults to the element used to initialize the viewer.
     
     */
    public setContainer(element) {
        Iif (typeof (element) === "string")
            element = $("#" + element);
        Iif (!element) {
            element = this.container;
        }
        this.initContainer(element);
        return this;
    };
 
    /**
     * Set the background color (default white)
     *
     * @function $3Dmol.GLViewer#setBackgroundColor
     * @param {number}
     *            hex Hexcode specified background color, or standard color spec
     * @param {number}
     *            a Alpha level (default 1.0)
     *
     * @example
     *
     * viewer.setBackgroundColor(0x000000);
     
     
     *
     */
    public setBackgroundColor(hex, a) {
        if (typeof (a) == "undefined") {
            a = 1.0;
        }
        else Iif (a < 0 || a > 1.0) {
            a = 1.0;
        }
        var c = CC.color(hex);
        this.scene.fog.color = c;
        this.bgColor = c.getHex();
        this.renderer.setClearColorHex(c.getHex(), a);
        this.show();
 
        return this;
    };
 
    /**
     * Set view projection scheme.  Either orthographic or perspective.
     * Default is perspective.  Orthographic can also be enabled on viewer creation
     * by setting orthographic to true in the config object.
     *
     * @function $3Dmol.GLViewer#setProjection
     *
     * @example
     viewer.setViewStyle({style:"outline"});
          $.get('data/1fas.pqr', function(data){
              viewer.addModel(data, "pqr");
              $.get("data/1fas.cube",function(volumedata){
                  viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
              });
              viewer.zoomTo();
     
              viewer.setProjection("orthographic");
              viewer.render(callback);
          });
     *
     */
    public setProjection(proj) {
        this.camera.ortho = (proj === "orthographic");
        this.setSlabAndFog();
    };
 
    /**
     * Set global view styles.
     * @function $3Dmol.GLViewer#setViewStyle
     *
     * @example
     *   viewer.setViewStyle({style:"outline"});
          $.get('data/1fas.pqr', function(data){
              viewer.addModel(data, "pqr");
              $.get("data/1fas.cube",function(volumedata){
                  viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
              });
              viewer.zoomTo();
              viewer.render(callback);
          });
     *
     */
    public setViewStyle(parameters) {
        if (parameters.style === "outline") {
            var params: any = {};
            Iif (parameters.color) params.color = CC.color(parameters.color);
            Iif (parameters.width) params.width = parameters.width;
            this.renderer.enableOutline(params);
        } else {
            this.renderer.disableOutline();
        }
        return this;
    };
 
 
    /**
     * Set viewer width
     *
     * @function $3Dmol.GLViewer#setWidth
     * @param {number}
     *            w Width in pixels
     */
    public setWidth(w) {
        this.WIDTH = w || this.WIDTH;
        this.renderer.setSize(this.WIDTH, this.HEIGHT);
        return this;
    };
 
    /**
     * Set viewer height
     *
     * @function $3Dmol.GLViewer#setHeight
     * @param {number}
     *            h Height in pixels
     */
    public setHeight(h) {
        this.HEIGHT = h || this.HEIGHT;
        this.renderer.setSize(this.WIDTH, this.HEIGHT);
        return this;
    };
 
    /**
     * Resize viewer according to containing HTML element's dimensions
     *
     * @function $3Dmol.GLViewer#resize
     */
    public resize() {
        this.WIDTH = this.getWidth();
        this.HEIGHT = this.getHeight();
        let regen = false;
        Iif (this.renderer.isLost() && this.WIDTH > 0 && this.HEIGHT > 0) {
            //create new context
            this.container.children('canvas').remove(); //remove existing
            this.setupRenderer();
            this.initContainer(this.container);
            regen = true;
        }
        if (this.WIDTH == 0 || this.HEIGHT == 0) {
            Iif (this.animated) this._viewer.pauseAnimate();
        } else Iif (this.animated) {
            this._viewer.resumeAnimate();
        }
        this.ASPECT = this.renderer.getAspect(this.WIDTH, this.HEIGHT);
        this.renderer.setSize(this.WIDTH, this.HEIGHT);
        this.camera.aspect = this.ASPECT;
        this.camera.updateProjectionMatrix();
 
        if (regen) { //restored rendere, need to regenerate scene
            let options = this.renderer.supportedExtensions();
            options.regen = true;
            this._viewer.render(null, options);
        } else {
            this.show();
        }
 
        // UI Edition
        this.ui.updateUI();
        return this;
    };
 
 
    /**
     * Return specified model
     *
     * @function $3Dmol.GLViewer#getModel
     * @param {number}
     *            [id=last model id] - Retrieve model with specified id
     * @default Returns last model added to viewer or null if there are no models
     * @return {GLModel}
     *
     * @example // Retrieve reference to first GLModel added var m =
     *    $3Dmol.download("pdb:1UBQ",viewer,{},function(m1){
              $3Dmol.download("pdb:1UBI", viewer,{}, function(m2) {
                viewer.zoomTo();
                m1.setStyle({cartoon: {color:'green'}});
                //could use m2 here as well
                viewer.getModel().setStyle({cartoon: {color:'blue'}});
                viewer.render();
            })
          });
     */
    public getModel(id) {
        Iif (id === undefined) {
            return this.models.length == 0 ? null : this.models[this.models.length - 1];
        }
        Iif (id instanceof GLModel) {
            return id;
        }
        Iif (!(id in this.models)) {
            if (this.models.length == 0)
                return null;
            else
                return this.models[this.models.length - 1]; //get last model if no (or invalid) id specified
        }
        return this.models[id];
    };
 
 
    /**
     * Continuously rotate a scene around the specified axis.
     *
     * Call `$3Dmol.GLViewer.spin(false)` to stop spinning.
     *
     * @function $3Dmol.GLViewer#spin
     * @param {string}
     *            [axis] - Axis ("x", "y", "z", "vx", "vy", or "vz") to rotate around.
     *            Default "y".  View relative (rather than model relative) axes are prefixed with v.
     * @param {number}
     *            [speed] - Speed multiplier for spinning the viewer. 1 is default and a negative
     *             value reverses the direction of the spin.
     *
     */
    public spin(axis, speed) {
        clearInterval(this.spinInterval);
        Iif (typeof axis == 'undefined')
            axis = 'y';
        Iif (typeof axis == "boolean") {
            if (!axis)
                return;
            else
                axis = 'y';
        }
        Iif (typeof speed != 'number') {
            speed = 1;
        }
 
        Iif (Array.isArray(axis)) {
            axis = { x: axis[0], y: axis[1], z: axis[2] };
        }
        //out of bounds check
 
        var viewer = this;
 
        this.spinInterval = setInterval(
            function () {
                Iif (!viewer.getCanvas().isConnected && viewer.renderer.isLost()) {
                    clearInterval(viewer.spinInterval);
                }
                viewer.rotate(1 * speed, axis);
            }, 25);
 
    };
 
    //animate motion between current position and passed position
    // can set some parameters to null
    //if fixed is true will enforce the request animation, otherwise
    //does relative updates
    //positions objects have modelggroup position, rotation group position.z,
    //and rotationgroup quaternion
    //return array includes final position, but not current
    //the returned array includes an animate method
    private animateMotion(duration, fixed, mpos, rz, rot, cam) {
        var interval = 20;
        var steps: any = Math.ceil(duration / interval);
        Iif (steps < 1) steps = 1;
        this.incAnim();
 
        var curr = {
            mpos: this.modelGroup.position.clone(),
            rz: this.rotationGroup.position.z,
            rot: this.rotationGroup.quaternion.clone(),
            cam: this.lookingAt.clone()
        };
 
        if (fixed) { //precompute path and stick to it
            steps = new Array(steps);
            var n = steps.length;
            for (var i = 0; i < n; i++) {
                let frac = (i + 1) / n;
                let next: any = { mpos: curr.mpos, rz: curr.rz, rot: curr.rot };
                Iif (mpos) {
                    next.mpos = mpos.clone().sub(curr.mpos).multiplyScalar(frac).add(curr.mpos);
                }
                Iif (typeof (rz) != 'undefined' && rz != null) {
                    next.rz = curr.rz + frac * (rz - curr.rz);
                }
                Iif (rot) {
                    next.rot = GLViewer.slerp(curr.rot, rot, frac);
                }
                Iif (cam) {
                    next.cam = cam.clone().sub(curr.cam).multiplyScalar(frac).add(curr.cam);
                }
 
                steps[i] = next;
            }
 
            let step = 0;
            let self = this;
            let callback = function () {
                var p = steps[step];
                step += 1;
                Iif (p.mpos) {
                    self.modelGroup.position = p.mpos;
                }
                Iif (p.rz) {
                    self.rotationGroup.position.z = p.rz;
                }
                Iif (p.rot) {
                    self.rotationGroup.quaternion = p.rot;
                }
                Iif (p.cam) {
                    self.camera.lookAt(p.cam);
                }
 
                if (step < steps.length) {
                    setTimeout(callback, interval);
                } else {
                    self.decAnim();
                }
                self.show();
            };
            setTimeout(callback, interval);
 
        } else { //relative update
            var delta: any = {};
            let frac = 1.0 / steps;
            Iif (mpos) {
                delta.mpos = mpos.clone().sub(curr.mpos).multiplyScalar(frac);
            }
            Iif (typeof (rz) != 'undefined' && rz != null) {
                delta.rz = frac * (rz - curr.rz);
            }
            Iif (rot) {
                var next = GLViewer.slerp(curr.rot, rot, frac);
                //comptute step delta rotation
                delta.rot = curr.rot.clone().inverse().multiply(next);
            }
            Iif (cam) {
                delta.cam = cam.clone().sub(curr.cam).multiplyScalar(frac);
            }
            let step = 0.0;
            let self = this;
            let callback = function () {
                step += 1;
                Iif (delta.mpos) {
                    self.modelGroup.position.add(delta.mpos);
                }
                Iif (delta.rz) {
                    self.rotationGroup.position.z += delta.rz;
                }
                Iif (delta.rot) {
                    self.rotationGroup.quaternion.multiply(delta.rot);
                }
                Iif (delta.cam) {
                    self.lookingAt.add(delta.cam);
                    self.camera.lookAt(self.lookingAt);
                }
 
                if (step < steps) {
                    setTimeout(callback, interval);
                } else {
                    self.decAnim();
                }
                self.show();
            };
            setTimeout(callback, interval);
        }
    };
 
    /**
     * Rotate scene by angle degrees around axis
     *
     * @function $3Dmol.GLViewer#rotate
     * @param {number}
     *            [angle] - Angle, in degrees, to rotate by.
     * @param {string}
     *            [axis] - Axis ("x", "y", "z", "vx", "vy", or "vz") to rotate around.
     *            Default "y".  View relative (rather than model relative) axes are prefixed with v.
     *            Axis can also be specified as a vector.
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of the rotation animation. Default 0 (no animation)
     * @param {boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation         *
     * @example     $3Dmol.download('cid:4000', viewer, {}, function() {
    viewer.setStyle({stick:{}});
    viewer.zoomTo();
    viewer.rotate(90,'y',1);
    viewer.render(callback);
    });
     
     *
     */
    public rotate(angle, axis: any = "y", animationDuration = 0, fixedPath?) {
 
        if (axis == "x") {
            axis = { x: 1, y: 0, z: 0 };
        } else if (axis == "y") {
            axis = { x: 0, y: 1, z: 0 };
        } else Iif (axis == "z") {
            axis = { x: 0, y: 0, z: 1 };
        }
 
        //support rotating with respect to view axis, not model
        if (axis == "vx") {
            axis = { vx: 1, vy: 0, vz: 0 };
        } else if (axis == "vy") {
            axis = { vx: 0, vy: 1, vz: 0 };
        } else Iif (axis == "vz") {
            axis = { vx: 0, vy: 0, vz: 1 };
        }
 
        Iif (typeof (axis.vx) !== 'undefined') {
            var vaxis = new Vector3(axis.vx, axis.vy, axis.vz);
            vaxis.applyQuaternion(this.rotationGroup.quaternion);
            axis = { x: vaxis.x, y: vaxis.y, z: vaxis.z };
        }
 
        var qFromAngle = function (rangle) {
            var s = Math.sin(rangle / 2.0);
            var c = Math.cos(rangle / 2.0);
            var i = 0, j = 0, k = 0;
 
            i = axis.x * s;
            j = axis.y * s;
            k = axis.z * s;
 
            return new Quaternion(i, j, k, c).normalize();
        };
 
        var rangle = Math.PI * angle / 180.0;
        var q = qFromAngle(rangle);
 
        if (animationDuration) {
            var final = new Quaternion().copy(this.rotationGroup.quaternion).multiply(q);//final
            this.animateMotion(animationDuration, fixedPath,
                this.modelGroup.position,
                this.rotationGroup.position.z,
                final,
                this.lookingAt);
        } else { //not animated
            this.rotationGroup.quaternion.multiply(q);
            this.show();
        }
        return this;
 
    };
 
    public surfacesFinished() {
        for (var key in this.surfaces) {
            Iif (!this.surfaces[key][0].done) {
                return false;
            }
        }
        return true;
    };
 
    /** Returns an array representing the current viewpoint.
     * Translation, zoom, and rotation quaternion.
     * @function $3Dmol.GLViewer#getView
     * @returns {Array.<number>} [ pos.x, pos.y, pos.z, rotationGroup.position.z, q.x, q.y, q.z, q.w ]
     *  */
    public getView() {
        Iif (!this.modelGroup)
            return [0, 0, 0, 0, 0, 0, 0, 1];
        var pos = this.modelGroup.position;
        var q = this.rotationGroup.quaternion;
        return [pos.x, pos.y, pos.z, this.rotationGroup.position.z, q.x, q.y,
        q.z, q.w];
    };
 
    /** Sets the view to the specified translation, zoom, and rotation.
     *
     * @function $3Dmol.GLViewer#setView
     * @param {Array.<number>} arg Array formatted identically to the return value of getView */
    public setView(arg, nolink?) {
 
        Iif (arg === undefined ||
            !(arg instanceof Array || arg.length !== 8))
            return this;
 
        Iif (!this.modelGroup || !this.rotationGroup)
            return this;
        this.modelGroup.position.x = arg[0];
        this.modelGroup.position.y = arg[1];
        this.modelGroup.position.z = arg[2];
        this.rotationGroup.position.z = arg[3];
        this.rotationGroup.quaternion.x = arg[4];
        this.rotationGroup.quaternion.y = arg[5];
        this.rotationGroup.quaternion.z = arg[6];
        this.rotationGroup.quaternion.w = arg[7];
        Iif (typeof (arg[8]) != "undefined") {
            this.rotationGroup.position.x = arg[8];
            this.rotationGroup.position.y = arg[9];
        }
 
        this.show(nolink);
        return this;
 
    };
 
    // apply styles, models, etc in viewer
    /**
     * Render current state of viewer, after
     * adding/removing models, applying styles, etc.
     *
     * @function $3Dmol.GLViewer#render
     */
    public render(callback?, exts?) {
        this.renderer.setViewport();
        this.updateClickables(); //must render for clickable styles to take effect
        var view = this.getView();
 
        Iif (this.stateChangeCallback) {
            //todo: have ability to only send delta updates
            this.stateChangeCallback(this.getInternalState());
        }
 
        var i, n;
        Iif (!exts) exts = this.renderer.supportedExtensions();
        for (i = 0; i < this.models.length; i++) {
            Iif (this.models[i]) {
                this.models[i].globj(this.modelGroup, exts);
            }
        }
 
        for (i = 0; i < this.shapes.length; i++) {
            Iif (this.shapes[i]) { //exists
                if ((typeof (this.shapes[i].frame) === 'undefined' || this.viewer_frame < 0 ||
                    this.shapes[i].frame < 0 || this.shapes[i].frame == this.viewer_frame)) {
                    this.shapes[i].globj(this.modelGroup, exts);
                } else { //should not be displayed in current frame
                    this.shapes[i].removegl(this.modelGroup);
                }
            }
        }
 
        for (i = 0; i < this.labels.length; i++) {
            Iif (this.labels[i] && typeof (this.labels[i].frame) != 'undefined' && this.labels[i].frame >= 0) { //exists and has frame specifier
                this.modelGroup.remove(this.labels[i].sprite);
                Iif (this.viewer_frame < 0 || this.labels[i].frame == this.viewer_frame) {
                    this.modelGroup.add(this.labels[i].sprite);
                }
            }
        }
 
        for (i in this.surfaces) { // this is an object with possible holes
            Iif (!this.surfaces.hasOwnProperty(i)) continue;
            var surfArr = this.surfaces[i];
            for (n = 0; n < surfArr.length; n++) {
                Iif (surfArr.hasOwnProperty(n)) {
                    var geo = surfArr[n].geo;
                    // async surface generation can cause
                    // the geometry to be webgl initialized before it is fully
                    // formed; force various recalculations until full surface
                    // is
                    // available
                    Iif (!surfArr[n].finished || exts.regen) {
                        geo.verticesNeedUpdate = true;
                        geo.elementsNeedUpdate = true;
                        geo.normalsNeedUpdate = true;
                        geo.colorsNeedUpdate = true;
                        geo.buffersNeedUpdate = true;
                        geo.boundingSphere = null;
 
                        Iif (surfArr[n].done)
                            surfArr[n].finished = true;
 
                        // remove partially rendered surface
                        Iif (surfArr[n].lastGL)
                            this.modelGroup.remove(surfArr[n].lastGL);
 
                        // create new surface
                        var smesh = null;
 
                        if (surfArr[n].mat instanceof LineBasicMaterial) {
                            //special case line meshes
                            smesh = new Line(geo, surfArr[n].mat);
                        }
                        else {
                            smesh = new Mesh(geo, surfArr[n].mat);
                        }
                        if (surfArr[n].mat.transparent && surfArr[n].mat.opacity == 0) {
                            //don't bother with hidden surfaces
                            smesh.visible = false;
                        } else {
                            smesh.visible = true;
                        }
                        if (surfArr[n].symmetries.length > 1 ||
                            (surfArr[n].symmetries.length == 1 &&
                                !(surfArr[n].symmetries[n].isIdentity()))) {
                            var j;
                            var tmeshes = new Object3D(); //transformed meshes
                            for (j = 0; j < surfArr[n].symmetries.length; j++) {
                                var tmesh = smesh.clone();
                                tmesh.matrix = surfArr[n].symmetries[j];
                                tmesh.matrixAutoUpdate = false;
                                tmeshes.add(tmesh);
                            }
                            surfArr[n].lastGL = tmeshes;
                            this.modelGroup.add(tmeshes);
                        }
                        else {
                            surfArr[n].lastGL = smesh;
                            this.modelGroup.add(smesh);
                        }
                    } // else final surface already there
                }
            }
        }
 
        this.setView(view); // Calls show() => renderer render
        Iif (typeof callback === 'function') {
            callback(this);
        }
        return this;
    };
 
    /** @param {AtomSelectionSpec} sel
     * @return list of models specified by sel
     */
    private getModelList(sel) {
        var ms = [];
        if (typeof sel === 'undefined' || typeof sel.model === "undefined") {
            for (let i = 0; i < this.models.length; i++) {
                Iif (this.models[i])
                    ms.push(this.models[i]);
            }
        } else { // specific to some models
            ms = sel.model;
            Iif (!Array.isArray(ms))
                ms = [ms];
 
            for (let i = 0; i < ms.length; i++) {
                //allow referencing models by order of creation
                Iif (typeof ms[i] === 'number') {
                    var index = ms[i];
                    //support python backward indexing
                    Iif (index < 0) index += this.models.length;
                    ms[i] = this.models[index];
                }
            }
        }
 
        return ms;
    }
    /**
     *
     * @param {AtomSelectionSpec}
     *            sel
     * @return {AtomSpec[]}
     */
    private getAtomsFromSel(sel) {
        var atoms = [];
        Iif (typeof (sel) === "undefined")
            sel = {};
 
        var ms = this.getModelList(sel);
 
        for (var i = 0; i < ms.length; i++) {
            atoms = atoms.concat(ms[i].selectedAtoms(sel));
        }
 
        return atoms;
    }
 
    /**
     *
     * @param {AtomSpec}
     *            atom
     * @param {AtomSpec}
     *            sel
     * @return {boolean}
     */
    private atomIsSelected(atom, sel) {
        Iif (typeof (sel) === "undefined")
            sel = {};
 
        var ms = this.getModelList(sel);
 
        for (var i = 0; i < ms.length; i++) {
            Iif (ms[i].atomIsSelected(atom, sel))
                return true;
        }
 
        return false;
    }
 
 
    /** return list of atoms selected by sel
     *
     * @function $3Dmol.GLViewer#selectedAtoms
     * @param {AtomSelectionSpec} sel
     * @return {Array.<Object>}
     */
    public selectedAtoms(sel) {
        return this.getAtomsFromSel(sel);
    };
 
    /**
    * Returns valid values for the specified attribute in the given selection
    * @function $3Dmol.GlViewer#getUniqueValues
    * @param {string} attribute
    * @param {AtomSelectionSpec} sel
    * @return {Array.<Object>}
    *
    */
    public getUniqueValues(attribute, sel) {
        Iif (typeof (sel) === "undefined")
            sel = {};
        var atoms = this.getAtomsFromSel(sel);
        var values = {};
 
        for (var atom in atoms) {
            Iif (atoms[atom].hasOwnProperty(attribute)) {
                var value = atoms[atom][attribute];
                values[value] = true;
            }
        }
 
        return Object.keys(values);
    };
 
    /**
     * Return pdb output of selected atoms (if atoms from pdb input)
     *
     * @function $3Dmol.GLViewer#pdbData
     * @param {Object=} [sel] - Selection specification specifying model and atom properties to select.  Default: all atoms in viewer
     * @return {string} PDB string of selected atoms
     */
    public pdbData(sel) {
        var atoms = this.getAtomsFromSel(sel);
        var ret = "";
        for (var i = 0, n = atoms.length; i < n; ++i) {
            ret += atoms[i].pdbline + "\n";
        }
        return ret;
    };
 
 
    /**
     * Zoom current view by a constant factor
     *
     * @function $3Dmol.GLViewer#zoom
     * @param {number}
     *            [factor] - Magnification factor. Values greater than 1
     *            will zoom in, less than one will zoom out. Default 2.
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of a zoom animation
     * @param {Boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation
     * @example
    $.get('data/4csv.pdb', function(data) {
    viewer.addModel(data,'pdb');
    viewer.setStyle({cartoon:{},stick:{}});
    viewer.zoomTo()
    viewer.zoom(2,1000);
    viewer.render();
    });
     
         */
    public zoom(factor, animationDuration, fixedPath) {
        factor = factor || 2;
        animationDuration = animationDuration !== undefined ? animationDuration : 0;
        var scale = (this.CAMERA_Z - this.rotationGroup.position.z) / factor;
        var final_z = this.CAMERA_Z - scale;
 
        if (animationDuration > 0) {
            this.animateMotion(animationDuration, fixedPath,
                this.modelGroup.position,
                this.adjustZoomToLimits(final_z),
                this.rotationGroup.quaternion,
                this.lookingAt);
        } else { //no animation
            this.rotationGroup.position.z = this.adjustZoomToLimits(final_z);
            this.show();
        }
        return this;
    };
 
    /**
     * Translate current view by x,y screen coordinates
     * This pans the camera rather than translating the model.
     *
     * @function $3Dmol.GLViewer#translate
     * @param {number} x Relative change in view coordinates of camera
     * @param {number} y Relative change in view coordinates of camera
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of a zoom animation
     * @param {Boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation         *
     * @example     $.get('data/4csv.pdb', function(data) {
    viewer.addModel(data,'pdb');
    viewer.setStyle({cartoon:{},stick:{}});
    viewer.zoomTo();
    viewer.translate(200,50);
    viewer.rotate(90,'z');
    viewer.render(callback);
    });
     */
    public translate(x, y, animationDuration, fixedPath) {
        animationDuration = animationDuration !== undefined ? animationDuration : 0;
        var dx = x / this.WIDTH;
        var dy = y / this.HEIGHT;
        var v = new Vector3(0, 0, -this.CAMERA_Z);
 
        this.projector.projectVector(v, this.camera);
        v.x -= dx;
        v.y -= dy;
        this.projector.unprojectVector(v, this.camera);
        v.z = 0;
 
        var final_position = this.lookingAt.clone().add(v);
        if (animationDuration > 0) {
            this.animateMotion(animationDuration, fixedPath,
                this.modelGroup.position,
                this.rotationGroup.position.z,
                this.rotationGroup.quaternion,
                final_position);
        } else { //no animation
            this.lookingAt = final_position;
            this.camera.lookAt(this.lookingAt);
            this.show();
        }
        return this;
    };
 
    /**
     * Translate current models by x,y screen coordinates
     * This translates the models relative to the current view. It does
     * not change the center of rotation.
     *
     * @function $3Dmol.GLViewer#translateScene
     * @param {number} x Relative change in x screen coordinate
     * @param {number} y Relative change in y screen coordinate
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of a zoom animation
     * @param {Boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation         *
     * @example     $.get('data/4csv.pdb', function(data) {
    viewer.addModel(data,'pdb');
    viewer.setStyle({cartoon:{},stick:{}});
    viewer.zoomTo();
    viewer.translateScene(200,50);
    viewer.rotate(90,'z'); // will no longer be around model center
    viewer.render(callback);
    });
     */
    public translateScene(x, y, animationDuration, fixedPath) {
        animationDuration = animationDuration !== undefined ? animationDuration : 0;
 
        var t = this.screenOffsetToModel(x, y);
        var final_position = this.modelGroup.position.clone().add(t);
 
        if (animationDuration > 0) {
            this.animateMotion(animationDuration, fixedPath,
                this.modelGroup.position,
                this.rotationGroup.position.z,
                this.rotationGroup.quaternion,
                this.lookingAt);
        } else { //no animation
            this.modelGroup.position = final_position;
            this.show();
        }
        return this;
    };
 
    /**
     * Adjust slab to fully enclose selection (default everything).
     *
     * @function $3Dmol.GLViewer#fitSlab
     * @param {Object}
     *            [sel] - Selection specification specifying model and atom
     *            properties to select. Default: all atoms in viewer
     */
    public fitSlab(sel) {
        sel = sel || {};
        var atoms = this.getAtomsFromSel(sel);
        var tmp = getExtent(atoms);
 
        // fit to bounding box
        var x = tmp[1][0] - tmp[0][0],
            y = tmp[1][1] - tmp[0][1],
            z = tmp[1][2] - tmp[0][2];
 
        var maxD = Math.sqrt(x * x + y * y + z * z);
        Iif (maxD < 5)
            maxD = 5;
 
        // use full bounding box for slab/fog
        this.slabNear = -maxD / 1.9;
        this.slabFar = maxD / 2;
 
        return this;
    };
 
    /**
     * Re-center the viewer around the provided selection (unlike zoomTo, does not zoom).
     *
     * @function $3Dmol.GLViewer#center
     * @param {Object}
     *            [sel] - Selection specification specifying model and atom
     *            properties to select. Default: all atoms in viewer
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of a zoom animation
     * @param {Boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation         *
     * @example // if the user were to pass the animationDuration value to
     *           // the function like so viewer.zoomTo({resn:'STI'},1000);
     *         //   the program would center on resn 'STI' over the course
     *         //   of 1 second(1000 milleseconds).
     *  // Reposition to centroid of all atoms of all models in this
     * //viewer glviewer.center();
    $.get('data/4csv.pdb', function(data) {
    viewer.addModel(data,'pdb');
    viewer.setStyle({cartoon:{},stick:{}});
    viewer.center();
    viewer.render(callback);
    });
     */
    public center(sel, animationDuration, fixedPath) {
        animationDuration = animationDuration !== undefined ? animationDuration : 0;
        var allatoms, alltmp;
        sel = sel || {};
        var atoms = this.getAtomsFromSel(sel);
        var tmp = getExtent(atoms);
 
        if (isEmptyObject(sel)) {
            //include shapes when zooming to full scene
            //TODO: figure out a good way to specify shapes as part of a selection
            this.shapes.forEach((shape) => {
                Iif (shape && shape.boundingSphere && shape.boundingSphere.center) {
                    var c = shape.boundingSphere.center;
                    var r = shape.boundingSphere.radius;
                    if (r > 0) {
                        //make sure full shape is visible
                        atoms.push(new Vector3(c.x + r, c.y, c.z));
                        atoms.push(new Vector3(c.x - r, c.y, c.z));
                        atoms.push(new Vector3(c.x, c.y + r, c.z));
                        atoms.push(new Vector3(c.x, c.y - r, c.z));
                        atoms.push(new Vector3(c.x, c.y, c.z + r));
                        atoms.push(new Vector3(c.x, c.y, c.z - r));
                    } else {
                        atoms.push(c);
                    }
                }
            });
            tmp = getExtent(atoms);
            allatoms = atoms;
            alltmp = tmp;
 
        }
        else {
            allatoms = this.getAtomsFromSel({});
            alltmp = getExtent(allatoms);
        }
 
        // use selection for center
        var center = new Vector3(tmp[2][0], tmp[2][1], tmp[2][2]);
 
        // but all for bounding box
        var x = alltmp[1][0] - alltmp[0][0], y = alltmp[1][1] -
            alltmp[0][1], z = alltmp[1][2] - alltmp[0][2];
 
        var maxD = Math.sqrt(x * x + y * y + z * z);
        Iif (maxD < 5)
            maxD = 5;
 
        // use full bounding box for slab/fog
        this.slabNear = -maxD / 1.9;
        this.slabFar = maxD / 2;
 
        // for zoom, use selection box
        x = tmp[1][0] - tmp[0][0];
        y = tmp[1][1] - tmp[0][1];
        z = tmp[1][2] - tmp[0][2];
        maxD = Math.sqrt(x * x + y * y + z * z);
        Iif (maxD < 5)
            maxD = 5;
 
        //find the farthest atom from center to get max distance needed for view
        var maxDsq = 25;
        for (var i = 0; i < atoms.length; i++) {
            Iif (atoms[i]) {
                var dsq = center.distanceToSquared(atoms[i]);
                Iif (dsq > maxDsq)
                    maxDsq = dsq;
            }
        }
 
        maxD = Math.sqrt(maxDsq) * 2;
        var finalpos = center.clone().multiplyScalar(-1);
        if (animationDuration > 0) {
            this.animateMotion(animationDuration, fixedPath,
                finalpos,
                this.rotationGroup.position.z,
                this.rotationGroup.quaternion,
                this.lookingAt);
        } else { //no animation
            this.modelGroup.position = finalpos;
            this.show();
        }
        return this;
    };
 
    /**
     * Zoom to center of atom selection.  The slab will be set appropriately for
     * the selection, unless an empty selection is provided, in which case there will be no slab.
     *
     * @function $3Dmol.GLViewer#zoomTo
     * @param {Object}
     *            [sel] - Selection specification specifying model and atom
     *            properties to select. Default: all atoms in viewer
     * @param {number}
     *            [animationDuration] - an optional parameter that denotes
     *            the duration of a zoom animation
     * @param {Boolean} [fixedPath] - if true animation is constrained to
     *      requested motion, overriding updates that happen during the animation         *
      * @example
     
     
          $.get('data/1fas.pqr', function(data){
              viewer.addModel(data, "pqr");
              $.get("data/1fas.cube",function(volumedata){
                  viewer.addSurface($3Dmol.SurfaceType.VDW, {
                      opacity:0.85,
                      voldata: new $3Dmol.VolumeData(volumedata, "cube"),
                      volscheme: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'charge'))
                  },{});
     
              viewer.render();
              });
              viewer.zoomTo();
            });
     */
    public zoomTo(sel, animationDuration, fixedPath) {
        animationDuration = animationDuration !== undefined ? animationDuration : 0;
        sel = sel || {};
        let atoms = this.getAtomsFromSel(sel);
        let atombox = getExtent(atoms);
        let allbox = atombox;
 
        if (isEmptyObject(sel)) {
            //include shapes when zooming to full scene
            //TODO: figure out a good way to specify shapes as part of a selection
            let natoms = atoms && atoms.length;
            this.shapes.forEach((shape) => {
                Iif (shape && shape.boundingSphere) {
                    if (shape.boundingSphere.box) {
                        let box = shape.boundingSphere.box;
                        atoms.push(new Vector3(box.min.x, box.min.y, box.min.z));
                        atoms.push(new Vector3(box.max.x, box.max.y, box.max.z));
                    } else Iif (shape.boundingSphere.center) {
                        var c = shape.boundingSphere.center;
                        var r = shape.boundingSphere.radius;
                        if (r > 0) {
                            //make sure full shape is visible
                            atoms.push(new Vector3(c.x + r, c.y, c.z));
                            atoms.push(new Vector3(c.x - r, c.y, c.z));
                            atoms.push(new Vector3(c.x, c.y + r, c.z));
                            atoms.push(new Vector3(c.x, c.y - r, c.z));
                            atoms.push(new Vector3(c.x, c.y, c.z + r));
                            atoms.push(new Vector3(c.x, c.y, c.z - r));
                        } else {
                            atoms.push(c);
                        }
                    }
                }
            });
            allbox = getExtent(atoms);
            Iif (!natoms) { //if no atoms, use shapes for center
                for (let i = 0; i < 3; i++) { //center of bounding box
                    atombox[2][i] = (allbox[0][i] + allbox[1][i]) / 2;
                }
            }
        } else { //include all atoms in slab calculation
            let allatoms = this.getAtomsFromSel({});
            allbox = getExtent(allatoms);
        }
 
        // use selection for center
        var center = new Vector3(atombox[2][0], atombox[2][1], atombox[2][2]);
 
        // but all for bounding box
        var x = allbox[1][0] - allbox[0][0], y = allbox[1][1]
            - allbox[0][1], z = allbox[1][2] - allbox[0][2];
 
        var maxD = Math.sqrt(x * x + y * y + z * z);
        Iif (maxD < 5)
            maxD = 5;
 
        // use full bounding box for slab/fog
        this.slabNear = -maxD / 1.9;
        this.slabFar = maxD / 2;
 
        //if we are selecting everything, have ver permissive slab
        //can't do "infinity" size since this will break orthographic
        Iif (Object.keys(sel).length === 0) {
            this.slabNear = Math.min(-maxD * 2, -50);
            this.slabFar = Math.max(maxD * 2, 50);
        }
 
        // keep at least this much space in view
        var MAXD = this.config.minimumZoomToDistance || 5;
        // for zoom, use selection box
        x = atombox[1][0] - atombox[0][0];
        y = atombox[1][1] - atombox[0][1];
        z = atombox[1][2] - atombox[0][2];
        maxD = Math.sqrt(x * x + y * y + z * z);
        Iif (maxD < MAXD)
            maxD = MAXD;
 
        //find the farthest atom from center to get max distance needed for view
        var maxDsq = MAXD * MAXD;
        for (var i = 0; i < atoms.length; i++) {
            Iif (atoms[i]) {
                var dsq = center.distanceToSquared(atoms[i]);
                Iif (dsq > maxDsq)
                    maxDsq = dsq;
            }
        }
 
        maxD = Math.sqrt(maxDsq) * 2;
        var finalpos = center.clone().multiplyScalar(-1);
        var finalz = -(maxD * 0.5
            / Math.tan(Math.PI / 180.0 * this.camera.fov / 2) - this.CAMERA_Z);
 
        finalz = this.adjustZoomToLimits(finalz);
        if (animationDuration > 0) {
            this.animateMotion(animationDuration, fixedPath,
                finalpos,
                finalz,
                this.rotationGroup.quaternion,
                this.lookingAt);
        } else {
            this.modelGroup.position = finalpos;
            this.rotationGroup.position.z = finalz;
            this.show();
        }
        return this;
 
    };
 
    /**
     * Set slab of view (contents outside of slab are clipped).
     * Must call render to update.
     *
     * @function $3Dmol.GLViewer#setSlab
     * @param {number} near near clipping plane distance
     * @param {number} far far clipping plane distance
     */
    public setSlab(near, far) {
        this.slabNear = near;
        this.slabFar = far;
    };
 
    /**
     * Get slab of view (contents outside of slab are clipped).
     *
     * @function $3Dmol.GLViewer#getSlab
     * @return {Object}
     *      @property {number} near - near clipping plane distance
     *      @property {number} far - far clipping plane distance
     */
    public getSlab() {
        return { near: this.slabNear, far: this.slabFar };
    };
 
    /**
     * Add label to viewer
     *
     * @function $3Dmol.GLViewer#addLabel
     * @param {string}
     *            text - Label text
     * @param {LabelSpec}
     *            options - Label style specification
      @param {AtomSelection}
     *            sel - Set position of label to center of this selection
     * @param {boolean} noshow - if true, do not immediately display label - when adding multiple labels this is more efficient
     * @return {$3Dmol.Label}
     *
     * @example
     *  $3Dmol.download("pdb:2EJ0",viewer,{},function(){
     
              viewer.addLabel("Aromatic", {position: {x:-6.89, y:0.75, z:0.35}, backgroundColor: 0x800080, backgroundOpacity: 0.8});
              viewer.addLabel("Label",{font:'sans-serif',fontSize:18,fontColor:'white',fontOpacity:1,borderThickness:1.0,
                                       borderColor:'red',borderOpacity:0.5,backgroundColor:'black',backgroundOpacity:0.5,
                                       position:{x:50.0,y:0.0,z:0.0},inFront:true,showBackground:true});
              viewer.setStyle({chain:'A'},{cross:{hidden:true}});
              viewer.setStyle({chain:'B'},{cross:{hidden:false,
                                                  linewidth:1.0,
                                                  colorscheme:'greenCarbon'}});
              viewer.setStyle({chain:'C'},{cross:{hidden:false,
                                                  linewidth:1.0,
                                                  radius:0.5}});
              viewer.setStyle({chain:'D'},{cross:{hidden:false,
                                                  linewidth:10.0}});
              viewer.setStyle({chain:'E'},{cross:{hidden:false,
                                                  linewidth:1.0,
                                                  color:'black'}});
     
              viewer.render();
     
     
            });
     
     */
    public addLabel(text, options, sel?, noshow?) {
        options = options || {};
        Iif (sel) {
            var extent = getExtent(this.getAtomsFromSel(sel));
            options.position = { x: extent[2][0], y: extent[2][1], z: extent[2][2] };
        }
        var label = new Label(text, options);
        label.setContext();
        this.modelGroup.add(label.sprite);
        Iif (options.fixed)
            this.fixed_labels.push(this.labels.length);
        this.labels.push(label);
 
        Iif (!noshow) this.show();
        return label;
    };
 
 
 
    /** Add residue labels.  This will generate one label per a
     * residue within the selected atoms.  The label will be at the
     * centroid of the atoms and styled according to the passed style.
     * The label text will be [resn][resi]
     *
     * @function $3Dmol.GLViewer#addResLabels
     * @param {Object} sel
     * @param {Object} style
     * @param {boolean} byframe - if true, create labels for every individual frame, not just current
     *
     * * @example
         $3Dmol.download("mmtf:2ll5",viewer,{},function(){
              viewer.setStyle({stick:{radius:0.15},cartoon:{}});
              viewer.addResLabels({hetflag:false}, {font: 'Arial', fontColor:'black',showBackground:false, screenOffset: {x:0,y:0}});
              viewer.zoomTo();
              viewer.render();
            });
     */
    public addResLabels(sel, style, byframe) {
        let start = this.labels.length;
        this.applyToModels("addResLabels", sel, this, style, byframe);
        this.show();
        return this.labels.slice(start);
    };
 
    /** Add property labels.  This will generate one label per a selected
     * atom at the atom's coordinates with the property value as the label text.
     *
     * @function $3Dmol.GLViewer#addPropertyLabels
     * @param {string} prop - property name
     * @param {Object} sel
     * @param {Object} style
     *
     * * @example
         $3Dmol.download("cid:5291",viewer,{},function(){
              viewer.setStyle({stick: {radius:.2}});
              viewer.addPropertyLabels("index",{not:{elem:'H'}}, {fontColor:'black',font: 'sans-serif', fontSize: 28, showBackground:false,alignment:'center'});
              viewer.zoomTo();
              viewer.render();
            });
     */
    public addPropertyLabels(prop, sel, style) {
        this.applyToModels("addPropertyLabels", prop, sel, this, style);
        this.show();
        return this;
    };
 
    /**
     * Remove label from viewer
     *
     * @function $3Dmol.GLViewer#removeLabel
     * @param {$3Dmol.Label}
     *            label - $3Dmol label
     *
     * @example // Remove labels created in
     $3Dmol.download("pdb:2EJ0",viewer,{},function(){
              var toremove = viewer.addLabel("Aromatic", {position: {x:-6.89, y:0.75, z:0.35}, backgroundColor: 0x800080, backgroundOpacity: 0.8});
              viewer.addLabel("Label",{font:'sans-serif',fontSize:18,fontColor:'white',fontOpacity:1,borderThickness:1.0,
                                       borderColor:'red',borderOpacity:0.5,backgroundColor:'black',backgroundOpacity:0.5,
                                       position:{x:50.0,y:0.0,z:0.0},inFront:true,showBackground:true});
              viewer.removeLabel(toremove);
              viewer.render();
     
     
            });
     
     */
    public removeLabel(label) {
        //todo: don't do the linear search
        for (var i = 0; i < this.labels.length; i++) {
            Iif (this.labels[i] == label) {
                this.labels.splice(i, 1);
                label.dispose();
                this.modelGroup.remove(label.sprite);
                break;
            }
        }
        this.show();
        return this;
    };
 
    /**
     * Remove all labels from viewer
     *
     * @function $3Dmol.GLViewer#removeAllLabels
     *         @example
    $3Dmol.download("pdb:1ubq",viewer,{},function(){
     
           viewer.addResLabels();
           viewer.setStyle({},{stick:{}});
           viewer.render( ); //show labels
     
           viewer.removeAllLabels();
           viewer.render(); //hide labels
    });
     */
    public removeAllLabels() {
        for (var i = 0; i < this.labels.length; i++) {
            Iif (this.labels[i] && this.labels[i].sprite) {
                this.modelGroup.remove(this.labels[i].sprite);
            }
        }
        this.labels.splice(0, this.labels.length); //don't overwrite in case linked
        this.show();
        return this;
    };
 
    // Modify label style
    /**
     * Modify existing label's style
     *
     * @function $3Dmol.GLViewer#setLabelStyle
     * @param {$3Dmol.Label}
     *            label - $3Dmol label
     * @param {Object}
     *            stylespec - Label style specification
     * @return {$3Dmol.Label}
     */
    public setLabelStyle(label, stylespec) {
        this.modelGroup.remove(label.sprite);
        label.dispose();
        label.stylespec = stylespec;
        label.setContext();
        this.modelGroup.add(label.sprite);
        this.show();
        return label;
 
    };
 
    // Change label text
    /**
     * Modify existing label's text
     *
     * @function $3Dmol.GLViewer#setLabelText
     * @param {$3Dmol.Label}
     *            label - $3Dmol label
     * @param {String}
     *            text - Label text
     * @return {$3Dmol.Label}
     */
    public setLabelText(label, text) {
        this.modelGroup.remove(label.sprite);
        label.dispose();
        label.text = text;
        label.setContext();
        this.modelGroup.add(label.sprite);
        this.show();
        return label;
 
    };
 
    /**
     * Add shape object to viewer
     * @see {@link GLShape}
     *
     * @function $3Dmol.GLViewer#addShape
     * @param {ShapeSpec} shapeSpec - style specification for label
     * @return {GLShape}
     */
    public addShape(shapeSpec) {
        shapeSpec = shapeSpec || {};
        var shape = new GLShape(shapeSpec);
        shape.shapePosition = this.shapes.length;
        this.shapes.push(shape);
 
        return shape;
 
    };
 
    /**
     * Remove shape object from viewer
     *
     * @function $3Dmol.GLViewer#removeShape
     * @param {GLShape} shape - Reference to shape object to remove
     */
    public removeShape(shape) {
        Iif (!shape)
            return this;
        shape.removegl(this.modelGroup);
        delete this.shapes[shape.shapePosition];
        // clear off back of model array
        while (this.shapes.length > 0
            && typeof (this.shapes[this.shapes.length - 1]) === "undefined")
            this.shapes.pop();
        return this;
    };
 
    /**
     * Remove all shape objects from viewer
     * @function $3Dmol.GLViewer#removeAllShapes
     */
    public removeAllShapes() {
        for (var i = 0; i < this.shapes.length; i++) {
            var shape = this.shapes[i];
            Iif (shape) shape.removegl(this.modelGroup);
        }
        this.shapes.splice(0, this.shapes.length);
        return this;
    };
 
    //gets the center of the selection
    private getSelectionCenter(spec) {
        Iif (spec.hasOwnProperty("x") && spec.hasOwnProperty("y") && spec.hasOwnProperty("z"))
            return spec;
        var atoms = this.getAtomsFromSel(spec);
        Iif (atoms.length == 0)
            return { x: 0, y: 0, z: 0 };
 
        var extent = getExtent(atoms);
        return { x: extent[0][0] + (extent[1][0] - extent[0][0]) / 2, y: extent[0][1] + (extent[1][1] - extent[0][1]) / 2, z: extent[0][2] + (extent[1][2] - extent[0][2]) / 2 };
    };
 
    /**
     * Create and add sphere shape. This method provides a shorthand
     * way to create a spherical shape object
     *
     * @function $3Dmol.GLViewer#addSphere
     * @param {SphereShapeSpec} spec - Sphere shape style specification
     * @return {GLShape}
     @example
     
     viewer.addSphere({center:{x:0,y:0,z:0},radius:10.0,color:'red'});
     
     viewer.render();
     */
    public addSphere(spec) {
        spec = spec || {};
 
        spec.center = this.getSelectionCenter(spec.center);
 
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addSphere(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
        return s;
    };
 
    /**
     * Create and add box shape. This method provides a shorthand
     * way to create a box shape object
     *
     * @function $3Dmol.GLViewer#addBox
     * @param {BoxSpec} spec - Box shape style specification
     * @return {GLShape}
     @example
     
     viewer.addLine({color:'red',start:{x:0,y:0,z:0},end:{x:5,y:0,z:0}});
     viewer.addLine({color:'blue',start:{x:0,y:0,z:0},end:{x:0,y:5,z:0}});
     viewer.addLine({color:'green',start:{x:0,y:0,z:0},end:{x:0,y:0,z:5}});
     
     viewer.addBox({center:{x:0,y:0,z:0},dimensions: {w:3,h:4,d:2},color:'magenta'});
     viewer.zoomTo();
     viewer.rotate(45, {x:1,y:1,z:1});
     viewer.render();
     */
    public addBox(spec) {
        spec = spec || {};
 
        Iif (spec.corner != undefined) {
            spec.corner = this.getSelectionCenter(spec.corner);
        }
        Iif (spec.center != undefined) {
            spec.center = this.getSelectionCenter(spec.center);
        }
 
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addBox(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
    /**
     * Create and add arrow shape
     *
     * @function $3Dmol.GLViewer#addArrow
     * @param {ArrowSpec} spec - Style specification
     * @return {GLShape}
     @example
    $3Dmol.download("pdb:4DM7",viewer,{},function(){
     
              viewer.setBackgroundColor(0xffffffff);
              viewer.addArrow({
                  start: {x:-10.0, y:0.0, z:0.0},
                  end: {x:0.0, y:-10.0, z:0.0},
                  radius: 1.0,
                  radiusRadio:1.0,
                  mid:1.0,
                  clickable:true,
                  callback:function(){
                      this.color.setHex(0xFF0000FF);
                      viewer.render( );
                  }
              });
              viewer.render();
            });
     */
    public addArrow(spec) {
        spec = spec || {};
 
        spec.start = this.getSelectionCenter(spec.start);
        spec.end = this.getSelectionCenter(spec.end);
 
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addArrow(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
    /**
     * Create and add cylinder shape
     *
     * @function $3Dmol.GLViewer#addCylinder
     * @param {CylinderSpec} spec - Style specification
     * @return {GLShape}
     
      @example
     viewer.setBackgroundColor(0xffffffff);
          viewer.addCylinder({start:{x:0.0,y:0.0,z:0.0},
                              end:{x:10.0,y:0.0,z:0.0},
                              radius:1.0,
                              fromCap:1,
                              toCap:2,
                              color:'red',
                              hoverable:true,
                              clickable:true,
                              callback:function(){ this.color.setHex(0x00FFFF00);viewer.render( );},
                              hover_callback: function(){ viewer.render( );},
                              unhover_callback: function(){ this.color.setHex(0xFF000000);viewer.render( );}
                             });
          viewer.addCylinder({start:{x:0.0,y:2.0,z:0.0},
                              end:{x:0.0,y:10.0,z:0.0},
                              radius:0.5,
                              fromCap:false,
                              toCap:true,
                              color:'teal'});
          viewer.addCylinder({start:{x:15.0,y:0.0,z:0.0},
                              end:{x:20.0,y:0.0,z:0.0},
                              radius:1.0,
                              color:'black',
                              fromCap:false,
                              toCap:false});
          viewer.render();
     */
    public addCylinder(spec) {
        spec = spec || {};
 
        spec.start = this.getSelectionCenter(spec.start);
        spec.end = this.getSelectionCenter(spec.end);
 
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        if (spec.dashed)
            s.addDashedCylinder(spec);
        else
            s.addCylinder(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
    /**
     * Create and add Curve shape
     *
     * @function $3Dmol.GLViewer#addCurve
     * @param {CurveSpec} spec - Style specification
     * @return {GLShape}
     
     @example
          viewer.addCurve({points: [{x:0.0,y:0.0,z:0.0}, {x:5.0,y:3.0,z:0.0}, {x:5.0,y:7.0,z:0.0}, {x:0.0,y:10.0,z:0.0}],
                              radius:0.5,
                              smooth: 10,
                              fromArrow:false,
                              toArrow: true,
                              color:'orange',
                              });
          viewer.addCurve({points: [{x:-1,y:0.0,z:0.0}, {x:-5.0,y:5.0,z:0.0}, {x:-2,y:10.0,z:0.0}],
                              radius:1,
                              fromArrow:true,
                              toArrow: false,
                              color:'purple',
                              });
          viewer.zoomTo();
          viewer.render();
     */
    public addCurve(spec) {
        spec = spec || {};
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addCurve(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
 
    /**
     * Create and add line shape
     *
     * @function $3Dmol.GLViewer#addLine
     * @param {LineSpec} spec - Style specification, can specify dashed, dashLength, and gapLength
     * @return {GLShape}
     @example
     $3Dmol.download("pdb:2ABJ",viewer,{},function(){
     
              viewer.setViewStyle({style:"outline"});
              viewer.setStyle({chain:'A'},{sphere:{hidden:true}});
              viewer.setStyle({chain:'D'},{sphere:{radius:3.0}});
              viewer.setStyle({chain:'G'},{sphere:{colorscheme:'greenCarbon'}});
              viewer.setStyle({chain:'J'},{sphere:{color:'blue'}});
              viewer.addLine({dashed:true,start:{x:0,y:0,z:0},end:{x:100,y:100,z:100}});
              viewer.render();
          });
     
     */
    public addLine(spec) {
        spec = spec || {};
 
        spec.start = this.getSelectionCenter(spec.start);
        spec.end = this.getSelectionCenter(spec.end);
 
        spec.wireframe = true;
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        if (spec.dashed)
            s = this.addLineDashed(spec, s);
        else
            s.addLine(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
    /**
     * Unit Cell shape specification.
     * @typedef UnitCellStyleSpec
     * @prop {LineStyleSpec} box - line style used to draw box
     * @prop {ArrowSpec} astyle - arrow specification of "a" axis
     * @prop {ArrowSpec} bstyle - arrow specification of "b" axis
     * @prop {ArrowSpec} cstyle - arrow specification of "c" axis
     * @prop {string} alabel - label for a axis
     * @prop {LabelSpec} alabelstyle - label style for a axis
     * @prop {string} blabel - label for b axis
     * @prop {LabelSpec} blabelstyle - label style for b axis
     * @prop {string} clabel - label for c axis
     * @prop {LabelSpec} clabelstyle - label style for c axis
     
     */
 
    /**
     * Create and add unit cell visualization.
     *
     * @function $3Dmol.GLViewer#addUnitCell
     * @param {GLModel} model - Model with unit cell information (e.g., pdb derived).  If omitted uses most recently added model.
     * @param {UnitCellStyleSpec} spec - visualization style
       @example
     
            $.get('data/1jpy.cif', function(data) {
              let m = viewer.addModel(data);
              viewer.addUnitCell(m, {box:{color:'purple'},alabel:'X',blabel:'Y',clabel:'Z',alabelstyle: {fontColor: 'black',backgroundColor:'white',inFront:true,fontSize:40},astyle:{color:'darkred', radius:5,midpos: -10}});
              viewer.zoomTo();
              viewer.render();
    });
     */
    public addUnitCell(model, spec) {
        model = this.getModel(model);
        spec = spec || { alabel: 'a', blabel: 'b', clabel: 'c' };
 
        spec.box = spec.box || {};
        spec.astyle = spec.astyle || { color: 'red', radius: 0.1, midpos: -1 };
        spec.bstyle = spec.bstyle || { color: 'green', radius: 0.1, midpos: -1 };
        spec.cstyle = spec.cstyle || { color: 'blue', radius: 0.1, midpos: -1 };
        spec.alabelstyle = spec.alabelstyle || { fontColor: 'red', showBackground: false, alignment: 'center', inFront: false };
        spec.blabelstyle = spec.blabelstyle || { fontColor: 'green', showBackground: false, alignment: 'center', inFront: false };
        spec.clabelstyle = spec.clabelstyle || { fontColor: 'blue', showBackground: false, alignment: 'center', inFront: false };
 
        //clear any previous box
        Iif (model.unitCellObjects) {
            this.removeUnitCell(model);
        }
        model.unitCellObjects = { shapes: [], labels: [] };
        //calculate points
        var data = model.getCrystData();
        var matrix = null;
        Iif (data) {
 
            if (data.matrix) {
                matrix = data.matrix;
            } else {
                var a = data.a, b = data.b, c = data.c, alpha = data.alpha, beta = data.beta, gamma = data.gamma;
                alpha = alpha * Math.PI / 180.0;
                beta = beta * Math.PI / 180.0;
                gamma = gamma * Math.PI / 180.0;
 
                var u, v, w;
 
                u = Math.cos(beta);
                v = (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma);
                w = Math.sqrt(Math.max(0, 1 - u * u - v * v));
 
                matrix = new Matrix3(a, b * Math.cos(gamma), c * u,
                    0, b * Math.sin(gamma), c * v,
                    0, 0, c * w);
            }
 
            var points = [new Vector3(0, 0, 0),
            new Vector3(1, 0, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, 0, 1),
            new Vector3(1, 1, 0),
            new Vector3(0, 1, 1),
            new Vector3(1, 0, 1),
            new Vector3(1, 1, 1)];
 
            // console.log('Matrix4', data.matrix4, data.matrix);
            if (data.matrix4) {
                for (let i = 0; i < points.length; i++) {
                    Iif (data.size) points[i].multiplyVectors(points[i], data.size); //matrix is for unit vectors, not whole box
                    points[i] = points[i].applyMatrix4(data.matrix4);
                }
            } else {
                for (let i = 0; i < points.length; i++) {
                    points[i] = points[i].applyMatrix3(matrix);
                }
            }
 
            //draw box
            Iif (spec.box && !spec.box.hidden) {
                spec.box.wireframe = true;
                var s = new GLShape(spec.box);
                s.shapePosition = this.shapes.length;
 
                s.addLine({ start: points[0], end: points[1] });
                s.addLine({ start: points[0], end: points[2] });
                s.addLine({ start: points[1], end: points[4] });
                s.addLine({ start: points[2], end: points[4] });
 
                s.addLine({ start: points[0], end: points[3] });
                s.addLine({ start: points[3], end: points[5] });
                s.addLine({ start: points[2], end: points[5] });
 
                s.addLine({ start: points[1], end: points[6] });
                s.addLine({ start: points[4], end: points[7] });
                s.addLine({ start: points[6], end: points[7] });
 
                s.addLine({ start: points[3], end: points[6] });
                s.addLine({ start: points[5], end: points[7] });
 
                this.shapes.push(s);
                model.unitCellObjects.shapes.push(s);
                s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
            }
 
            //draw arrows
            Iif (!spec.astyle.hidden) {
                spec.astyle.start = points[0];
                spec.astyle.end = points[1];
                let arrow = this.addArrow(spec.astyle);
                model.unitCellObjects.shapes.push(arrow);
            }
 
            Iif (!spec.bstyle.hidden) {
                spec.bstyle.start = points[0];
                spec.bstyle.end = points[2];
                let arrow = this.addArrow(spec.bstyle);
                model.unitCellObjects.shapes.push(arrow);
            }
 
            Iif (!spec.cstyle.hidden) {
                spec.cstyle.start = points[0];
                spec.cstyle.end = points[3];
                let arrow = this.addArrow(spec.cstyle);
                model.unitCellObjects.shapes.push(arrow);
            }
 
            Iif (spec.alabel) {
                spec.alabelstyle.position = points[1];
                let label = this.addLabel(spec.alabel, spec.alabelstyle);
                model.unitCellObjects.labels.push(label);
 
            }
            Iif (spec.blabel) {
                spec.blabelstyle.position = points[2];
                let label = this.addLabel(spec.blabel, spec.blabelstyle);
                model.unitCellObjects.labels.push(label);
            }
            Iif (spec.clabel) {
                spec.clabelstyle.position = points[3];
                let label = this.addLabel(spec.clabel, spec.clabelstyle);
                model.unitCellObjects.labels.push(label);
            }
 
        }
 
    };
 
    /**
    * Remove unit cell visualization from model.
    *
    * @function $3Dmol.GLViewer#removeUnitCell
    * @param {GLModel} model - Model with unit cell information (e.g., pdb derived).  If omitted uses most recently added model.
      @example
           $.get('data/icsd_200866.cif', function(data) {
             let m = viewer.addModel(data);
             viewer.setStyle({sphere:{}})
             viewer.addUnitCell();
             viewer.zoomTo();
             viewer.removeUnitCell();
             viewer.render();
       });
    */
    public removeUnitCell(model) {
        model = this.getModel(model);
        Iif (model.unitCellObjects) {
            let viewer = this;
            model.unitCellObjects.shapes.forEach(function (s) { viewer.removeShape(s); });
            model.unitCellObjects.labels.forEach(function (l) { viewer.removeLabel(l); });
        }
        delete model.unitCellObjects;
    };
 
    /**
    * Replicate atoms in model to form a super cell of the specified dimensions.
    * Original cell will be centered as much as possible.
    *
    * @function $3Dmol.GLViewer#replicateUnitCell
    * @param {integer} A - number of times to replicate cell in X dimension.
    * @param {integer} B - number of times to replicate cell in Y dimension.  If absent, X value is used.
    * @param {integer} C - number of times to replicate cell in Z dimension.  If absent, Y value is used.
    * @param {GLModel} model - Model with unit cell information (e.g., pdb derived).  If omitted uses most recently added model.
      @example
           $.get('data/icsd_200866.cif', function(data) {
             let m = viewer.addModel(data);
             viewer.setStyle({sphere:{scale:.25}})
             viewer.addUnitCell();
             viewer.zoomTo();
             viewer.replicateUnitCell(3,2,1,m);
             viewer.render();
       });
    */
    public replicateUnitCell(A, B, C, model) {
        model = this.getModel(model);
        A = A || 3;
        B = B || A;
        C = C || B;
        let cryst = model.getCrystData();
        Iif (cryst) {
            const atoms = model.selectedAtoms({});
            const matrix = cryst.matrix;
            let makeoff = function (I) {
                //alternate around zero: 1,-1,2,-2...
                if (I % 2 == 0) return -I / 2;
                else return Math.ceil(I / 2);
            };
 
            for (let i = 0; i < A; i++) {
                for (let j = 0; j < B; j++) {
                    for (let k = 0; k < C; k++) {
                        Iif (i == 0 && j == 0 && k == 0) continue; //actual unit cell
                        let offset = new Vector3(makeoff(i), makeoff(j), makeoff(k));
                        offset.applyMatrix3(matrix);
 
                        let newatoms = [];
                        for (let a = 0; a < atoms.length; a++) {
                            let newAtom: any = {};
                            for (let p in atoms[a]) {
                                newAtom[p] = atoms[a][p];
                            }
                            newAtom.x += offset.x;
                            newAtom.y += offset.y;
                            newAtom.z += offset.z;
                            newatoms.push(newAtom);
                        }
                        model.addAtoms(newatoms);
                    }
                }
            }
        }
    };
 
    public addLineDashed(spec, s) {
        spec.dashLength = spec.dashLength || 0.5;
        spec.gapLength = spec.gapLength || 0.5;
        spec.start = spec.start || {};
        spec.end = spec.end || {};
 
        var p1 = new Vector3(spec.start.x || 0,
            spec.start.y || 0, spec.start.z || 0);
        var p2 = new Vector3(spec.end.x,
            spec.end.y || 0, spec.end.z || 0);
 
        var dir = new Vector3();
        var dash = new Vector3();
        var gap = new Vector3();
        var length, dashAmt, gapAmt;
        var temp = p1.clone();
        var drawn = 0;
 
        dir.subVectors(p2, p1);
        length = dir.length();
        dir.normalize();
        dash = dir.clone();
        gap = dir.clone();
        dash.multiplyScalar(spec.dashLength);
        gap.multiplyScalar(spec.gapLength);
        dashAmt = dash.length();
        gapAmt = gap.length();
 
        while (drawn < length) {
            Iif ((drawn + dashAmt) > length) {
                spec.start = p1;
                spec.end = p2;
                s.addLine(spec);
                break;
            }
            temp.addVectors(p1, dash);
            spec.start = p1;
            spec.end = temp;
            s.addLine(spec);
            p1 = temp.clone();
            drawn += dashAmt;
 
            temp.addVectors(p1, gap);
            p1 = temp.clone();
            drawn += gapAmt;
        }
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    }
 
    /**
     * Add custom shape component from user supplied function
     *
     * @function $3Dmol.GLViewer#addCustom
     * @param {CustomSpec} spec - Style specification
     * @return {GLShape}
     @example
     function triangle(viewer) {
        var vertices = [];
        var normals = [];
        var colors = [];
        var r = 20;
        //triangle
        vertices.push(new $3Dmol.Vector3(0,0,0));
        vertices.push(new $3Dmol.Vector3(r,0,0));
        vertices.push(new $3Dmol.Vector3(0,r,0));
        
        normals.push(new $3Dmol.Vector3(0,0,1));
        normals.push(new $3Dmol.Vector3(0,0,1));
        normals.push(new $3Dmol.Vector3(0,0,1));
        
        colors.push({r:1,g:0,b:0});
        colors.push({r:0,g:1,b:0});
        colors.push({r:0,g:0,b:1});
        
        var faces = [ 0,1,2 ];
        
        var spec = {vertexArr:vertices, normalArr: normals, faceArr:faces,color:colors};
        viewer.addCustom(spec);
    }
    triangle(viewer);
    viewer.render();
     */
    public addCustom(spec) {
        spec = spec || {};
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addCustom(spec);
        this.shapes.push(s);
        s.finalize(); //finalize shape for memory efficiency, assume shape won't be extended
 
        return s;
    };
 
    /**
     * Construct isosurface from volumetric data in gaussian cube format
     * @function $3Dmol.GLViewer#addVolumetricData
     * @param {String} data - Input file contents
     * @param {String} format - Input file format
     * @param {IsoSurfaceSpec} or {VolumetricRenderSpec} spec - Shape style specification
     * @return {GLShape}
     *
     * @example
     
     
    $.get('data/bohr.cube', function(data) {
     
    viewer.addVolumetricData(data, "cube", {isoval: -0.01, color: "red", opacity: 0.95});
    viewer.setStyle({cartoon:{},stick:{}});
    viewer.zoomTo();
    viewer.render();
    });
     
     
     */
    public addVolumetricData(data, format, spec) {
        spec = spec || {};
 
        var voldata = new VolumeData(data, format);
        if (spec.transferfn) { //volumetric rendering
            return this.addVolumetricRender(voldata, spec);
        } else {
            return this.addIsosurface(voldata, spec);
        }
    };
 
    /**
     * Construct isosurface from volumetric data.  This is more flexible
    * than addVolumetricData, but can not be used with py3Dmol.
     * @function $3Dmol.GLViewer#addIsosurface
     * @param {$3Dmol.VolumeData} data - volumetric data
     * @param {IsoSurfaceSpec} spec - Shape style specification
     * @return {GLShape}
     *
     @example
     $.get('../test_structs/benzene-homo.cube', function(data){
              var voldata = new $3Dmol.VolumeData(data, "cube");
              viewer.addIsosurface(voldata, {isoval: 0.01,
                                             color: "blue"});
              viewer.addIsosurface(voldata, {isoval: -0.01,
                                             color: "red"});
              viewer.zoomTo();
              viewer.render();
            });
     */
    public addIsosurface(data, spec, callback?) {
        spec = spec || {};
        var s = new GLShape(spec);
        s.shapePosition = this.shapes.length;
        s.addIsosurface(data, spec, callback);
        this.shapes.push(s);
        return s;
    };
 
    /**
     * Create volumetric renderer for volumetricData
     * @function $3Dmol.GLViewer#addVolumetricRender
     * @param {$3Dmol.VolumeData} data - volumetric data
     * @param {VolumetricRenderSpec} spec - specification of volumetric render
     *
     * @return {GLShape}
     *
     */
    public addVolumetricRender(data, spec) {
        spec = spec || {};
        var s = new GLVolumetricRender(data, spec);
        s.shapePosition = this.shapes.length;
        this.shapes.push(s);
        return s;
    };
 
    /**
     * Return true if volumetric rendering is supported (WebGL 2.0 required)
     *
     * @function $3Dmol.GLViewer#hasVolumetricRender
     * @return {boolean}
     */
    public hasVolumetricRender() {
        return this.renderer.supportsVolumetric();
    };
 
    /**
     * Enable/disable fog for content far from the camera
     *
     * @function $3Dmol.GLViewer#enableFog
     * @param {boolean} fog whether to enable or disable the fog
     */
    public enableFog(fog) {
        if (fog) {
            this.scene.fog = new Fog(this.bgColor, 100, 200);
        } else {
            this.config.disableFog = true;
            this.show();
        }
    };
 
    /**
     * Sets the atomlists of all models in the viewer to specified frame.
     * Shapes and labels can also be displayed by frame.
     * Sets to last frame if framenum out of range
     *
     * @function $3Dmol.GLViewer#setFrame
     * @param {number} framenum - fame index to use, starts at zero
     * @return {Promise}
     */
    public setFrame(framenum) {
        this.viewer_frame = framenum;
        let viewer = this;
        return new Promise<void>(function (resolve) {
            var modelMap = viewer.models.map(function (model) {
                return model.setFrame(framenum, viewer);
            });
            Promise.all(modelMap)
                .then(function () { resolve(); });
        });
    };
 
    /**
     * Gets the current viewer frame.
     *
     * @function $3Dmol.GLViewer#getFrame
     */
    public getFrame() {
        return this.viewer_frame;
    };
 
    /**
     * Returns the number of frames that the model with the most frames in the viewer has
     *
     * @function $3Dmol.GLViewer#getNumFrames
     * @return {number}
     */
    public getNumFrames() {
        var mostFrames = 0;
        for (let i = 0; i < this.models.length; i++) {
            Iif (this.models[i].getNumFrames() > mostFrames) {
                mostFrames = this.models[i].getNumFrames();
            }
        }
        for (let i = 0; i < this.shapes.length; i++) {
            Iif (this.shapes[i].frame && this.shapes[i].frame >= mostFrames) {
                mostFrames = this.shapes[i].frame + 1;
            }
        }
        for (let i = 0; i < this.labels.length; i++) {
            Iif (this.labels[i].frame && this.labels[i].frame >= mostFrames) {
                mostFrames = this.labels[i].frame + 1;
            }
        }
        return mostFrames;
    };
 
 
    /**
     * Animate all models in viewer from their respective frames
     * @function $3Dmol.GLViewer#animate
     * @param {Object} options - can specify interval (speed of animation), loop (direction
     * of looping, 'backward', 'forward' or 'backAndForth'), step interval between frames ('step'), and reps (numer of repetitions, 0 indicates infinite loop)
     *
     */
 
    public animate(options) {
        this.incAnim();
        var interval = 100;
        var loop = "forward";
        var reps = 0;
        options = options || {};
        Iif (options.interval) {
            interval = options.interval;
        }
        Iif (options.loop) {
            loop = options.loop;
        }
        Iif (options.reps) {
            reps = options.reps;
        }
        var mostFrames = this.getNumFrames();
        var self = this;
        var currFrame = 0;
        var inc = 1;
        Iif (options.step) {
            inc = options.step;
            reps /= inc;
        }
        var displayCount = 0;
        var displayMax = mostFrames * reps;
        var time = new Date();
        var resolve, timer;
        var display = function (direction) {
            time = new Date();
            if (direction == "forward") {
                self.setFrame(currFrame)
                    .then(function () {
                        currFrame = (currFrame + inc) % mostFrames;
                        resolve();
                    });
            }
            else if (direction == "backward") {
                self.setFrame((mostFrames - 1) - currFrame)
                    .then(function () {
                        currFrame = (currFrame + inc) % mostFrames;
                        resolve();
                    });
            }
            else { //back and forth
                self.setFrame(currFrame)
                    .then(function () {
                        currFrame += inc;
                        inc *= (((currFrame % (mostFrames - 1)) == 0) ? -1 : 1);
                        resolve();
                    });
            }
        };
 
        resolve = function () {
            self.render();
            if (!self.getCanvas().isConnected) {
                //we no longer exist as part of the DOM
                self.stopAnimate();
            }
            else if (++displayCount == displayMax || !self.isAnimated()) {
                timer.cancel();
                self.animationTimers.delete(timer);
                self.decAnim();
            }
            else {
                var newInterval = interval - (new Date().getTime() - time.getTime());
                newInterval = (newInterval > 0) ? newInterval : 0;
                self.animationTimers.delete(timer);
                timer = new PausableTimer(display, newInterval, loop);
                self.animationTimers.add(timer);
            }
        };
 
        timer = new PausableTimer(display, 0, loop);
        this.animationTimers.add(timer);
        return this;
    };
 
    /**
     * Stop animation of all models in viewer
     * @function $3Dmol.GLViewer#stopAnimate
     */
    public stopAnimate() {
        this.animated = 0;
        this.animationTimers.forEach(function (timer: PausableTimer) { timer.cancel(); });
        this.animationTimers = new Set();
        return this;
    };
 
    /**
     * Pause animation of all models in viewer
     * @function $3Dmol.GLViewer#pauseAnimate
     */
    public pauseAnimate() {
        this.animationTimers.forEach(function (timer) { timer.pause(); });
        return this;
    };
 
    /**
     * Resume animation of all models in viewer
     * @function $3Dmol.GLViewer#resumeAnimate
     */
    public resumeAnimate() {
        this.animationTimers.forEach(function (timer) { timer.resume(); });
        return this;
    };
 
 
    /**
     * Return true if viewer is currently being animated, false otherwise
     * @function $3Dmol.GLViewer#isAnimated
     * @return {boolean}
     */
    public isAnimated() {
        return this.animated > 0;
    };
 
 
    /**
     * Create and add model to viewer, given molecular data and its format
     *
     * @function $3Dmol.GLViewer#addModel
     * @param {string} data - Input data
     * @param {string} format - Input format ('pdb', 'sdf', 'xyz', 'pqr', or 'mol2')
     * @param {ParserOptionsSpec} options - format dependent options. Attributes depend on the input file format.
     * @example
     
     
          viewer.setViewStyle({style:"outline"});
          $.get('data/1fas.pqr', function(data){
              viewer.addModel(data, "pqr");
              $.get("data/1fas.cube",function(volumedata){
                  viewer.addSurface($3Dmol.SurfaceType.VDW, {opacity:0.85,voldata: new $3Dmol.VolumeData(volumedata, "cube"), volscheme: new $3Dmol.Gradient.RWB(-10,10)},{});
     
              viewer.render();
              });
              viewer.zoomTo();
          });
     *
     * @return {GLModel}
     */
    public addModel(data, format, options?) {
        if (options && !options.defaultcolors) {
            options.defaultcolors = this.defaultcolors;
            options.cartoonQuality = options.cartoonQuality || this.config.cartoonQuality;
        } else Iif (typeof (options) === 'undefined') {
            options = { defaultcolors: this.defaultcolors, cartoonQuality: this.config.cartoonQuality };
        }
        var m = new GLModel(this.models.length, options);
        m.addMolData(data, format, options);
        this.models.push(m);
 
        return m;
    };
 
    /**
     * Given multimodel file and its format, add atom data to the viewer as separate models
     * and return list of these models
     *
     * @function $3Dmol.GLViewer#addModels
     * @param {string} data - Input data
     * @param {string} format - Input format (see {@link FileFormats})
     * @return {Array<GLModel>}
     */
    public addModels(data, format, options?) {
        options = options || {};
        options.multimodel = true;
        options.frames = true;
 
        var modelatoms = GLModel.parseMolData(data, format, options);
 
        for (var i = 0; i < modelatoms.length; i++) {
            var newModel = new GLModel(this.models.length, this.defaultcolors);
            newModel.setAtomDefaults(modelatoms[i]);
            newModel.addFrame(modelatoms[i]);
            newModel.setFrame(0);
            Iif (modelatoms.modelData)
                newModel.setModelData(modelatoms.modelData[i]);
            newModel.setDontDuplicateAtoms(!options.duplicateAssemblyAtoms);
            this.models.push(newModel);
        }
 
        return this.models;
    };
 
    /**
     * Create and add model to viewer. Given multimodel file and its format,
     * different atomlists are stored in model's frame
     * property and model's atoms are set to the 0th frame
     *
     * @function $3Dmol.GLViewer#addModelsAsFrames
     * @param {string} data - Input data
     * @param {string} format - Input format (see {@link FileFormats})
     * @return {GLModel}
     *
     * @example
            $.get('../test_structs/multiple2.xyz', function(data){
              viewer.addModelsAsFrames(data, "xyz");
              viewer.animate({loop: "forward",reps: 1});
              viewer.setStyle({stick:{colorscheme:'magentaCarbon'}});
              viewer.zoomTo();
              viewer.render();
          });
     */
    public addModelsAsFrames(data, format, options?) {
        options = options || {};
        options.multimodel = true;
        options.frames = true;
        var m = new GLModel(this.models.length, this.defaultcolors);
        m.addMolData(data, format, options);
        this.models.push(m);
 
        return m;
    };
 
    /**
     * Create and add model to viewer. Given multimodel file and its format,
     * all atoms are added to one model
     *
     * @function $3Dmol.GLViewer#addAsOneMolecule
     * @param {string} data - Input data
     * @param {string} format - Input format (see {@link FileFormats})
     * @return {GLModel}
     @example
     
     
          $.get('../test_structs/multiple.sdf', function(data){
              viewer.addAsOneMolecule(data, "sdf");
              viewer.zoomTo();
              viewer.render();
          });
     */
    public addAsOneMolecule(data, format, options?) {
        options = options || {};
        options.multimodel = true;
        options.onemol = true;
        var m = new GLModel(this.models.length, this.defaultcolors);
        m.addMolData(data, format, options);
        this.models.push(m);
 
        return m;
    };
 
 
    /**
     * Delete specified model from viewer
     *
     * @function $3Dmol.GLViewer#removeModel
     * @param {GLModel} model
     */
    public removeModel(model) {
        model = this.getModel(model);
        Iif (!model)
            return;
        model.removegl(this.modelGroup);
        delete this.models[model.getID()];
        // clear off back of model array
        while (this.models.length > 0
            && typeof (this.models[this.models.length - 1]) === "undefined")
            this.models.pop();
        return this;
    };
 
    /**
     * Delete all existing models
     * @function $3Dmol.GLViewer#removeAllModels
     */
    public removeAllModels() {
        for (var i = 0; i < this.models.length; i++) {
            var model = this.models[i];
            Iif (model) model.removegl(this.modelGroup);
 
        }
        this.models.splice(0, this.models.length); //don't simply overwrite array in case linked
        return this;
    };
 
    /**
     * Export one or all of the loaded models into ChemDoodle compatible JSON.
     * @function $3Dmol.GLViewer#exportJSON
     * @param {boolean} includeStyles - Whether or not to include style information.
     * @param {number} modelID - Optional parameter for which model to export. If left out, export all of them.
     * @return {string}
     */
    public exportJSON(includeStyles, modelID) {
        var object: any = {};
        if (modelID === undefined) {
            object.m = this.models.map(function (model) {
                return model.toCDObject(includeStyles);
            });
        } else {
            object.m = [this.models[modelID].toCDObject()];
        }
        return JSON.stringify(object);
    };
 
    /** return a VRML string representation of the scene.  Include VRML header information
     * @function $3Dmol.GLViewer#exportVRML
     * @return VRML
     */
    public exportVRML() {
        var savedmodelGroup = this.modelGroup;
        this.applyToModels("removegl", this.modelGroup); //cleanup
        this.modelGroup = new Object3D();
        //rendering with plain mesh
        this.render(null, { supportsImposters: false, supportsAIA: false, regen: true });
        var ret = '#VRML V2.0 utf8\n' + this.modelGroup.vrml() + '\n';
        this.applyToModels("removegl", this.modelGroup); //cleanup
        this.modelGroup = savedmodelGroup;
        return ret;
    };
 
    /**
     * Create a new model from atoms specified by sel.
     * If extract, removes selected atoms from existing models
     *
     * @function $3Dmol.GLViewer#createModelFrom
     * @param {Object} sel - Atom selection specification
     * @param {boolean=} extract - If true, remove selected atoms from existing models
     * @return {GLModel}
     */
    public createModelFrom(sel, extract) {
        var m = new GLModel(this.models.length, this.defaultcolors);
        for (var i = 0; i < this.models.length; i++) {
            Iif (this.models[i]) {
                var atoms = this.models[i].selectedAtoms(sel);
                m.addAtoms(atoms);
                Iif (extract)
                    this.models[i].removeAtoms(atoms);
            }
        }
        this.models.push(m);
        return m;
    };
 
    private applyToModels(func, sel, value1?, value2?, value3?, value4?, value5?) {
 
        //apply func to all models that are selected by sel with value1 and 2
        var ms = this.getModelList(sel);
        for (var i = 0; i < ms.length; i++) {
            ms[i][func](sel, value1, value2, value3, value4, value5);
        }
    }
 
    /**
     * Set style properties to all selected atoms
     *
     * @function $3Dmol.GLViewer#setStyle
     * @param {AtomSelectionSpec} sel - Atom selection specification
     * @param {AtomStyleSpec} style - Style spec to apply to specified atoms
     *
     * @example
     viewer.setBackgroundColor(0xffffffff);
    $3Dmol.download('pdb:5IRE',viewer,{doAssembly: false},function(m) {
    m.setStyle({chain:'A'},{'cartoon':{color:'spectrum'}});
    m.setStyle({chain:'C'},{'cartoon':{style:'trace',color:'blue'}});
    m.setStyle({chain:'E'},{'cartoon':{tubes:true,arrows:true,color:'green',opacity:0.75}});
    m.setStyle({chain:'B'},{'cartoon':{color:'red',opacity:0.5}});
    m.setStyle({chain:'D'},{'cartoon':{style:'trace',color:'grey',opacity:0.75}});
    m.setStyle({chain:'F'},{'cartoon':{arrows:true,color:'white'}});
    // viewer.addStyle({chain:'B'},{line:{}});
    viewer.zoomTo();
    viewer.render();
    });
     */
    public setStyle(sel, style) {
        Iif (typeof (style) === 'undefined') {
            //if a single argument is provided, assume it is a style and select all
            style = sel;
            sel = {};
        }
 
        this.applyToModels("setStyle", sel, style, false);
        return this;
    };
 
    /**
     * Add style properties to all selected atoms
     *
     * @function $3Dmol.GLViewer#addStyle
     * @param {AtomSelectionSpec} sel - Atom selection specification
     * @param {AtomStyleSpec} style - style spec to add to specified atoms
     @example
     
    $3Dmol.download('pdb:5IRE',viewer,{doAssembly: false},function(m) {
    viewer.setStyle({cartoon:{}});
    //keep cartoon style, but show thick sticks for chain A
    viewer.addStyle({chain:'A'},{stick:{radius:.5,colorscheme:"magentaCarbon"}});
    viewer.zoomTo();
    viewer.render();
    });
     */
    public addStyle(sel, style) {
        Iif (typeof (style) === 'undefined') {
            //if a single argument is provided, assume it is a style and select all
            style = sel;
            sel = {};
        }
        this.applyToModels("setStyle", sel, style, true);
        return this;
    };
 
 
    /**
     * Set click-handling properties to all selected atomsthis.
     *
     * @function $3Dmol.GLViewer#setClickable
     * @param {AtomSelectionSpec} sel - atom selection to apply clickable settings to
     * @param {boolean} clickable - whether click-handling is enabled for the selection
     * @param {function} callback - function called when an atom in the selection is clicked
     *
     * @example
        $3Dmol.download("cid:307900",viewer,{},function(){
     
               viewer.setStyle({},{sphere:{}});
               viewer.setClickable({},true,function(atom,viewer,event,container) {
                   viewer.addLabel(atom.resn+":"+atom.atom,{position: atom, backgroundColor: 'darkgreen', backgroundOpacity: 0.8});
               });
               viewer.render();
    });
     */
    public setClickable(sel, clickable, callback) {
        this.applyToModels("setClickable", sel, clickable, callback);
        return this;
    };
    /** Set hoverable and callback of selected atoms
     *
     * @function $3Dmol.GLViewer#setHoverable
     * @param {AtomSelectionSpec} sel - atom selection to apply hoverable settings to
     * @param {boolean} hoverable - whether hover-handling is enabled for the selection
     * @param {function} hover_callback - function called when an atom in the selection is hovered over
     * @param {function} unhover_callback - function called when the mouse moves out of the hover area
    @example
    $3Dmol.download("pdb:1ubq",viewer,{},function(){
     
           viewer.setHoverable({},true,function(atom,viewer,event,container) {
               if(!atom.label) {
                atom.label = viewer.addLabel(atom.resn+":"+atom.atom,{position: atom, backgroundColor: 'mintcream', fontColor:'black'});
               }
           },
           function(atom) {
               if(atom.label) {
                viewer.removeLabel(atom.label);
                delete atom.label;
               }
            }
           );
           viewer.setStyle({},{stick:{}});
           viewer.render();
    });
     
     */
    public setHoverable(sel, hoverable, hover_callback, unhover_callback) {
        this.applyToModels("setHoverable", sel, hoverable, hover_callback, unhover_callback);
        return this;
    };
 
    /** enable context menu and callback of selected atoms
     *
     * @function $3Dmol.GLViewer#enableContextMenu
     * @param {AtomSelectionSpec} sel - atom selection to apply hoverable settings to
     * @param {boolean} contextMenuEnabled - whether contextMenu-handling is enabled for the selection
     
     */
    public enableContextMenu(sel, contextMenuEnabled) {
        this.applyToModels("enableContextMenu", sel, contextMenuEnabled);
        return this;
    };
 
    /**
     * If  atoms have dx, dy, dz properties (in some xyz files), vibrate populates each model's frame property based on parameters.
     * Models can then be animated
     *
     * @function $3Dmol.GLViewer#vibrate
     * @param {number} numFrames - number of frames to be created, default to 10
     * @param {number} amplitude - amplitude of distortion, default to 1 (full)
     * @param {boolean} bothWays - if true, extend both in positive and negative directions by numFrames
     * @param {ArrowSpec} arrowSpec - specification for drawing animated arrows. If color isn't specified, atom color (sphere, stick, line preference) is used.
     */
    public vibrate(numFrames, amplitude, bothways, arrowSpec) {
        this.applyToModels("vibrate", numFrames, amplitude, bothways, this, arrowSpec);
        return this;
    };
 
    /**
     * @function $3Dmol.GLViewer#setColorByProperty
     * @param {AtomSelectionSpec} sel
     * @param {type} prop
     * @param {type} scheme
     */
    public setColorByProperty(sel, prop, scheme, range) {
        this.applyToModels("setColorByProperty", sel, prop, scheme, range);
        return this;
    };
 
    /**
     * @function $3Dmol.GLViewer#setColorByElement
     * @param {AtomSelectionSpec} sel
     * @param {type} colors
     */
    public setColorByElement(sel, colors) {
        this.applyToModels("setColorByElement", sel, colors);
        return this;
    };
 
    /**
     *
     * @param {AtomSpec[]} atomlist
     * @param {Array}
     *            extent
     * @return {Array}
     */
    private static getAtomsWithin(atomlist, extent) {
        var ret = [];
 
        for (let i = 0; i < atomlist.length; i++) {
            var atom = atomlist[i];
            Iif (typeof (atom) == "undefined")
                continue;
 
            Iif (atom.x < extent[0][0] || atom.x > extent[1][0])
                continue;
            Iif (atom.y < extent[0][1] || atom.y > extent[1][1])
                continue;
            Iif (atom.z < extent[0][2] || atom.z > extent[1][2])
                continue;
            ret.push(atom);
        }
        return ret;
    };
 
    // return volume of extent
    private static volume(extent) {
        var w = extent[1][0] - extent[0][0];
        var h = extent[1][1] - extent[0][1];
        var d = extent[1][2] - extent[0][2];
        return w * h * d;
    }; // volume
    /*
     * Break up bounding box/atoms into smaller pieces so we can parallelize
     * with webworkers and also limit the size of the working memory Returns
     * a list of bounding boxes with the corresponding atoms. These extents
     * are expanded by 4 angstroms on each side.
     */
    /**
     *
     * @param {Array}
     *            extent
     * @param {AtomSpec[]} atomlist
     * @param {AtomSpec[]} atomstoshow
     * @return {Array}
     */
    private carveUpExtent(extent, atomlist, atomstoshow) {
        let ret = [];
 
        let index2atomlist = {}; //map from atom.index to position in atomlist
        for (let i = 0, n = atomlist.length; i < n; i++) {
            index2atomlist[atomlist[i].index] = i;
        }
 
        let atomsToListIndex = function (atoms) {
            //return a list of indices into atomlist
            let ret = [];
            for (let i = 0, n = atoms.length; i < n; i++) {
                Iif (atoms[i].index in index2atomlist)
                    ret.push(index2atomlist[atoms[i].index]);
            }
            return ret;
        };
        let copyExtent = function (extent) {
            // copy just the dimensions
            let ret = [];
            ret[0] = [extent[0][0], extent[0][1], extent[0][2]];
            ret[1] = [extent[1][0], extent[1][1], extent[1][2]];
            return ret;
        }; // copyExtent
        let splitExtentR = function (extent) {
            // recursively split until volume is below maxVol
            if (GLViewer.volume(extent) < GLViewer.maxVolume) {
                return [extent];
            } else {
                // find longest edge
                var w = extent[1][0] - extent[0][0];
                var h = extent[1][1] - extent[0][1];
                var d = extent[1][2] - extent[0][2];
 
                var index;
 
                if (w > h && w > d) {
                    index = 0;
                } else if (h > w && h > d) {
                    index = 1;
                } else {
                    index = 2;
                }
 
                // create two halves, splitting at index
                var a = copyExtent(extent);
                var b = copyExtent(extent);
                var mid = (extent[1][index] - extent[0][index]) / 2
                    + extent[0][index];
                a[1][index] = mid;
                b[0][index] = mid;
 
                var alist = splitExtentR(a);
                var blist = splitExtentR(b);
                return alist.concat(blist);
            }
        }; // splitExtentR
 
        // divide up extent
        let splits = splitExtentR(extent);
        // now compute atoms within expanded (this could be more efficient)
        let off = 6; // enough for water and 2*r, also depends on scale
        // factor
        for (let i = 0, n = splits.length; i < n; i++) {
            let e = copyExtent(splits[i]);
            e[0][0] -= off;
            e[0][1] -= off;
            e[0][2] -= off;
            e[1][0] += off;
            e[1][1] += off;
            e[1][2] += off;
 
            let atoms = GLViewer.getAtomsWithin(atomlist, e);
            let toshow = GLViewer.getAtomsWithin(atomstoshow, splits[i]);
 
            // ultimately, divide up by atom for best meshing
            ret.push({
                extent: splits[i],
                atoms: atomsToListIndex(atoms),
                toshow: atomsToListIndex(toshow)
            });
        }
 
        return ret;
    };
 
    // create a mesh defined from the passed vertices and faces and material
    // Just create a single geometry chunk - broken up whether sync or not
    /**
     *
     * @param {AtomSpec[]} atoms
     * @param {{vertices:number,faces:number}}
     *            VandF
     * @param {$3Dmol.MeshLambertMaterial}
     *            mat
     * @return {$3Dmol.Mesh}
     */
    private static generateSurfaceMesh(atoms, VandF, mat) {
        var geo = new Geometry(true);
        // Only one group per call to generate surface mesh (addSurface
        // should split up mesh render)
        var geoGroup = geo.updateGeoGroup(0);
 
        // set colors for vertices
        var colors = [];
        for (let i = 0, il = atoms.length; i < il; i++) {
            var atom = atoms[i];
            Iif (atom) {
                if (typeof (atom.surfaceColor) != "undefined") {
                    colors[i] = atom.surfaceColor;
                } else Iif (atom.color) // map from atom
                    colors[i] = CC.color(atom.color);
            }
        }
 
        var vertexArray = geoGroup.vertexArray;
        // reconstruct vertices and faces
        var v = VandF.vertices;
        for (let i = 0, il = v.length; i < il; i++) {
            let offset = geoGroup.vertices * 3;
            vertexArray[offset] = v[i].x;
            vertexArray[offset + 1] = v[i].y;
            vertexArray[offset + 2] = v[i].z;
            geoGroup.vertices++;
        }
 
        //set colorArray of there are per-atom colors
        var colorArray = geoGroup.colorArray;
 
        if (mat.voldata && mat.volscheme) {
            //convert volumetric data into colors
            var scheme = mat.volscheme;
            var voldata = mat.voldata;
            var range = scheme.range() || [-1, 1];
            for (let i = 0, il = v.length; i < il; i++) {
                let val = voldata.getVal(v[i].x, v[i].y, v[i].z);
                let col = CC.color(scheme.valueToHex(val, range));
                let offset = i * 3;
                colorArray[offset] = col.r;
                colorArray[offset + 1] = col.g;
                colorArray[offset + 2] = col.b;
            }
        }
        else Iif (colors.length > 0) { //have atom colors
            for (let i = 0, il = v.length; i < il; i++) {
                let A = v[i].atomid;
                let offsetA = i * 3;
 
                colorArray[offsetA] = colors[A].r;
                colorArray[offsetA + 1] = colors[A].g;
                colorArray[offsetA + 2] = colors[A].b;
            }
        }
 
        var faces = VandF.faces;
        geoGroup.faceidx = faces.length;// *3;
        geo.initTypedArrays();
 
        var verts = geoGroup.vertexArray;
        var normalArray = geoGroup.normalArray;
        var vA, vB, vC, norm;
 
        // Setup colors, faces, and normals
        for (let i = 0, il = faces.length; i < il; i += 3) {
 
            // var a = faces[i].a, b = faces[i].b, c = faces[i].c;
            var a = faces[i], b = faces[i + 1], c = faces[i + 2];
            var offsetA = a * 3, offsetB = b * 3, offsetC = c * 3;
 
            // setup Normals
            // todo - calculate normals in parallel code
            vA = new Vector3(verts[offsetA], verts[offsetA + 1],
                verts[offsetA + 2]);
            vB = new Vector3(verts[offsetB], verts[offsetB + 1],
                verts[offsetB + 2]);
            vC = new Vector3(verts[offsetC], verts[offsetC + 1],
                verts[offsetC + 2]);
 
            vC.subVectors(vC, vB);
            vA.subVectors(vA, vB);
            vC.cross(vA);
 
            // face normal
            norm = vC;
            norm.normalize();
 
            normalArray[offsetA] += norm.x;
            normalArray[offsetB] += norm.x;
            normalArray[offsetC] += norm.x;
            normalArray[offsetA + 1] += norm.y;
            normalArray[offsetB + 1] += norm.y;
            normalArray[offsetC + 1] += norm.y;
            normalArray[offsetA + 2] += norm.z;
            normalArray[offsetB + 2] += norm.z;
            normalArray[offsetC + 2] += norm.z;
 
        }
        geoGroup.faceArray = new Uint16Array(faces);
        var mesh = new Mesh(geo, mat);
        return mesh;
    };
 
    // do same thing as worker in main thread
    /**
     *
     * @param {$3Dmol.SurfaceType}
     *            type
     * @param {Array}
     *            expandedExtent
     * @param {Array}
     *            extendedAtoms
     * @param {Array}
     *            atomsToShow
     * @param {AtomSpec[]} atoms
     * @param {number}
     *            vol
     * @return {Object}
     */
    private static generateMeshSyncHelper(type, expandedExtent,
        extendedAtoms, atomsToShow, atoms, vol) {
        //            var time = new Date();
        var ps = new ProteinSurface();
        ps.initparm(expandedExtent, (type === 1) ? false : true, vol);
 
        //            var time2 = new Date();
        //console.log("initialize " + (time2 - time) + "ms");
 
        ps.fillvoxels(atoms, extendedAtoms);
 
        //            var time3 = new Date();
        //console.log("fillvoxels " + (time3 - time2) + "  " + (time3 - time) + "ms");
 
        ps.buildboundary();
 
        Iif (type == SurfaceType.SES || type == SurfaceType.MS) {
            ps.fastdistancemap();
            ps.boundingatom(false);
            ps.fillvoxelswaals(atoms, extendedAtoms);
        }
 
        //            var time4 = new Date();
        //console.log("buildboundaryetc " + (time4 - time3) + "  " + (time4 - time) + "ms");
 
        ps.marchingcube(type);
 
        //            var time5 = new Date();
        //console.log("marching cube " + (time5 - time4) + "  "+ (time5 - time) + "ms");
 
        return ps.getFacesAndVertices(atomsToShow);
    };
 
    /**
     *
     * @param {matSpec}
     *            style
     * @return {$3Dmol.MeshLambertMaterial}
     */
    private static getMatWithStyle(style) {
        var mat = new MeshLambertMaterial();
        mat.vertexColors = Coloring.VertexColors;
 
        for (var prop in style) {
            if (prop === "color" || prop === "map") {
                // ignore
            } else Iif (style.hasOwnProperty(prop))
                mat[prop] = style[prop];
        }
        Iif (style.opacity !== undefined) {
            if (style.opacity === 1)
                mat.transparent = false;
            else
                mat.transparent = true;
        }
 
        return mat;
    }
 
 
    /**
     * Adds an explicit mesh as a surface object.
     * @function $3Dmol.GLViewer#addMesh
     * @param {$3Dmol.Mesh}
     *            mesh
     * @param {Object}
     *            style
     * @returns {number} surfid
     */
    public addMesh(mesh) {
        var surfobj = {
            geo: mesh.geometry,
            mat: mesh.material,
            done: true,
            finished: false //the rendered finishes surfaces when they are done
        };
        var surfid = this.nextSurfID();
        this.surfaces[surfid] = surfobj;
        return surfid;
    };
 
    //return a shallow copy of list l, e.g., for atoms so we can
    //ignore superficial changes (ie surfacecolor, position) that happen
    //while we're surface building
    private static shallowCopy(l) {
        var ret = [];
        let length = l.length;
        for (let i = 0; i < length; i++) {
            ret[i] = extend({}, l[i]);
        }
        return ret;
    };
 
 
 
    /**
     * Add surface representation to atoms
     * @function $3Dmol.GLViewer#addSurface
     * @param {$3Dmol.SurfaceType|string} type - Surface type (VDW, MS, SAS, or SES)
     * @param {SurfaceStyleSpec} style - optional style specification for surface material (e.g. for different coloring scheme, etc)
     * @param {AtomSelectionSpec} atomsel - Show surface for atoms in this selection
     * @param {AtomSelectionSpec} allsel - Use atoms in this selection to calculate surface; may be larger group than 'atomsel'
     * @param {AtomSelectionSpec} focus - Optionally begin rendering surface specified atoms
     * @param {function} surfacecallback - function to be called after setting the surface
     * @return {Promise} promise - Returns a promise that ultimately resovles to the surfid.  Returns surfid immediately if surfacecallback is specified.  Returned promise has a [surfid, GLViewer, style, atomsel, allsel, focus] fields for immediate access.
     */
    public addSurface(type, style, atomsel, allsel, focus, surfacecallback) {
        // type 1: VDW 3: SAS 4: MS 2: SES
        // if sync is true, does all work in main thread, otherwise uses
        // workers
        // with workers, must ensure group is the actual modelgroup since
        // surface
        // will get added asynchronously
        // all atoms in atomlist are used to compute surfaces, but only the
        // surfaces
        // of atomsToShow are displayed (e.g., for showing cavities)
        // if focusSele is specified, will start rending surface around the
 
        //surfacecallback gets called when done
        let surfid = this.nextSurfID();
        let mat = null;
        let self = this;
 
        if (typeof type == "string") {
            if (this.surfaceTypeMap[type.toUpperCase()] !== undefined)
                type = this.surfaceTypeMap[type];
            else {
                console.log("Surface type : " + type + " is not recognized");
            }
        }
        else Iif (type === undefined) {
            type = SurfaceType.VDW; //default
        }
        // atoms specified by this selection
        var atomlist = null, focusSele = null;
        //TODO: currently generating a shallow copy to avoid problems when atoms are chagned
        //during surface generation - come up with a better solution
        var atomsToShow = GLViewer.shallowCopy(this.getAtomsFromSel(atomsel));
        if (!allsel) {
            atomlist = atomsToShow;
        }
        else {
            atomlist = GLViewer.shallowCopy(this.getAtomsFromSel(allsel));
        }
 
        adjustVolumeStyle(style);
        var symmetries = false;
        var n;
        for (n = 0; n < this.models.length; n++) {
            Iif (this.models[n]) {
                var symMatrices = this.models[n].getSymmetries();
                Iif (symMatrices.length > 1 || (symMatrices.length == 1 && !(symMatrices[0].isIdentity()))) {
                    symmetries = true;
                    break;
                }
            }
        }
 
        var addSurfaceHelper = function addSurfaceHelper(surfobj, atomlist, atomsToShow) {
            //function returns promise with surfid resolved
            if (!focus) {
                focusSele = atomsToShow;
            } else {
                focusSele = GLViewer.shallowCopy(self.getAtomsFromSel(focus));
            }
 
            var atom;
            //                var time = new Date();
            var extent = getExtent(atomsToShow, true);
            Iif (style.map && style.map.prop) {
                // map color space using already set atom properties
                /** @type {AtomSpec} */
                var prop = style.map.prop;
                /** @type {Gradient} */
                var scheme = style.map.scheme || style.map.gradient || new Gradient.RWB();
                var range = scheme.range();
                Iif (!range) {
                    range = getPropertyRange(atomsToShow, prop);
                }
                style.colorscheme = { prop: prop, gradient: scheme };
 
            }
 
            //cache surface color on each atom
            for (let i = 0, il = atomlist.length; i < il; i++) {
                atom = atomlist[i];
                atom.surfaceColor = getColorFromStyle(atom, style);
            }
 
            var totalVol = GLViewer.volume(extent); // used to scale resolution
            var extents = self.carveUpExtent(extent, atomlist, atomsToShow);
 
            Iif (focusSele && focusSele.length && focusSele.length > 0) {
                var seleExtent = getExtent(focusSele, true);
                // sort by how close to center of seleExtent
                var sortFunc = function (a, b) {
                    var distSq = function (ex, sele) {
                        // distance from e (which has no center of mass) and
                        // sele which does
                        var e = ex.extent;
                        var x = e[1][0] - e[0][0];
                        var y = e[1][1] - e[0][1];
                        var z = e[1][2] - e[0][2];
                        var dx = (x - sele[2][0]);
                        dx *= dx;
                        var dy = (y - sele[2][1]);
                        dy *= dy;
                        var dz = (z - sele[2][2]);
                        dz *= dz;
 
                        return dx + dy + dz;
                    };
                    var d1 = distSq(a, seleExtent);
                    var d2 = distSq(b, seleExtent);
                    return d1 - d2;
                };
                extents.sort(sortFunc);
            }
 
            var reducedAtoms = [];
            // to reduce amount data transfered, just pass x,y,z,serial and elem
            for (let i = 0, il = atomlist.length; i < il; i++) {
                atom = atomlist[i];
                reducedAtoms[i] = {
                    x: atom.x,
                    y: atom.y,
                    z: atom.z,
                    serial: i,
                    elem: atom.elem
                };
            }
 
            var sync = !!(syncSurface);
            if (sync) { // don't use worker, still break up for memory purposes
 
                // to keep the browser from locking up, call through setTimeout
                var callSyncHelper = function callSyncHelper(i) {
                    return new Promise<void>(function (resolve) {
                        var VandF = GLViewer.generateMeshSyncHelper(type, extents[i].extent,
                            extents[i].atoms, extents[i].toshow, reducedAtoms,
                            totalVol);
                        //complicated surfaces sometimes have > 2^16 vertices
                        var VandFs = splitMesh({ vertexArr: VandF.vertices, faceArr: VandF.faces });
                        for (var vi = 0, vl = VandFs.length; vi < vl; vi++) {
                            VandF = {
                                vertices: VandFs[vi].vertexArr,
                                faces: VandFs[vi].faceArr
                            };
                            var mesh = GLViewer.generateSurfaceMesh(atomlist, VandF, mat);
                            mergeGeos(surfobj.geo, mesh);
                        }
                        self.render();
                        resolve();
                    });
                };
                var promises = [];
                for (let i = 0; i < extents.length; i++) {
                    promises.push(callSyncHelper(i));
                }
                return Promise.all(promises)
                    .then(function () {
                        surfobj.done = true;
                        return Promise.resolve(surfid);
                    });
 
                // TODO: Asynchronously generate geometryGroups (not separate
                // meshes) and merge them into a single geometry
            } else { // use worker
 
                var workers = [];
                Iif (type < 0)
                    type = 0; // negative reserved for atom data
                for (let i = 0, il = GLViewer.numWorkers; i < il; i++) {
                    var w = new Worker($3Dmol.SurfaceWorker);
                    workers.push(w);
                    w.postMessage({
                        'type': -1,
                        'atoms': reducedAtoms,
                        'volume': totalVol
                    });
                }
 
                return new Promise(function (resolve, reject) {
                    var cnt = 0;
 
                    var releaseMemory = function () {
                        Iif (!workers || !workers.length) return;
                        workers.forEach(function (worker) {
                            Iif (worker && worker.terminate) {
                                worker.terminate();
                            }
                        });
                    };
 
                    var rfunction = function (event) {
                        var VandFs = splitMesh({
                            vertexArr: event.data.vertices,
                            faceArr: event.data.faces
                        });
                        for (var i = 0, vl = VandFs.length; i < vl; i++) {
                            var VandF = {
                                vertices: VandFs[i].vertexArr,
                                faces: VandFs[i].faceArr
                            };
                            var mesh = GLViewer.generateSurfaceMesh(atomlist, VandF, mat);
                            mergeGeos(surfobj.geo, mesh);
                        }
                        self.render();
 
                        //    console.log("async mesh generation " + (+new Date() - time) + "ms");
                        cnt++;
                        Iif (cnt == extents.length) {
                            surfobj.done = true;
                            releaseMemory();
                            resolve(surfid); //caller of helper will resolve callback if present
                        }
                    };
 
                    var efunction = function (event) {
                        releaseMemory();
                        console.log(event.message + " (" + event.filename + ":" + event.lineno + ")");
                        reject(event);
                    };
 
                    for (let i = 0; i < extents.length; i++) {
                        var worker = workers[i % workers.length];
                        worker.onmessage = rfunction;
                        worker.onerror = efunction;
 
                        worker.postMessage({
                            'type': type,
                            'expandedExtent': extents[i].extent,
                            'extendedAtoms': extents[i].atoms,
                            'atomsToShow': extents[i].toshow
                        });
                    }
                });
            }
        };
 
        style = style || {};
        mat = GLViewer.getMatWithStyle(style);
        var surfobj: any = [];
        //save configuration of surface
        surfobj.style = style;
        surfobj.atomsel = atomsel;
        surfobj.allsel = allsel;
        surfobj.focus = focus;
        var promise = null;
        if (symmetries) { //do preprocessing
            var modelsAtomList = {};
            var modelsAtomsToShow = {};
            for (n = 0; n < this.models.length; n++) {
                modelsAtomList[n] = [];
                modelsAtomsToShow[n] = [];
            }
            for (n = 0; n < atomlist.length; n++) {
                modelsAtomList[atomlist[n].model].push(atomlist[n]);
            }
            for (n = 0; n < atomsToShow.length; n++) {
                modelsAtomsToShow[atomsToShow[n].model].push(atomsToShow[n]);
            }
            var promises = [];
            for (n = 0; n < this.models.length; n++) {
                Iif (modelsAtomsToShow[n].length > 0) {
                    surfobj.push({
                        geo: new Geometry(true),
                        mat: mat,
                        done: false,
                        finished: false,
                        symmetries: this.models[n].getSymmetries()
                        // also webgl initialized
                    });
                    promises.push(addSurfaceHelper(surfobj[surfobj.length - 1], modelsAtomList[n], modelsAtomsToShow[n]));
                }
            }
            promise = Promise.all(promises);
        }
        else {
            surfobj.push({
                geo: new Geometry(true),
                mat: mat,
                done: false,
                finished: false,
                symmetries: [new Matrix4()]
            });
            promise = addSurfaceHelper(surfobj[surfobj.length - 1], atomlist, atomsToShow);
        }
        this.surfaces[surfid] = surfobj;
        promise.surfid = surfid;
 
        if (surfacecallback && typeof (surfacecallback) == "function") {
            promise.then(function (surfid) {
                surfacecallback(surfid);
            });
            return surfid;
        }
        else {
            return promise;
        }
    };
 
    /**
     * Set the surface material to something else, must render change
    *  @function $3Dmol.GLViewer#setSurfaceMaterialStyle
     * @param {number} surf - Surface ID to apply changes to
     * @param {SurfaceStyleSpec} style - new material style specification
     @example
     $.get("data/9002806.cif",function(data){
        viewer.addModel(data);
        viewer.setStyle({stick:{}});
        let surf = viewer.addSurface("SAS");
        surf.then(function() {
            viewer.setSurfaceMaterialStyle(surf.surfid, {color:'blue',opacity:0.5});
            viewer.render();
            });
       });
     */
    public setSurfaceMaterialStyle(surf, style) {
        adjustVolumeStyle(style);
        Iif (this.surfaces[surf]) {
            var surfArr = this.surfaces[surf];
            surfArr.style = style;
            for (var i = 0; i < surfArr.length; i++) {
                var mat = surfArr[i].mat = GLViewer.getMatWithStyle(style);
                surfArr[i].mat.side = FrontSide;
                if (style.color) {
                    surfArr[i].mat.color = style.color;
                    surfArr[i].geo.colorsNeedUpdate = true;
                    const c = CC.color(style.color);
                    surfArr[i].geo.setColors(function () { return c; });
                }
                else Iif (mat.voldata && mat.volscheme) {
                    //convert volumetric data into colors
                    const scheme = mat.volscheme;
                    const voldata = mat.voldata;
                    const cc = CC;
                    const range = scheme.range() || [-1, 1];
                    surfArr[i].geo.setColors(function (x, y, z) {
                        let val = voldata.getVal(x, y, z);
                        let col = cc.color(scheme.valueToHex(val, range));
                        return col;
                    });
                }
                surfArr[i].finished = false; // trigger redraw
            }
        }
        return this;
    };
 
    /**
     * Return surface object
     * @function $3Dmol.GLViewer#getSurface
     * @param {number} surf - surface id
     */
    public getSurface(surf) {
        return this.surfaces[surf];
    };
 
    /**
     * Remove surface with given ID
     * @function $3Dmol.GLViewer#removeSurface
     * @param {number} surf - surface id
     */
    public removeSurface(surf) {
        var surfArr = this.surfaces[surf];
        for (var i = 0; i < surfArr.length; i++) {
            Iif (surfArr[i] && surfArr[i].lastGL) {
                Iif (surfArr[i].geo !== undefined)
                    surfArr[i].geo.dispose();
                Iif (surfArr[i].mat !== undefined)
                    surfArr[i].mat.dispose();
                this.modelGroup.remove(surfArr[i].lastGL); // remove from scene
            }
        }
        delete this.surfaces[surf];
        this.show();
        return this;
    };
 
    /** Remove all surfaces.
     * @function $3Dmol.GLViewer#removeAllSurfaces */
    public removeAllSurfaces() {
        for (var n in this.surfaces) {
            Iif (!this.surfaces.hasOwnProperty(n)) continue;
            var surfArr = this.surfaces[n];
            for (var i = 0; i < surfArr.length; i++) {
                Iif (surfArr[i] && surfArr[i].lastGL) {
                    Iif (surfArr[i].geo !== undefined)
                        surfArr[i].geo.dispose();
                    Iif (surfArr[i].mat !== undefined)
                        surfArr[i].mat.dispose();
                    this.modelGroup.remove(surfArr[i].lastGL); // remove from scene
                }
            }
            delete this.surfaces[n];
        }
        this.show();
        return this;
    };
 
    /** return Jmol moveto command to position this scene */
    public jmolMoveTo() {
        var pos = this.modelGroup.position;
        // center on same position
        var ret = "center { " + (-pos.x) + " " + (-pos.y) + " " + (-pos.z)
            + " }; ";
        // apply rotation
        var q = this.rotationGroup.quaternion;
        ret += "moveto .5 quaternion { " + q.x + " " + q.y + " " + q.z
            + " " + q.w + " };";
        // zoom is tricky.. maybe i would be best to let callee zoom on
        // selection?
        // can either do a bunch of math, or maybe zoom to the center with a
        // fixed
        // but reasonable percentage
 
        return ret;
    };
 
    /** Clear scene of all objects
     * @function $3Dmol.GLViewer#clear
     * */
    public clear() {
        this.removeAllSurfaces();
        this.removeAllModels();
        this.removeAllLabels();
        this.removeAllShapes();
        this.show();
        return this;
    };
 
    // props is a list of objects that select certain atoms and enumerate
    // properties for those atoms
    /**
     * Add specified properties to all atoms matching input argument
     * @function $3Dmol.GLViewer#mapAtomProperties
     * @param {Object} props, either array of atom selectors with associated props, or function that takes atom and sets its properties
     * @param {AtomSelectionSpec} sel  - subset of atoms to work on - model selection must be specified here
         @example
         $.get('../test_structs/b.sdf', function(data){
                  viewer.addModel(data,'sdf');
                  let props = [];
                  //make the atom index a property x
                  for(let i = 0; i < 8; i++) {
                    props.push({index:i,props:{'x':i}});
                  }
                  viewer.mapAtomProperties(props);
                  viewer.setStyle({sphere:{colorscheme:{gradient:'roygb',prop:'x',min:0,max:8}}});
                  viewer.zoomTo();
                  viewer.render();
                });
     */
    public mapAtomProperties(props, sel) {
        sel = sel || {};
        var atoms = this.getAtomsFromSel(sel);
 
        if (typeof (props) == "function") {
            for (let a = 0, numa = atoms.length; a < numa; a++) {
                let atom = atoms[a];
                props(atom);
            }
        }
        else {
            for (let a = 0, numa = atoms.length; a < numa; a++) {
                var atom = atoms[a];
                for (let i = 0, n = props.length; i < n; i++) {
                    let prop = props[i];
                    Iif (prop.props) {
                        for (var p in prop.props) {
                            Iif (prop.props.hasOwnProperty(p)) {
                                // check the atom
                                Iif (this.atomIsSelected(atom, prop)) {
                                    Iif (!atom.properties)
                                        atom.properties = {};
                                    atom.properties[p] = prop.props[p];
                                }
                            }
                        }
                    }
                }
            }
        }
        return this;
    };
 
 
    /**
     * Synchronize this view matrix of this viewer to the passed viewer.
     * When the viewpoint of this viewer changes, the other viewer will
     * be set to this viewer's view.
     * @function $3Dmol.GLViewer#linkViewer
     * @param {$3Dmol.GLViewer} otherview
     */
    public linkViewer(otherviewer) {
        this.linkedViewers.push(otherviewer);
        return this;
    };
 
    /**
     * Return the z distance between the model and the camera
     * @function $3Dmol.GLViewer#getPerceivedDistance
     * @return {number} distance
     */
    public getPerceivedDistance() {
        return this.CAMERA_Z - this.rotationGroup.position.z;
    };
 
    /**
     * Set the distance between the model and the camera
     * Essentially zooming. Useful while stereo rendering.
     * @function $3Dmol.GLViewer#setPerceivedDistance
     */
    public setPerceivedDistance(dist) {
        this.rotationGroup.position.z = this.CAMERA_Z - dist;
    };
 
    /**
     * Used for setting an approx value of eyeSeparation. Created for calling by StereoViewer object
     * @function $3Dmol.GLViewer#setAutoEyeSeparation
     * @return {number} camera x position
     */
    public setAutoEyeSeparation(isright, x) {
        var dist = this.getPerceivedDistance();
        Iif (!x) x = 5.0;
        if (isright || this.camera.position.x > 0) //setting a value of dist*tan(x)
            this.camera.position.x = dist * Math.tan(Math.PI / 180.0 * x);
        else
            this.camera.position.x = -dist * Math.tan(Math.PI / 180.0 * x);
        this.camera.lookAt(new Vector3(0, 0, this.rotationGroup.position.z));
        return this.camera.position.x;
    };
 
    /**
     * Set the default cartoon quality for newly created models.  Default is 5.
     * Current models are not affected.
     * @number quality, higher results in higher resolution renders
     * @function $3Dmol.GLViewer#ui.setDefaultCartoonQuality
     */
    public setDefaultCartoonQuality(val) {
        this.config.cartoonQuality = val;
    };
 
}
 
 
/**
 * Create and initialize an appropriate viewer at supplied HTML element using specification in config
 @function $3Dmol.createViewer
 * @param {Object | string} element - Either HTML element or string identifier
 * @param {ViewerSpec} [config] Viewer configuration
 * @return {$3Dmol.GLViewer} GLViewer, null if unable to instantiate WebGL
 * @example
   var viewer = $3Dmol.createViewer(
     'gldiv', //id of div to create canvas in
     {
       defaultcolors: $3Dmol.elementColors.rasmol,
       backgroundColor: 'black'
     }
   );
 *                        
 */
export function createViewer(element, config?) {
    Iif (typeof (element) === "string")
        element = $("#" + element);
    Iif (!element) return;
 
    config = config || {};
    //try to create the  viewer
    try {
        var viewer = new GLViewer(element, config);
        return viewer;
    }
    catch (e) {
        throw "error creating viewer: " + e;
    }
};
 
/**
 * Create and initialize an appropriate a grid of viewers that share a WebGL canvas
 @function $3Dmol.createViewerGrid
 * @param {Object | string} element - Either HTML element or string identifier
 * @param {GridSpec} [config] - grid configuration
 * @param {ViewerGridSpec} [viewer_config] - Viewer specification to apply to all subviewers
 * @return [[$3Dmol.GLViewer]] 2D array of GLViewers
 * @example                    
   var viewers = $3Dmol.createViewerGrid(
     'gldiv', //id of div to create canvas in
     {
       rows: 2,
       cols: 2,
       control_all: true  //mouse controls all viewers
     },
     { backgroundColor: 'lightgrey' }
   );
   $.get('data/1jpy.cif', function(data) {
     var viewer = viewers[0][0];
     viewer.addModel(data,'cif');
     viewer.setStyle({sphere:{}});
     viewer.zoomTo();
     viewer.render( );
 
     viewer = viewers[0][1];
     viewer.addModel(data,'cif');
     viewer.setStyle({stick:{}});
     viewer.zoomTo();     
     viewer.render( );
     
     viewer = viewers[1][0];
     viewer.addModel(data,'cif');
     viewer.setStyle({cartoon:{color:'spectrum'}});
     viewer.zoomTo();     
     viewer.render( );
     
     viewer = viewers[1][1];
     viewer.addModel(data,'cif');
     viewer.setStyle({cartoon:{colorscheme:'chain'}});
     viewer.zoomTo();     
     viewer.render();
     
     
   });
     
 */
export function createViewerGrid(element, config?, viewer_config?) {
    Iif (typeof (element) === "string")
        element = $("#" + element);
    Iif (!element) return;
 
    config = config || {};
    viewer_config = viewer_config || {};
 
    var viewers = [];
    //create canvas
    var canvas = document.createElement('canvas');
 
    viewer_config.rows = config.rows;
    viewer_config.cols = config.cols;
    viewer_config.control_all = config.control_all != undefined ? config.control_all : false;
    $(element).append($(canvas));
 
    //try to create the  viewer
    try {
        for (var r = 0; r < config.rows; r++) {
            var row = [];
            for (var c = 0; c < config.cols; c++) {
                viewer_config.row = r;
                viewer_config.col = c;
                viewer_config.canvas = canvas;
                viewer_config.viewers = viewers;
                viewer_config.control_all = config.control_all;
                var viewer = createViewer(element, viewer_config);
                row.push(viewer);
            }
            viewers.unshift(row); //compensate for weird ordering in renderer
        }
    } catch (e) {
        throw "error creating viewer grid: " + e;
    }
 
    return viewers;
};
 
 
/* StereoViewer for stereoscopic viewing
  @function $3Dmol.createStereoViewer
* @param {Object | string} element - Either HTML element or string identifier
* 
*/
export function createStereoViewer(element) {
    var that = this;
    Iif (typeof (element) === "string")
        element = $("#" + element);
    Iif (!element) return;
 
    var viewers = createViewerGrid(element, { rows: 1, cols: 2, control_all: true });
 
    this.glviewer1 = viewers[0][0];
    this.glviewer2 = viewers[0][1];
 
    this.glviewer1.setAutoEyeSeparation(false);
    this.glviewer2.setAutoEyeSeparation(true);
 
    this.glviewer1.linkViewer(this.glviewer2);
    this.glviewer2.linkViewer(this.glviewer1);
 
    var methods = Object.getOwnPropertyNames(this.glviewer1.__proto__) //get all methods of glviewer object
        .filter(function (property) {
            return typeof that.glviewer1[property] == 'function';
        });
 
    for (var i = 0; i < methods.length; i++) { //create methods of the same name
        this[methods[i]] = (function (method) {
            return function () {
                var m1 = this.glviewer1[method].apply(this.glviewer1, arguments);
                var m2 = this.glviewer2[method].apply(this.glviewer2, arguments);
                return [m1, m2];
            };
        })(methods[i]);
    }
 
    //special cased methods
    this.setCoordinates = function (models, data, format) { //for setting the coordinates of the models
        for (var i = 0; i < models.length; i++) {
            models[i].setCoordinates(data, format);
        }
    };
 
    this.surfacesFinished = function () {
        return this.glviewer1.surfacesFinished() && this.glviewer2.surfacesFinished();
    };
 
    this.isAnimated = function () {
        return this.glviewer1.isAnimated() || this.glviewer2.isAnimated();
    };
 
    this.render = function (callback) {
        this.glviewer1.render();
        this.glviewer2.render();
        Iif (callback) {
            callback(this); //call only once
        }
    };
 
    this.getCanvas = function () {
        return this.glviewer1.getCanvas(); //same for both
    };
 
};