All files / js sp_lev.js

87.1% Statements 4351/4995
74.83% Branches 1668/2229
86.01% Functions 203/236
87.1% Lines 4351/4995

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 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 499673x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 231147x 1381479x 1381479x   231147x 73x 73x 73x 73x 73x 73x 73x 174x 174x 174x 174x 174x 174x 174x 174x 174x 86x 86x 86x 86x 64x 64x 86x 42x 42x 86x 44x 44x 44x 86x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 86x 174x     174x     174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 282x 282x 282x 282x 282x 118x 118x     118x 118x 118x 118x 118x 118x     118x 118x 118x 118x 118x 282x 282x 194x           194x 194x 194x 194x 282x 88x 88x 88x 88x 88x 88x 88x 88x 282x 282x 20x       20x 20x 20x 20x 282x       282x 282x 282x 118x 118x 118x 118x 394x 3345x 15x 3345x 3330x 3330x   3330x 3330x 1354x 1354x 1354x 3330x 1976x 1976x 1976x 1976x 427x 1976x 1549x 21x 21x 1976x 3330x 3345x 109x 109x 109x 1x 1x 1x 3345x 394x 394x 118x 118x 173x 173x 174x 174x 1x 1x 1x 1x 173x 173x 173x 173x 173x 173x 174x 2261x 129915x 129915x 129915x 126021x 129915x 126021x 126021x 126021x 126021x 126021x 126021x 126021x 126021x 126021x 126021x           126021x 126021x 126021x 126021x 126021x 126021x 126021x 793x 793x 793x 793x 793x 126021x 24174x 24174x 126021x 126021x 126021x 129915x 2261x 173x 174x 63x 63x 63x 173x 174x 73x 73x 73x 73x 57x 57x 57x 57x 57x       57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x                   57x 217x 217x 217x 217x 217x 217x 217x 71409x 71409x 71409x 71409x 71409x 217x 217x 6304x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 103907x 6304x 217x 217x 217x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 10x 10x 10x 10x                                       73x 73x 73x 1879x 1879x 73x 819x 819x 73x 39x 39x 73x 192x 192x 192x 192x 192x 9732x 168814x 168814x 9732x 192x 192x 192x 5355x 91331x 91331x 91331x 192x 124x 124x 192x 3x 3x 192x 192x 39839x 39839x 91139x 5163x 192x 73x 19x 19x 19x 19x 1231x 19385x 993x 993x 19385x 1231x 19x 19x 73x 1x 1x 1x 13x 741x 741x 741x 741x 4x 13x 1x 73x 5x 5x 5x 5x 5x 5x 5x 5x 327x 6741x 6741x 6741x 1364x 6741x 6741x 1364x 1364x 6741x     6741x 6741x     6741x 6741x 327x 5x 5x 73x 2292x     2292x 2292x 797259x 797259x 797259x 797259x 797259x 2292x 2292x 73x 73x 73x                                             73x 73x 73x 73x 73x 73x 342x 342x 342x 342x 342x 338x 338x 342x     342x 342x 73x 26x 26x 26x 2080x 43680x 43680x 2080x 26x 26x 73x 76x 76x 76x 76x 76x 76x 73x 56x 56x 73x     73x     73x 22x 22x 22x 22x 22x 22x 22x 73x                     73x 422x 422x 422x 422x 422x 13x 422x 409x 409x 422x 422x 73x 29x 29x 29x 29x 29x 29x 29x 73x             73x             73x 498034x 492955x 498034x 365519x 358115x 358115x 498034x 127436x 127436x 492955x 498034x 73x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 4040x 74625x 74625x 74625x 4040x 56x 56x 73x 57x 57x 57x 57x 57x 1254x 99066x 99066x 1254x 57x 57x 73x 2x 2x 2x 2x 2x 2x 13x 75x 75x 57x 57x 75x 13x 2x 2x 73x 73x 73x 30x 30x           73x 73x 59x 59x 73x 73x     73x 73x     73x 73x     73x 73x 65x 65x 73x 73x 4x 4x 73x 73x     73x 73x     73x 73x     73x 73x     73x 73x 22x 22x 73x 73x     73x 73x 11x 11x 73x 73x 411x 411x 73x 73x 29x   73x 73x     73x 73x     73x 73x 7x 7x 7x 7x 7x 7x 7x 7x 7x 15127x 15127x 15127x 5567x 15127x 15127x 3780x 3780x 15127x     15127x 7x 73x 73x 2x     2x 73x 73x 3x 3x 73x 73x 57x 73x 73x 73x 73x 73x 216x 562x 562x 562x 216x 216x 73x 73x 73x 73x       73x 73x 73x 73x 73x 73x       73x 73x 73x 73x 2x 2x 2x 2x 454x 2x 2x 2x 454x 2x 2x 73x 73x 73x 6x 6x 6x 6x 73x 73x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 73x 73x 73x 73x 73x 73x 73x 73x 11x 10x 11x 73x 73x 73x 11x 11x 11x 11x 11x 11x 11x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 9x 9x 11x 11x 8x 8x 8x 8x 8x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 8x 8x 3x 3x 3x 3x 3x 8x 8x 11x 11x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 11x 73x 73x 73x 73x 73x 73x 73x 579x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 578x 73x 73x 73x 73x 73x       73x 73x           73x 73x           73x 73x 603x 579x 579x 579x 579x 579x 579x 1x 1x 579x 579x 603x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 9283x 9283x 9283x 4920x 4920x 305x 305x 4919x 123x 123x 4492x 4492x 4731x 2593x 104x 104x 2593x 28x 28x 2593x 4920x 1899x 1899x 2461x 4920x 2287x 2287x 2287x 1156x 1156x 1156x 1156x 581x 2287x 2287x 949x 949x 949x         599x 514x 514x 514x 35x 949x 949x 2905x 2905x 2905x 1582x 1582x 1582x 1582x 935x 2905x 2905x 113x 113x 113x 113x 113x 5030x 5030x 5030x 88x 88x 4942x 5030x 5030x 5030x 5030x 2124x 2124x 2124x 2124x 1168x 2124x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x   316x 3672x 3672x 3672x 3672x 3672x 3672x 3672x 3672x 3672x 3672x 3672x 4x 4x 4x 4x 4x 100x 100x 97x 97x 97x 3x 3x 100x 100x 100x 100x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x       4x 4x 4x 4x 3x 3x   100x 1118x 1118x 1068x 1068x 1068x 50x 896x 1118x 1118x 1118x 1118x 82x 82x 82x 82x 82x   1118x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 1295x 1295x 1011x 1295x 1011x 1295x 3970x 3970x 3970x 3960x 3960x 3970x 10x 10x 10x 3970x 10x 10x 3970x 3960x 3960x 3960x 3970x 3970x   3970x 3960x 3960x 3960x 3960x 175821x     175821x 175821x 175821x 175821x 175821x 3960x 3970x 10x 10x 10x 10x 26x     26x 26x 26x 26x 26x 10x 10x 3970x 14885x 14885x 7428x 14885x 7428x 14885x 7109x 7109x 14885x 319x 324x 324x 324x 324x 319x 319x 14885x 989x 989x 7428x 7428x 7428x 7428x 7428x 14885x                                                                                                                                               140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x               140x 140x 140x 140x 2x 2x 2x 2x 2x 2809x 2809x 2809x 2809x 39396x 39396x 36632x 36632x 45x 2809x 2809x 2809x 2809x 2809x 2809x 2809x 2809x 2809x 2809x 2809x 2452x 2809x 2943x 2943x 2943x 2942x 2809x 2809x 131x 2943x 926x 926x 926x 926x 2237x 2237x 2237x 922x 372x 926x 926x 926x 926x 716x 716x 926x 1046x 1046x 1046x 926x 1046x 1046x 1421x 1421x 1421x 1421x 657x 372x 372x 926x 4081x 4081x 4081x 4081x 4081x 4081x 4081x 4081x 3988x 3988x 3988x 3988x 3890x 3890x 3890x 3890x 3755x 3755x 3755x 3755x 3632x 4081x 4558x 4558x 4558x 4558x 4558x 4558x 926x 926x 4558x 1031x 1031x 1031x 9221x 63434x 63434x 63434x 9221x 1031x 1031x 129x 129x 129x 129x 129x 2709x 216720x 216720x 1002x 1002x 1002x 216720x 2369x 2369x 2369x 2369x 1739x 1739x 2369x 1002x 2709x 129x 40x 40x 40x 40x 1648x 1648x 72x 72x 72x 1648x 1648x 6592x 6592x 6592x 1648x 1648x 1648x 1648x 1648x 1648x 18x 18x 18x 18x 18x 1648x 1648x 1648x 646x 646x 646x 646x 646x       646x 646x 646x 646x 82x 82x 82x 82x 82x 82x 82x 4x 4x 1x     1x 4x 3x 3x 4x       4x 82x 294x 294x 294x 294x 70x 22x 70x 70x 22x 294x 70x 30x 70x 70x 30x 294x 89x 17x 89x 89x 17x 294x 65x 13x 65x 65x 13x 294x 294x 294x 294x 82x 82x 82x 328x 328x 82x 294x 82x 294x 294x 294x 294x 212x 82x 2942x 2942x 2942x 2942x 2942x 14x 2942x 15x 2942x 2942x 13x 2942x 2942x 75x 2942x 1x 2942x 1x 2942x 2942x 2809x 2942x 2942x 73x 73x 73x 73x 391x 391x 391x 391x 391x 391x 391x 73x 128x 128x 128x 128x 128x 128x 128x 128x 4993x 4993x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 70x 70x 199x 4993x 4993x 1774x 1774x 1774x 1774x 1774x 887x 887x 887x 887x 887x 887x 887x 887x 887x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1030x 1030x 1030x 1030x 887x 887x 887x 887x 887x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 887x 812x 812x 812x 812x 812x 812x 812x 812x 812x 812x 812x 812x 737x 737x 812x 887x 812x 812x 812x 812x 812x 75x 887x 126829x 126829x 126829x 1x 1x 126829x 126829x 8x 8x 8x 8x 8x 14x 14x 14x 14x 1078x 22638x 22638x 22638x   22638x 22638x 22638x 22638x 22638x 22638x 22638x 22638x 1078x 14x 202069x 202069x 202069x 202069x 202069x 195733x 195733x 190882x 195733x 195733x 195733x 202069x 202069x 2x 2x 2x 2x 2x 78x 780x 780x 780x 780x 780x 780x 760x 760x 258x 258x 760x 266x 266x 760x 236x 236x 760x   760x 760x 780x 78x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x             4x 4x 202x 2690x 2690x 2690x 2690x 202x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 231x 4389x 4389x 231x 3x 3x 3x 129x 129x 129x 129x 1432x 1432x 2508x 4256x 4104x 4104x 4256x 2508x 1432x 1432x 1432x 129x 129x 129x 3x 4x 73x 73x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 104x 104x 104x 97x 97x 104x 104x 104x 104x 104x 104x 104x 104x 138x 138x 28x 28x 28x 138x 138x 14x 14x 14x 138x 4x 124x 2x 2x 2x       2x 2x       2x 120x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 138x 73x 120x 120x 120x 120x 120x 9240x 194040x 194040x 194040x 194040x 194040x 194040x 194040x 194040x 9240x 120x 11x 11x 11x 304x 304x 304x 304x 304x 304x 304x 116x 116x 116x 116x 116x 116x 116x 1864x 1864x 1864x 1864x 1864x 2x 2x 2x 2x 2x 2x 2x 8x 8x 2x 2x 2x 2x 2x 160x 27x 27x 27x 160x 2x 2x 2x 2x 2x 42x 25x 25x 25x 42x 2x 2x 92x 1012x 1012x 1012x 4x 4x 2x 2x 2x 2x 2x 2x 1012x 4x 2x 2x 2x 2x 2x 2x 4x 1012x 92x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 114x 114x 114x 114x 114x               114x 114x 59114x 59114x 59114x 59114x 59114x 59054x 59114x     59114x 31x 31x 59114x 4320x 4320x 4320x 59114x 210x 210x 59114x 3x 3x 54516x 59114x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 1319x 73x 73x 73x 73x 1764x 1764x 1764x 18x 18x 1764x 1764x 3321x 3321x 3321x 3321x 3321x 3321x 3321x 3321x 3321x 3321x 200x 200x 200x 200x 3321x 3121x 3121x 3121x 3121x 3121x 3121x 3321x     3321x 3321x 3321x 10527x 200x 200x 200x 200x 200x 10527x 10327x 10327x 10327x 10527x 10527x 10527x 10527x 10527x 10527x 10527x 10527x 10527x     10527x 3285x 3285x 3285x 10527x 7242x 7242x 7242x 3273x 2736x 46512x 46512x 46512x       46512x 2736x 1806x 18x 18x 18x 1806x 18x 3321x 737x 737x 737x 737x 737x 737x 737x 7267x 7267x 7267x 737x 737x 737x 737x 405x 405x 405x 405x 549x 549x 549x 549x 549x 549x 92x 92x 549x 549x 43x 43x 549x 20x 20x 549x 16x 16x 549x 24x 24x 549x 26x 26x 549x 549x 52x 52x 549x 18x 18x 549x 22x 22x 549x 20x 20x 549x 216x 549x 405x 405x 405x 73x                                     73x 949x 949x 541x 541x 949x     949x 3x 3x 3x 405x 949x 73x 137x 137x 137x 179x 179x 179x 179x 179x 29x 29x 179x 8x 8x 8x 179x 179x 16x 16x 16x 179x 179x 11x 11x 11x 179x 115x 179x 137x 137x 137x 18x 18x 18x 18x 18x 18x 18x 1368x 27360x 27360x 1368x 18x 18x 18x 243x 243x 243x 18x 117x 117x 117x 117x 117x 18x 12x 12x 12x 18x 92x 92x 92x 18x 136x 136x 136x 18x 137x 137x 137x         137x 137x 18x 73x 73x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 18x 18x 18x 28x 10x 10x 10x 10x 10x 10x 10x 10x 28x 28x     28x 28x 28x     28x 28x 28x 28x 28x 28x 28x   28x 28x 28x 28x 28x 28x 28x 28x 28x 26x 26x 26x 26x 26x 26x 26x 28x 8x 8x 28x 28x 28x 73x 73x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x       5x 5x 5x 73x 73x 9x 9x 9x                                                                                                                                 73x                                               73x 73x 125x 125x 125x 125x 326x 326x 326x 57x 57x 326x 42x 42x 326x 18x 18x 326x 10x 10x 326x 1x 1x 326x     326x     326x 121x 121x 326x 3x 3x 326x 2x 2x 326x 7x 7x 326x 12x 12x 326x 7x 7x 326x 3x 3x 326x     326x 3x 3x 326x 24x 24x 326x 7x 7x 326x     326x     326x 3x 3x 326x 3x 3x 326x 3x 3x 326x     326x     326x   326x   326x 326x 125x 73x 159x 159x 159x 87495x 87495x 87495x 41338x 41338x 87495x 159x 73x 132x 132x 73x 27x 27x 314x 314x 238x 314x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 157x 288x 288x 288x 288x 288x 157x 157x 81x 81x 81x 81x 81x 81x 81x 157x 63x 63x 63x 63x 63x 63x 63x 157x 157x 157x 157x 73x 73x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 73x 4352x 4352x 4352x 4352x 4352x 4352x 4352x 73x 32x 32x 32x 32x 32x 1704x 1704x 1704x 1704x 1704x 1456x 1456x 1456x 1456x 1456x 584x     584x 584x 1456x 16x 16x 160x 1456x 73x 2x 2x 2x 2x 100x 1500x 488x 1500x 1500x 1500x 1500x 1500x 1500x 212x 212x 1500x 100x 2x 2x 2x 2x 2x 2x 2x 2x 2x 100x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 1500x 100x 2x 73x 129x 129x 129x 9746x 194875x 8x 8x 8x 194875x 9746x 129x 8x 8x 129x 624x 12480x 12480x 95x 95x 12480x 624x 129x 12x 12x 960x 20160x 20160x 15637x 15637x 20160x 960x 12x 15718x 15718x 15718x 15718x 6x 6x 6x 6x 6x 6x 31184x 31184x 6x 6x 6x 6x 6x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 3898x 31184x 31184x 31184x 31184x 3892x 3892x 3892x 3898x 6x 1955x 1955x 1952x 1952x 1952x 1955x 140327x 2583822x 2583822x 140327x 1955x 1952x 1955x 72906x 1326626x 1326626x 1326626x 1952x 1952x 1952x 1952x 1952x 325305x 325305x 1324674x 70954x 1955x 3x 3x 3x 3x 3x 3x 3x 3x 1949x 1949x 1949x 1949x 1949x       1949x 1949x 1949x 1949x       1949x 1949x 1949x 1949x       1949x 1949x 1949x 1949x       1949x 3x 3x 3x 3x 3x 3x 3x 3x 3x                 3x 3x 3x 3x 3x         3x           3x 3x 6x 6x 249x 5194x 5194x 3x 3x 3x 3x 3x 3x 5194x 249x 249x 3x 3x 82x 82x 82x 82x 547x 547x 547x 547x 547x 8x 8x 547x 74x 82x 129x 129x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 96x 325x 273x 273x 325x 325x 325x 325x 325x 96x 129x 129x 129x 129x 129x 129x 129x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 129x 129x 129x 79x 1659x 1659x 139x 139x 1659x 79x 1x 1x 1x 129x 129x 129x 5x 20x 20x 20x 5x 1x 1x 1x 1x 1x 1x 1x 129x 129x 129x 129x 30x 30x 30x 30x 30x 129x 129x 30x 30x 30x 30x 30x 30x 30x 30x 129x 129x 129x 129x 129x 129x 129x 157x 157x 157x 47x 47x 47x 47x 47x 47x 47x 157x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 157x 157x 41x 41x 41x 41x 41x 41x 157x 157x 157x 64x 37x 37x 37x 37x 37x 64x 48x 48x 48x 48x 48x 64x 157x   157x 157x 129x 8x 8x 129x 129x 13x 13x 13x 13x 28x 28x 28x 24x 24x 24x 24x 24x     24x 28x 13x 6x 13x 7x 7x 13x 13x 13x 13x 13x 2x 2x 13x 13x 129x 2x 2x 129x 129x 129x 73x 129x 129x 129x 129x 129x 75x 75x 75x 75x 75x 75x 75x 75x 4723x 4723x 75x 75x 75x 75x 68484x 3x 30816x     30816x 3x 3x 3x 75x 75x 69504x 2x 2966x 1x 1x 1x 1x 1x 1x 75x 75x 75x 52x 3639x 34752x 34752x 34752x 34752x 34752x 34752x 34752x 3639x 52x 75x 50x 1732x 34242x 34242x 34242x 34242x 34242x 34242x 34242x 1732x 50x 75x 3006x 3006x 3006x 2998x 3006x 75x 75x 576x 576x 352x 352x 352x 256x 256x 352x 576x 380x 380x 380x 265x 265x 380x 75x 75x 75x 211x 211x 75x 75x 75x 75x       75x 75x 75x 1971x 454x 1104x 75x 75x 1955x 1955x 1955x 1955x 1955x 1955x 1955x 1955x 16x 16x 16x 1955x           1955x 1955x 75x 75x 75x 75x 117x 117x 117x 117x 75x 75x 75x 150x 150x 75x 75x 29x 29x 29x 75x 35x 35x 35x 75x 75x 3x 3x 75x 129x 73x 73x 256x 256x 129x 129x 129x 129x 129x 256x 129x 129x 256x 127x 127x 129x 129x 129x 239x 106x 104x 104x 106x 106x 256x 129x 256x 129x 256x 73x 129x 129x 10320x 216720x 216720x 216720x 25060x 25060x 25060x 6x 6x 6x 25060x 25060x 25060x 25060x 25060x 25060x 25060x 25060x 216720x 10320x 129x 11613x 11613x 11613x 11613x 11613x 7x 7x 553x 11613x 11613x 1857x 1857x 11613x     1857x 1857x 11613x 11613x 553x 7x 99x 99x 99x 7x 73x 10x 10x 10x 10x 73x 82x 82x 82x 82x 157x 157x 157x 157x 157x 157x 107x 107x 107x 107x 153x 50x 50x 157x 157x 157x 157x 157x 157x 157x 157x 10x 10x 10x 10x 10x 10x 10x 10x 10x 147x 157x 157x 157x 157x 157x 157x 79x 147x 157x 73x 147x 147x 147x 143x 143x 143x 143x 147x 4x 4x 4x     147x 147x 73x 10x 10x 10x 10x 10x 10x 10x 10x           10x 10x 73x 73x 117x 117x 117x 117x 113x 113x 113x 113x 117x 4x 4x 4x 4x 117x 117x 117x 117x 117x 92x 92x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 73x 73x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 622x 622x 728x 106x 106x 106x 106x 106x 728x 728x 82x 82x 82x 82x 82x 82x 82x 82x 646x 725x 646x 646x 728x 73x 73x 402x 402x 402x 402x 402x 259x 259x 259x 259x 259x 259x 108823x 108823x 108823x 108823x 108823x 108823x 259x 259x 259x 402x     143x 143x 402x 143x 143x 402x 402x 402x 402x 402x 402x 402x 402x 402x 402x       143x 370x 57x 393x 86x 86x 86x 86x 393x 143x 143x 393x 9x 9x 9x 143x 143x 143x 143x 402x 73x 73x 949x 949x 949x 949x 949x 949x 395x 949x 21x 21x 21x 21x 21x 21x 21x 554x 533x 533x 533x 533x 533x 1222x 1222x 1222x 688x 688x 688x 1222x 1222x 1x 1x 1x 533x 533x 533x 533x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 541x   541x 541x 541x 541x 949x     949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 949x 13x 13x 13x 949x 15x 15x 949x 949x 949x 949x 949x 938x 938x 949x 25x 25x 949x 949x 949x 930x 930x 930x 930x 930x 930x 930x 930x 930x             930x 949x 949x 949x 73x 73x 945x 945x 945x 945x 945x 945x 945x 945x 945x 945x 945x 945x 945x 945x 79x 299x 44x 44x 44x 44x 299x 79x 945x 945x 354174x 354174x 354174x 354174x 354174x 354174x 1x 28x 164x 164x 164x 164x 164x                 945x 676x 676x 676x 24851x 24851x   676x 73x 73x 73x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 1499x 1499x 1499x 1499x 1499x         1499x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 2287x 945x 945x 182x 182x 945x 325x 325x 325x 325x 325x 325x 325x 325x 945x 945x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 2x 2x 335x 33x 33x 33x 33x 33x 33x 33x 33x 333x 205x 205x 205x 5x 5x 5x 5x 5x 5x 5x 205x 205x 335x 945x 945x 945x       2287x 739x 739x     739x       739x 739x 739x 1342x 603x 603x 603x 2287x   2287x 240x 240x 2287x 2287x 2287x 2287x 395x 395x 2287x 2287x 91x 91x 91x 91x 91x 91x 91x 91x 91x 91x 2287x 2287x 2287x 2287x 2287x 2x 2287x 238x   238x 238x 238x 238x 2287x 2287x 22x 22x 2287x 2287x 2287x 2287x 2287x 25x 25x 25x 2287x 2287x 2287x 2287x 2287x 2287x   2287x 2x 2x 2x 2287x 2x 2x 2287x     2287x 2287x 2287x 2287x 2287x 2287x 46x 46x 46x 46x 46x 46x 46x 46x 46x 2287x 29x 29x 29x 29x 2287x 120x 120x 120x 120x 120x 120x 120x 120x 120x 120x 2287x 2287x 2287x 2287x 2287x 2287x 95x 19x 19x 19x 19x 95x 95x 95x 95x 95x 95x 114x 114x 114x 114x 95x 95x 19x 19x 19x 95x 95x 95x 69x 69x 69x 69x 69x 69x 69x 95x 95x 95x 2287x 2287x 2287x 2287x 2287x 2287x 2241x 2241x 2241x 2241x 2241x 59x 59x 59x     59x 2241x 2287x 2287x 2287x 2287x 25x 25x 25x 25x 25x 2287x 120x 120x 2287x 2287x 2287x 2287x 2287x 2287x 58x 58x 2287x 2287x 58x 58x 2287x 2287x 2287x 2287x 73x 73x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 643x 643x 2905x 1789x 1789x 1789x 1789x 83x 1789x 1706x 1706x 1706x 1789x 1789x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 1789x 1789x 1789x 1789x 1789x 1789x 1789x 1789x 1789x 2905x 643x 643x 2905x 2905x 2905x     2905x 2905x 2905x                       2905x 1159x 2905x 1746x 1746x 1746x 18x 18x 1746x     1746x 1746x 1746x 1746x 2905x 2905x 2905x 58x 58x 58x 58x 58x 58x 2905x 2905x     2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 96x 96x 96x 2905x 4x 2809x 2805x 2805x 2905x 2905x 2905x 2905x 2905x 2905x 2057x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 6x 6x 6x 6x 6x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x 2905x       2905x       2905x       2905x       2905x 2905x 2905x 2905x 2905x 16x 16x 13x 13x 13x 13x 16x 2905x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 2905x 73x 40x 40x 40x     40x     40x 40x 40x 40x 40x         40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 32x 32x 32x 32x 32x 85x 85x 55x 55x 85x 23x 23x 7x 85x 9x 32x 73x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 1x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 26x 26x 26x 26x 26x 37x 37x 73x                                   73x 63x 63x 63x 63x 63x 63x 63x 63x         63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 32x           63x         63x     63x       63x   63x   63x 73x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 73x 18x 18x           18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 362x 362x 362x 27480x 27480x 27480x 27480x 27480x 27480x 19307x 53078x 53078x 53078x 2415x 2415x 2415x 2415x 53078x 19307x 7879x 362x 18x 73x 73x 73x 887x 887x     887x     887x 887x 887x 887x     887x 887x 887x     887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 887x 812x 812x 812x 812x 75x 75x 812x 812x 812x 131x 131x 131x 131x 131x 131x 131x 131x 812x 812x 812x 812x 110x 74x 74x 887x 75x 75x 75x 75x 75x 110x 74x 74x 887x 73x 73x 73x 73x 12x 12x 12x 73x 73x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 73x                                     15x 15x 15x 1185x 24885x 24885x 1185x 15x 15x 22x 22x 22x 22x 22x 22x 20x 20x 20x 20x 20x 20x 599x 11131x 11131x 599x 20x 22x 113067x 113067x 113067x 99003x 113067x 130892x 130892x 130892x 116828x 130892x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 113020x 113020x 113020x 113020x 113020x 102384x 102384x 102384x 102384x 106737x 113020x 113020x 113020x 113020x 44567x 40214x 102384x 73x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 14449x 14449x 14449x 14449x 14449x 14449x 14449x 2863x 2863x 22x 6489x 6489x 6489x 6489x 6489x 6489x           6489x 348x 6489x 1x 6141x 248x 248x 6489x 73x 107x 107x 107x 107x 24x 24x 24x 24x 24x     24x 24x 107x 10x 10x 10x 10x 83x 64x 64x 64x 73x 9x 9x 9x 9x     107x 107x 64x 64x 64x 43x 100x 43x 107x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 72x 72x 72x  
// sp_lev.js — Special level engine (port of sp_lev.c)
// Implements the des.* API functions used by themed rooms and special levels.
//
// Core functions:
//   des_map() — place a map fragment on the level
//   des_region() — create a room region
//   splev_chr2typ() — map character to terrain type
//
// C ref: sp_lev.c (~6000 lines). This is a minimal port covering
// the functions needed for themed room map placement.
import { game } from './gstate.js';
import { rn1, rn2, rnd, rne, c_d, pushRngLogEntry, rn2_raw } from './rng.js';
import {
    mons, PM_GHOST, PM_MINOTAUR, PM_GIANT_SPIDER, PM_ARCHEOLOGIST, PM_WIZARD, PM_DWARF, PM_GNOME, S_EEL, G_UNIQ,
} from './monsters.js';
import { map_background, map_object, map_trap, set_wall_state, tty_display_nhwindow } from './display.js';
import { def_char_to_objclass } from './drawing.js';
import { stairway_add } from './stairs.js';
import { create_drawbridge, is_lava, is_pool } from './dbridge.js';
import { make_grave } from './engrave.js';
import { parseNethackrc, applyOptions } from './options.js';
import { pline } from './pline.js';
import { walkfrom, maze_remove_deadends, place_lregion, rloc_mkmaze } from './mkmaze.js';
import { flood_fill_rm, mkmap } from './mkmap.js';
import { inside_room, somex, somey, somexy } from './mkroom.js';
import { priestini, mk_roamer } from './priest.js';
import { bless, blessorcurse, curse, mkcorpstat, mkgold, mkobj, mkobj_at, mksobj_at, mksobj_core, obfree, obj_extract_self, place_object, remove_object, rndmonnum, rndmonnum_adj, set_corpsenm, sobj_at, weight } from './mkobj.js';
import { mdrop_special_objs, mpickobj } from './steal.js';
import { add_room, create_room, create_subroom, dig_corridor, get_level_extends, makecorridors, mktrap_victim, topologize, wall_cleanup, wallification } from './mklev.js';
import { find_level, induced_align } from './dungeon.js';
import { ARMOR_CLASS, BOULDER, COIN_CLASS, CORPSE, DWARVISH_MATTOCK, EGG, FIGURINE, FOOD_CLASS, GEM_CLASS, MAXOCLASSES, PICK_AXE, POTION_CLASS, RANDOM_CLASS, RIN_TELEPORTATION, RING_CLASS, ROCK_CLASS, SCR_TELEPORTATION, SCROLL_CLASS, SPBOOK_CLASS, STATUE, TIN, TOOL_CLASS, WAN_DIGGING, WAN_TELEPORTATION, WAND_CLASS, WEAPON_CLASS } from './objects.js';
import { oname } from './do_name.js';
import { stackobj } from './invent.js';
import { readobjnam } from './objnam.js';
import { bury_an_obj, Can_dig_down } from './dig.js';
import { delete_contents } from './shk.js';
import { start_timer, stop_timer } from './timeout.js';
import { del_engr, engr_at, make_engr_at } from './engrave.js';
import { enexto_core, goodpos, level_difficulty, makemon, mkclass, apply_init_newcham } from './makemon.js';
import { mk_mplayer } from './mplayer.js';
import { Inhell, In_mines, Is_airlevel, Is_waterlevel, Race_if } from './macros.js';
import { Can_fall_thru } from './dbridge.js';
import {
    poly_when_stoned, pm_resists_ston, resists_ston, is_male, is_female, your_race,
    is_swimmer, is_amphibious, is_flyer, is_floater, likes_fire, passes_walls, noncorporeal,
    is_vampshifter, vampshifted,
    name_to_monplus,
} from './mondata.js';
import { t_at, m_at } from './map_access.js';
import { deltrap, maketrap, undestroyable_trap } from './trap.js';
import { depth as dungeonDepth, set_levltyp } from './hacklib.js';
import { extract_from_minvent, m_dowear } from './worn.js';
import { def_monsyms } from './symbols.js';
import { A_CHAOTIC, A_LAWFUL, A_NEUTRAL, A_NONE, ACCESSIBLE, AIR, Align2amask, ALTAR, AM_MASK, AM_SANCTUM, AM_SHRINE, AM_SPLEV_CO, AM_SPLEV_NONCO, AM_SPLEV_RANDOM, Amask2align, ANTHOLE, ANY_LOC, ARMORSHOP, ARROW_TRAP, BARRACKS, BEAR_TRAP, BEEHIVE, BLCORNER, BOOKSHOP, BRCORNER, BURN, CANDLESHOP, CLOUD, COCKNEST, COLNO, CORPSTAT_FEMALE, CORPSTAT_HISTORIC, CORPSTAT_MALE, CORPSTAT_NONE, CORR, COURT, CROSSWALL, D_BROKEN, D_CLOSED, D_ISOPEN, D_LOCKED, D_NODOOR, D_SECRET, D_TRAPPED, DART_TRAP, DB_DIR, DB_EAST, DB_NORTH, DB_SOUTH, DB_WEST, DBWALL, DELPHI, DOOR, DRY, DUST, ENGR_BLOOD, ENGRAVE, F_LOOTED, F_WARNED, FEMALE, FIRE_TRAP, FODDERSHOP, FOODSHOP, FOUNTAIN, G_EXTINCT, G_GONE, GP_AVOID_MONPOS, GP_CHECKSCARY, HOLE, HOT, HWALL, ICE, ICED_MOAT, ICED_POOL, IRONBARS, IS_DOOR, IS_DRAWBRIDGE, IS_FURNITURE, Is_knox_level, Is_rogue_level, is_hole, IS_LAVA, IS_OBSTRUCTED, is_pit, IS_POOL, IS_ROOM, IS_STWALL, IS_TREE, IS_WALL, isok, LA_DOWN, LA_UP, LADDER, LANDMINE, LAVAPOOL, LAVAWALL, LEPREHALL, LEVEL_TELEP, LR_BRANCH, LR_DOWNSTAIR, LR_DOWNTELE, LR_MONGEN, LR_PORTAL, LR_TELE, LR_UPSTAIR, LR_UPTELE, MAGIC_PORTAL, MAGIC_TRAP, MALE, MARK, MATCH_WALL, MAX_NESTED_ROOMS, MAXNROFROOMS, MKTRAP_MAZEFLAG, MKTRAP_NOSPIDERONWEB, MKTRAP_NOVICTIM, MKTRAP_SEEN, MM_ADJACENTOK, MM_IGNOREWATER, MM_NOCOUNTBIRTH, MM_NOGRP, MM_NOMSG, MM_NOTAIL, MOAT, MORGUE, NEUTRAL, NO_TRAP, NON_PM, OBJ_CONTAINED, OBJ_FLOOR, OROOM, PIT, POLY_TRAP, POOL, POTIONSHOP, RINGSHOP, ROCKTRAP, ROLLING_BOULDER_TRAP, ROOM, ROOMOFFSET, ROWNO, ROT_CORPSE, RUST_TRAP, S_LDWASHER, S_LPUDDING, S_LRING, SCORR, SCROLLSHOP, SDOOR, SET_LIT_NOCHANGE, SHARED, SHOPBASE, SINK, SLP_GAS_TRAP, SOLID, SPACE_POS, SPACELOC, SPIKED_PIT, SQKY_BOARD, STAIRS, STATUE_TRAP, STONE, STRAT_WAITFORU, SWAMP, T_LOOTED, TDWALL, TELEP_TRAP, TEMPLE, THEMEROOM, THRONE, TIMER_OBJECT, TLCORNER, TLWALL, TOOLSHOP, TRAPDOOR, TRAPNUM, TRAPPED_CHEST, TRAPPED_DOOR, TRCORNER, TREE, TREE_LOOTED, TREE_SWARM, TRWALL, TUWALL, VAULT, VIBRATING_SQUARE, VWALL, W_ANY, W_EAST, W_NONDIGGABLE, W_NONPASSWALL, W_NORTH, W_RANDOM, W_SOUTH, W_WEST, WANDSHOP, WATER, WEAPONSHOP, WEB, WET, ZOMBIFY_MON, ZOO, NO_ROOM, INVALID_TYPE, MAX_TYPE, ONAME_LEVEL_DEF } from './const.js';
const G_NOGEN = 0x0200;
const G_IGNORE = 0x8000;
const SVALL = 0xff;
// ── Character to terrain type mapping (C nhlua.c char2typ[]) ──
// C ref: nhlua.c char2typ[] — order matters; duplicate '-' entries
// must preserve first-match behavior.
const CHAR2TYP = [
    [' ', STONE],
    ['#', CORR],
    ['.', ROOM],
    ['-', HWALL],
    ['-', TLCORNER],
    ['-', TRCORNER],
    ['-', BLCORNER],
    ['-', BRCORNER],
    ['-', CROSSWALL],
    ['-', TUWALL],
    ['-', TDWALL],
    ['-', TLWALL],
    ['-', TRWALL],
    ['-', DBWALL],
    ['|', VWALL],
    ['+', DOOR],
    ['A', AIR],
    ['C', CLOUD],
    ['S', SDOOR],
    ['H', SCORR],
    ['{', FOUNTAIN],
    ['\\', THRONE],
    ['K', SINK],
    ['}', MOAT],
    ['P', POOL],
    ['L', LAVAPOOL],
    ['Z', LAVAWALL],
    ['I', ICE],
    ['W', WATER],
    ['T', TREE],
    ['F', IRONBARS],
    ['x', MAX_TYPE], // see-through
    ['B', CROSSWALL], // boundary
    ['w', MATCH_WALL], // IS_STWALL()
    ['~', ROOM], // DEC graphics mid-dot support in JS sessions
];
export function splev_chr2typ(ch) {
    for (const [mapCh, typ] of CHAR2TYP) {
        if (ch === mapCh) return typ;
    }
    return INVALID_TYPE;
}
// ── des_map: place a map fragment on the level ──
// C ref: sp_lev.c:6100 lspo_map()
//
// Parses a multiline map string and writes terrain to the level.
// For themed rooms: places at random (x,y) on the level, checks
// for collision with existing terrain, retries if needed.
export async function des_map(mapStr, x, y, lit) {
    const g = game;
    const map = g.level;
    if (!map) return null;
    // C ref: sp_lev.c:6107-6108 — early exit if themed room already failed
    if (g.in_mk_themerooms && g.themeroom_failed) return null;
    let contentsFn = null;
    // Lua-style call: map({ halign="...", valign="...", map="..." }).
    // C ref: sp_lev.c lspo_map().
    if (mapStr && typeof mapStr === 'object' && !Array.isArray(mapStr)) {
        const opts = mapStr;
        mapStr = opts.map;
        lit = opts.lit ?? lit;
        if (typeof opts.contents === 'function') {
            contentsFn = opts.contents;
        }
        if (Array.isArray(opts.coord) && opts.coord.length >= 2) {
            x = opts.coord[0];
            y = opts.coord[1];
        } else {
            if (Number.isFinite(opts.x)) x = opts.x;
            if (Number.isFinite(opts.y)) y = opts.y;
        }
        if ((x == null || y == null) && opts.halign && opts.valign) {
            const x_maze_max = g.x_maze_max ?? ((COLNO - 1) & ~1);
            const y_maze_max = g.y_maze_max ?? ((ROWNO - 1) & ~1);
            const linesForSize = String(mapStr || '').split('\n');
            if (linesForSize.length > 0 && linesForSize[0] === '') linesForSize.shift();
            if (linesForSize.length > 0 && linesForSize[linesForSize.length - 1] === '') linesForSize.pop();
            const xsize = Math.max(0, ...linesForSize.map(l => l.length));
            const ysize = linesForSize.length;
            const halign = String(opts.halign).toLowerCase();
            const valign = String(opts.valign).toLowerCase();
            switch (halign) {
            case 'left': x = g.splev_init_present ? 1 : 3; break;
            case 'half-left': x = 2 + Math.trunc((x_maze_max - 2 - xsize) / 4); break;
            case 'center': x = 2 + Math.trunc((x_maze_max - 2 - xsize) / 2); break;
            case 'half-right': x = 2 + Math.trunc(((x_maze_max - 2 - xsize) * 3) / 4); break;
            case 'right': x = x_maze_max - xsize - 1; break;
            default: break;
            }
            switch (valign) {
            case 'top': y = 3; break;
            case 'center': y = 2 + Math.trunc((y_maze_max - 2 - ysize) / 2); break;
            case 'bottom': y = y_maze_max - ysize - 1; break;
            default: break;
            }
            if (Number.isFinite(x) && !(x % 2)) x++;
            if (Number.isFinite(y) && !(y % 2)) y++;
        }
    }
    if (Array.isArray(mapStr)) {
        mapStr = mapStr.join('\n');
    }
    if (typeof mapStr !== 'string') {
        throw new Error('des.map requires string map data');
    }
    // Parse map string into lines
    const lines = mapStr.split('\n');
    // C ref: Lua [[...]] strips the first character if it's a newline.
    // JS template literals include the leading newline, so strip it here.
    if (lines.length > 0 && lines[0] === '') lines.shift();
    // C ref: mapfrag_fromstr() does not count a final trailing empty row.
    if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
    const mapH = lines.length;
    const mapW = Math.max(...lines.map(l => l.length));
    // C ref: sp_lev.c:6140-6141 — save original coords for retry logic.
    // ox/oy track whether each axis was originally unspecified (null).
    // When null, the retry loop picks new random coords on each attempt.
    const ox = x, oy = y;
    let tryct = 0;
    let themedMapFailed = false;
    // C ref: sp_lev.c:6142 redo_maploc — retry loop for themed room placement.
    // For non-themed maps or maps with explicit coords, this runs exactly once.
    redo_maploc: for (;;) { // eslint-disable-line no-labels
        g.sp_xsize = mapW;
        g.sp_ysize = mapH;
        // C ref: sp_lev.c:6146-6167 — themed room random position selection.
        // Only randomize axes that were originally unspecified (ox/oy null).
        if (g.in_mk_themerooms && (ox == null || oy == null)) {
            if (ox == null) {
                if (g.coder?.croom) {
                    x = somex(g.coder.croom) - mapW;
                    if (x < 1) x = 1;
                } else {
                    x = 1 + rn2(COLNO - 1 - mapW);
                }
            }
            if (oy == null) {
                if (g.coder?.croom) {
                    y = somey(g.coder.croom) - mapH;
                    if (y < 1) y = 1;
                } else {
                    y = rn2(ROWNO - mapH);
                }
            }
        }
        // C ref: sp_lev.c:6169-6190 — compute xstart/ystart from coords.
        if (x != null && y != null) {
            if (g.coder?.croom) {
                // In a room: adjust to room-relative coords
                g.sp_xstart = x + g.coder.croom.lx;
                g.sp_ystart = y + g.coder.croom.ly;
                g.sp_xsize = Math.min(mapW, g.coder.croom.hx - g.coder.croom.lx);
                g.sp_ysize = Math.min(mapH, g.coder.croom.hy - g.coder.croom.ly);
            } else {
                g.sp_xstart = x;
                g.sp_ystart = y;
            }
        } else {
            // C ref: sp_lev.c:6191-6225 — halign/valign placement (SPLEV_CENTER default)
            const x_maze_max = g.x_maze_max ?? ((COLNO - 1) & ~1);
            const y_maze_max = g.y_maze_max ?? ((ROWNO - 1) & ~1);
            g.sp_xstart = 2 + Math.trunc((x_maze_max - 2 - mapW) / 2);
            g.sp_ystart = 2 + Math.trunc((y_maze_max - 2 - mapH) / 2);
            if (!(g.sp_xstart % 2)) g.sp_xstart++;
            if (!(g.sp_ystart % 2)) g.sp_ystart++;
        }
        // C ref: sp_lev.c:6227-6238 — y-overflow handling
        if (g.sp_ystart < 0 || g.sp_ystart + g.sp_ysize > ROWNO) {
            if (g.in_mk_themerooms) {
                themedMapFailed = true;
                break;
            }
            g.sp_ystart += (g.sp_ystart > 0) ? -2 : 2;
            if (g.sp_ysize === ROWNO) g.sp_ystart = 0;
            if (g.sp_ystart < 0 || g.sp_ystart + g.sp_ysize > ROWNO) g.sp_ystart = 0;
        }
        if (g.sp_xsize <= 1 && g.sp_ysize <= 1) {
            resetXyStartSize();
            break;
        }
        // C ref: sp_lev.c:6246-6274 — themed room collision check.
        // Ensures the map area + 1-cell border is clear (STONE, NO_ROOM).
        if (g.in_mk_themerooms) {
            let isokp = true;
            const yhi = Math.min(ROWNO, g.sp_ystart + g.sp_ysize) + 1;
            const xhi = Math.min(COLNO, g.sp_xstart + g.sp_xsize) + 1;
            for (let cy = g.sp_ystart - 1; cy < yhi; cy++) {
                for (let cx = g.sp_xstart - 1; cx < xhi; cx++) {
                    if (!isok(cx, cy)) {
                        isokp = false;
                    } else {
                        const loc = map.at(cx, cy);
                        if (!loc) {
                            isokp = false;
                        } else if (cy < g.sp_ystart || cy >= (g.sp_ystart + g.sp_ysize)
                                || cx < g.sp_xstart || cx >= (g.sp_xstart + g.sp_xsize)) {
                            // Border: must be untouched STONE/NO_ROOM
                            if (loc.typ !== STONE || loc.roomno !== NO_ROOM)
                                isokp = false;
                        } else {
                            // Interior: check against map content
                            const mch = lines[cy - g.sp_ystart]?.[cx - g.sp_xstart] ?? ' ';
                            const mptyp = splev_chr2typ(mch);
                            if (mptyp >= MAX_TYPE) {
                                // see-through marker — skip this cell
                            } else if ((loc.typ !== STONE && loc.typ !== mptyp)
                                    || loc.roomno !== NO_ROOM) {
                                isokp = false;
                            }
                        }
                    }
                    if (!isokp) {
                        // C ref: sp_lev.c:6269 — tryct++ < 100, post-increment
                        if (tryct++ < 100 && (ox == null || oy == null))
                            continue redo_maploc; // eslint-disable-line no-labels
                        themedMapFailed = true;
                        break;
                    }
                }
                if (themedMapFailed) break;
            }
            if (themedMapFailed) break;
        }
        break; // placement succeeded (or not themed — proceed to terrain write)
    }
    // C ref: sp_lev.c:6303-6306 — on themed room failure, reset and return
    if (themedMapFailed) {
        g.themeroom_failed = true;
        resetXyStartSize();
        return null;
    }
    // Use computed xstart/ystart for terrain writing
    x = g.sp_xstart;
    y = g.sp_ystart;
    // C ref: lspo_map() returns a selection containing all map tiles placed.
    const mapSelection = new SelectionVar();
    // C ref: sp_lev.c:6277-6297 — load map terrain
    for (let my = 0; my < g.sp_ysize; my++) {
        for (let mx = 0; mx < g.sp_xsize; mx++) {
            const ch = lines[my]?.[mx] ?? ' ';
            const typ = splev_chr2typ(ch);
            if (typ < 0 || typ >= MAX_TYPE) continue; // skip invalid/see-through
            const lx = x + mx, ly = y + my;
            if (!isok(lx, ly)) continue;
            const loc = map.at(lx, ly);
            if (loc) {
                // C ref: sp_lev.c:6288-6292 — clear fields BEFORE set_levltyp.
                loc.flags = 0;
                loc.horizontal = 0;
                loc.roomno = 0;
                loc.edge = 0;
 
                // C ref: mkmaze.c:82-87 — SDOOR+AIR → keep SDOOR, mark arboreal
                if (loc.typ === SDOOR && typ === AIR) {
                    loc.arboreal_sdoor = 1;
                    markSpLevMap(lx, ly);
                    mapSelection.setAbsPoint(lx, ly, 1);
                    continue;
                }
                // C ref: mkmaze.c set_levltyp — refuse to overwrite stairs/ladders
                if (loc.typ === STAIRS || loc.typ === LADDER) continue;
 
                // C ref: mkmaze.c set_levltyp + sel_set_ter
                loc.typ = typ;
                loc.lit = IS_LAVA(loc.typ) ? 1 : (lit ? 1 : 0);
                if (loc.typ === SDOOR || IS_DOOR(loc.typ)) {
                    if (loc.typ === SDOOR) loc.flags = D_CLOSED;
                    if (lx > 0) {
                        const left = map.at(lx - 1, ly);
                        if (left && (IS_WALL(left.typ) || left.horizontal)) loc.horizontal = 1;
                    }
                } else if (loc.typ === HWALL || loc.typ === IRONBARS) {
                    loc.horizontal = 1;
                }
                markSpLevMap(lx, ly);
                mapSelection.setAbsPoint(lx, ly, 1);
            }
        }
    }
    // C ref: sp_lev.c:6308-6312 — run contents callback, then reset coords.
    if (contentsFn) {
        await contentsFn({ xsize: g.sp_xsize, ysize: g.sp_ysize });
        resetXyStartSize();
    }
    return mapSelection;
}
// ── des_region: create a room region ──
// C ref: sp_lev.c:1650 lspo_region()
// For themed rooms, creates an irregular room region.
export function des_region(x1, y1, x2, y2, rtype, rlit, irregular, filled) {
    const g = game;
    if (!g?.level) return null;
    // C ref: sp_lev.c:1513 — litstate_rnd runs BEFORE the nroom check.
    // C always consumes the RNG here, even when nroom >= MAXNROFROOMS.
    if (rlit < 0) {
        const dng = g.dungeons?.[g.u?.uz?.dnum ?? 0];
        const d = (dng?.depth_start ?? 0) + (g.u?.uz?.dlevel ?? 1) - 1;
        rlit = (rnd(1 + Math.abs(d)) < 11 && rn2(77)) ? 1 : 0;
    } else {
        rlit = rlit ? 1 : 0;
    }
    // C ref: sp_lev.c:5661 — nroom check AFTER litstate_rnd
    if (g.level.nroom >= MAXNROFROOMS) return null;
    if (irregular) {
        const roomnoidx = g.level.nroom;
        const roomno = roomnoidx + ROOMOFFSET;
        g.smeq[roomnoidx] = roomnoidx;
        // C ref: sp_lev.c:lspo_region() irregular branch:
        // flood_fill_rm(..., anyroom=TRUE) then add_room(min,max,FALSE,...,special=TRUE).
        g._min_rx = g._max_rx = x1;
        g._min_ry = g._max_ry = y1;
        flood_fill_rm(x1, y1, roomno, !!rlit, true);
        add_room(g._min_rx, g._min_ry, g._max_rx, g._max_ry, false, rtype ?? OROOM, true);
        const troom = g.level.rooms[roomnoidx];
        if (!troom) return null;
        troom.rlit = rlit;
        troom.irregular = true;
        troom.needfill = filled || 0;
        troom.needjoining = true;
        return troom;
    }
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            const loc = g.level.at(x, y);
            if (loc && IS_ROOM(loc.typ)) {
                loc.lit = !!rlit;
            }
        }
    }
    return null;
}
function growSelection(sel, dir) {
    if (!(sel instanceof SelectionVar)) return sel;
    let mask = dir;
    if (mask === W_RANDOM) mask = randomWdir();
    const set = new Set(sel.points.map((pt) => `${pt.x},${pt.y}`));
    let minX = COLNO - 1, minY = ROWNO - 1, maxX = 0, maxY = 0;
    for (const pt of sel.points) {
        if (pt.x < minX) minX = pt.x;
        if (pt.y < minY) minY = pt.y;
        if (pt.x > maxX) maxX = pt.x;
        if (pt.y > maxY) maxY = pt.y;
    }
    const added = [];
    for (let x = Math.max(0, minX - 1); x <= Math.min(COLNO - 1, maxX + 1); x++) {
        for (let y = Math.max(0, minY - 1); y <= Math.min(ROWNO - 1, maxY + 1); y++) {
            const west = set.has(`${x + 1},${y}`);
            const north = set.has(`${x},${y + 1}`);
            const east = set.has(`${x - 1},${y}`);
            const south = set.has(`${x},${y - 1}`);
            const nw = set.has(`${x + 1},${y + 1}`);
            const ne = set.has(`${x - 1},${y + 1}`);
            const se = set.has(`${x - 1},${y - 1}`);
            const sw = set.has(`${x + 1},${y - 1}`);
            const grows =
                ((mask & W_WEST) && west)
                || (((mask & (W_WEST | W_NORTH)) === (W_WEST | W_NORTH)) && nw)
                || ((mask & W_NORTH) && north)
                || (((mask & (W_NORTH | W_EAST)) === (W_NORTH | W_EAST)) && ne)
                || ((mask & W_EAST) && east)
                || (((mask & (W_EAST | W_SOUTH)) === (W_EAST | W_SOUTH)) && se)
                || ((mask & W_SOUTH) && south)
                || (((mask & (W_SOUTH | W_WEST)) === (W_SOUTH | W_WEST)) && sw);
            if (grows && !set.has(`${x},${y}`)) added.push({ x, y });
        }
    }
    sel.points.push(...added);
    return sel;
}
function parseGrowDir(dir) {
    switch (String(dir || 'all').toLowerCase()) {
    case 'all': return W_ANY;
    case 'random': return W_RANDOM;
    case 'north': return W_NORTH;
    case 'west': return W_WEST;
    case 'east': return W_EAST;
    case 'south': return W_SOUTH;
    default: return W_ANY;
    }
}
function randomWdir() {
    const wdirs = [W_NORTH, W_SOUTH, W_EAST, W_WEST];
    return wdirs[rn2(4)];
}
function lightRegion(x1, y1, x2, y2, rlit) {
    if (!game.level) return;
    const litstate = !!rlit;
    let lowx = x1, lowy = y1, hix = x2, hiy = y2;
    if (litstate) {
        lowx = Math.max(lowx - 1, 1);
        hix = Math.min(hix + 1, COLNO - 1);
        lowy = Math.max(lowy - 1, 0);
        hiy = Math.min(hiy + 1, ROWNO - 1);
    }
    for (let x = lowx; x <= hix; x++) {
        for (let y = lowy; y <= hiy; y++) {
            const loc = game.level.at(x, y);
            if (!loc) continue;
            loc.lit = IS_LAVA(loc.typ) || litstate;
            loc.waslit = !!loc.lit;
        }
    }
}
// ── Selection API needed by themed rooms ──
class SelectionVar {
    constructor(points = []) {
        this.points = points.slice();
    }
    clone() {
        return new SelectionVar(this.points);
    }
    numpoints() {
        return this.points.length;
    }
    rndcoord(removeit = 0) {
        if (!this.points.length) return { x: -1, y: -1 };
        const bounds = this.bounds();
        const pointSet = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        let idx = 0;
        for (let x = bounds.lx; x <= bounds.hx; x++) {
            for (let y = bounds.ly; y <= bounds.hy; y++) {
                if (pointSet.has(`${x},${y}`)) idx++;
            }
        }
        if (!idx) return { x: -1, y: -1 };
        let c = rn2(idx);
        for (let x = bounds.lx; x <= bounds.hx; x++) {
            for (let y = bounds.ly; y <= bounds.hy; y++) {
                const key = `${x},${y}`;
                if (!pointSet.has(key)) continue;
                if (c === 0) {
                    if (removeit) {
                        this.points = this.points.filter((pt) => !(pt.x === x && pt.y === y));
                    }
                    if (game.currentRoom) {
                        return { x: x - game.currentRoom.lx, y: y - game.currentRoom.ly };
                    }
                    return { x: x - (game.sp_xstart ?? 0), y: y - (game.sp_ystart ?? 0) };
                }
                c--;
            }
        }
        return { x: -1, y: -1 };
    }
    percentage(pct) {
        const kept = new SelectionVar();
        const bounds = this.bounds();
        const pointSet = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        for (let x = bounds.lx; x <= bounds.hx; x++) {
            for (let y = bounds.ly; y <= bounds.hy; y++) {
                if (pointSet.has(`${x},${y}`) && rn2(100) < pct) {
                    kept.setAbsPoint(x, y, 1);
                }
            }
        }
        return kept;
    }
    async iterate(fn) {
        const bounds = this.bounds();
        const pointSet = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        for (let y = bounds.ly; y <= bounds.hy; y++) {
            for (let x = Math.max(1, bounds.lx); x <= bounds.hx; x++) {
                if (!pointSet.has(`${x},${y}`)) continue;
                const rx = game.currentRoom ? (x - game.currentRoom.lx) : (x - (game.sp_xstart ?? 0));
                const ry = game.currentRoom ? (y - game.currentRoom.ly) : (y - (game.sp_ystart ?? 0));
                await fn(rx, ry);
            }
        }
    }
    filter_mapchar(ch, lit = -2) {
        const typ = parseMatchMapChr(ch);
        if (typ < 0) return new SelectionVar();
        const filtered = new SelectionVar();
        const level = game.level;
        if (!level) return filtered;
        const bounds = this.bounds();
        const pointSet = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        for (let x = bounds.lx; x <= bounds.hx; x++) {
            for (let y = bounds.ly; y <= bounds.hy; y++) {
                if (!pointSet.has(`${x},${y}`)) continue;
                const loc = level.at(x, y);
                if (!loc || !matchMapTyps(typ, loc.typ)) continue;
                switch (lit) {
                default:
                case -2:
                    filtered.setAbsPoint(x, y, 1);
                    break;
                case -1:
                    filtered.setAbsPoint(x, y, rn2(2));
                    break;
                case 0:
                case 1:
                    if ((loc.lit ? 1 : 0) === lit) filtered.setAbsPoint(x, y, 1);
                    break;
                }
            }
        }
        return filtered;
    }
    bounds() {
        if (!this.points.length) {
            return { lx: 0, ly: 0, hx: COLNO - 1, hy: ROWNO - 1 };
        }
        let lx = COLNO - 1, ly = ROWNO - 1, hx = 0, hy = 0;
        for (const pt of this.points) {
            if (pt.x < lx) lx = pt.x;
            if (pt.y < ly) ly = pt.y;
            if (pt.x > hx) hx = pt.x;
            if (pt.y > hy) hy = pt.y;
        }
        return { lx, ly, hx, hy };
    }
    // C ref: nhlsel.c l_selection_room → selvar.c selection_from_mkroom.
    // Creates a selection of all floor tiles belonging to the current room.
    room(roomIdx) {
        const sel = new SelectionVar();
        let croom = null;
        if (roomIdx !== undefined && roomIdx >= 0 && roomIdx < (game.level?.nroom ?? 0)) {
            croom = game.level?.rooms?.[roomIdx];
        }
        if (!croom && game.currentRoom) {
            croom = game.currentRoom;
        }
        if (!croom) return sel;
        const rooms = game.level?.rooms || [];
        const rmno = rooms.indexOf(croom) + ROOMOFFSET;
        for (let y = croom.ly; y <= croom.hy; y++) {
            for (let x = croom.lx; x <= croom.hx; x++) {
                if (!isok(x, y)) continue;
                const loc = game.level?.at(x, y);
                if (loc && !loc.edge && loc.roomno === rmno) {
                    sel.setAbsPoint(x, y, 1);
                }
            }
        }
        return sel;
    }
    grow(dir = 'all') {
        const grown = this.clone();
        growSelection(grown, parseGrowDir(dir));
        return grown;
    }
    set(x = -1, y = -1, value = 1) {
        const coord = resolveSelectionCoord(x, y);
        if (!coord) return this;
        const key = `${coord.x},${coord.y}`;
        if (value) {
            if (!this.points.some((pt) => pt.x === coord.x && pt.y === coord.y)) {
                this.points.push(coord);
            }
        } else {
            this.points = this.points.filter((pt) => `${pt.x},${pt.y}` !== key);
        }
        return this;
    }
    negate() {
        const existing = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        const negated = [];
        for (let x = 0; x < COLNO; x++) {
            for (let y = 0; y < ROWNO; y++) {
                if (!existing.has(`${x},${y}`)) negated.push({ x, y });
            }
        }
        return new SelectionVar(negated);
    }
    union(other) {
        const merged = new Map(this.points.map((pt) => [`${pt.x},${pt.y}`, pt]));
        if (other instanceof SelectionVar) {
            for (const pt of other.points) merged.set(`${pt.x},${pt.y}`, pt);
        }
        return new SelectionVar([...merged.values()]);
    }
    intersect(other) {
        return this.combineWith(other, (a, b) => a & b, false);
    }
    xor(other) {
        return this.combineWith(other, (a, b) => a ^ b, true);
    }
    subtract(other) {
        return this.combineWith(other, (a, b) => (a ^ b) & a, true);
    }
    line(x1, y1, x2, y2) {
        const drawn = this.clone();
        const p1 = resolveSelectionCoord(x1, y1);
        const p2 = resolveSelectionCoord(x2, y2);
        if (!p1 || !p2) return drawn;
        selectionDoLine(p1.x, p1.y, p2.x, p2.y, drawn);
        return drawn;
    }
    rect(x1, y1, x2, y2) {
        const drawn = this.clone();
        const p1 = resolveSelectionCoord(x1, y1);
        const p2 = resolveSelectionCoord(x2, y2);
        if (!p1 || !p2) return drawn;
        selectionDoLine(p1.x, p1.y, p2.x, p1.y, drawn);
        selectionDoLine(p1.x, p1.y, p1.x, p2.y, drawn);
        selectionDoLine(p2.x, p1.y, p2.x, p2.y, drawn);
        selectionDoLine(p1.x, p2.y, p2.x, p2.y, drawn);
        return drawn;
    }
    fillrect(x1, y1, x2, y2) {
        const filled = this.clone();
        const p1 = resolveSelectionCoord(x1, y1);
        const p2 = resolveSelectionCoord(x2, y2);
        if (!p1 || !p2) return filled;
        if (p1.x === p2.x) {
            for (let y = p1.y; y <= p2.y; y++) filled.setAbsPoint(p1.x, y, 1);
        } else {
            for (let y = p1.y; y <= p2.y; y++) selectionDoLine(p1.x, y, p2.x, y, filled);
        }
        return filled;
    }
    randline(x1, y1, x2, y2, roughness = 7) {
        const drawn = this.clone();
        const p1 = resolveSelectionCoord(x1, y1);
        const p2 = resolveSelectionCoord(x2, y2);
        if (!p1 || !p2) return drawn;
        selectionDoRandline(p1.x, p1.y, p2.x, p2.y, roughness, 12, drawn);
        return drawn;
    }
    circle(x, y, r, filled = 0) {
        const drawn = this.clone();
        const center = resolveSelectionCoord(x, y);
        if (!center) return drawn;
        selectionDoEllipse(drawn, center.x, center.y, r, r, !filled);
        return drawn;
    }
    ellipse(x, y, r1, r2, filled = 0) {
        const drawn = this.clone();
        const center = resolveSelectionCoord(x, y);
        if (!center) return drawn;
        selectionDoEllipse(drawn, center.x, center.y, r1, r2, !filled);
        return drawn;
    }
    setAbsPoint(x, y, value = 1) {
        if (x < 0 || y < 0 || x >= COLNO || y >= ROWNO) return this;
        const key = `${x},${y}`;
        if (value) {
            if (!this.points.some((pt) => pt.x === x && pt.y === y)) {
                this.points.push({ x, y });
            }
        } else {
            this.points = this.points.filter((pt) => `${pt.x},${pt.y}` !== key);
        }
        return this;
    }
    combineWith(other, combine, recalcBounds = false) {
        if (!(other instanceof SelectionVar)) return new SelectionVar();
        const aBounds = this.bounds();
        const bBounds = other.bounds();
        const lx = Math.min(aBounds.lx, bBounds.lx);
        const ly = Math.min(aBounds.ly, bBounds.ly);
        const hx = Math.max(aBounds.hx, bBounds.hx);
        const hy = Math.max(aBounds.hy, bBounds.hy);
        const aSet = new Set(this.points.map((pt) => `${pt.x},${pt.y}`));
        const bSet = new Set(other.points.map((pt) => `${pt.x},${pt.y}`));
        const result = new SelectionVar();
        for (let x = lx; x <= hx; x++) {
            for (let y = ly; y <= hy; y++) {
                const val = combine(aSet.has(`${x},${y}`) ? 1 : 0, bSet.has(`${x},${y}`) ? 1 : 0);
                result.setAbsPoint(x, y, val);
            }
        }
        return recalcBounds ? new SelectionVar(result.points) : result;
    }
    match(pattern) {
        if (typeof pattern !== 'string') return new SelectionVar();
        const mf = mapfragFromStr(pattern);
        if (!mf) return new SelectionVar();
        const matched = new SelectionVar();
        for (let y = 0; y <= ROWNO; y++) {
            for (let x = 1; x < COLNO; x++) {
                matched.setAbsPoint(x, y, mapfragMatch(mf, x, y) ? 1 : 0);
            }
        }
        return matched;
    }
}
function roomSelection(croom = null) {
    const room = croom || game.currentRoom;
    if (!room || !game.level) return new SelectionVar();
    const roomno = (room.roomnoidx ?? -1) + ROOMOFFSET;
    const points = [];
    for (let x = room.lx; x <= room.hx; x++) {
        for (let y = room.ly; y <= room.hy; y++) {
            const loc = game.level.at(x, y);
            if (loc && !loc.edge && loc.roomno === roomno) {
                points.push({ x, y });
            }
        }
    }
    return new SelectionVar(points);
}
export const selection = {
    new: () => new SelectionVar(),
    set(selOrX = -1, y = -1, value = 1, maybeValue = 1) {
        if (selOrX instanceof SelectionVar) {
            if (arguments.length === 1) return selOrX.set();
            if (arguments.length === 2) return selOrX.set(y);
            if (arguments.length === 3) return selOrX.set(y, value);
            return selOrX.set(y, value, maybeValue);
        }
        return new SelectionVar().set(selOrX, y, value);
    },
    rndcoord(sel, removeit = 0) {
        if (!(sel instanceof SelectionVar)) return { x: -1, y: -1 };
        return sel.rndcoord(removeit);
    },
    async iterate(sel, fn) {
        if (!(sel instanceof SelectionVar)) return;
        await sel.iterate(fn);
    },
    clone(sel) {
        if (!(sel instanceof SelectionVar)) return new SelectionVar();
        return sel.clone();
    },
    bounds(sel) {
        if (!(sel instanceof SelectionVar)) return { lx: 0, ly: 0, hx: COLNO - 1, hy: ROWNO - 1 };
        return sel.bounds();
    },
    grow(sel, dir = 'all') {
        if (!(sel instanceof SelectionVar)) return new SelectionVar();
        return sel.grow(dir);
    },
    negate(sel = null) {
        if (sel instanceof SelectionVar) return sel.negate();
        return new SelectionVar().negate();
    },
    union(a, b) {
        if (!(a instanceof SelectionVar)) return new SelectionVar();
        return a.union(b);
    },
    intersect(a, b) {
        if (!(a instanceof SelectionVar)) return new SelectionVar();
        return a.intersect(b);
    },
    xor(a, b) {
        if (!(a instanceof SelectionVar)) return new SelectionVar();
        return a.xor(b);
    },
    subtract(a, b) {
        if (!(a instanceof SelectionVar)) return new SelectionVar();
        return a.subtract(b);
    },
    line(selOrX1, y1, x2, y2, maybeY2) {
        if (selOrX1 instanceof SelectionVar) return selOrX1.line(y1, x2, y2, maybeY2);
        return new SelectionVar().line(selOrX1, y1, x2, y2);
    },
    rect(selOrX1, y1, x2, y2, maybeY2) {
        if (selOrX1 instanceof SelectionVar) return selOrX1.rect(y1, x2, y2, maybeY2);
        return new SelectionVar().rect(selOrX1, y1, x2, y2);
    },
    fillrect(selOrX1, y1, x2, y2, maybeY2) {
        if (selOrX1 instanceof SelectionVar) return selOrX1.fillrect(y1, x2, y2, maybeY2);
        return new SelectionVar().fillrect(selOrX1, y1, x2, y2);
    },
    area(selOrX1, y1, x2, y2, maybeY2) {
        if (selOrX1 instanceof SelectionVar) return selOrX1.fillrect(y1, x2, y2, maybeY2);
        return new SelectionVar().fillrect(selOrX1, y1, x2, y2);
    },
    randline(selOrX1, y1, x2, y2, roughness, maybeRoughness = 7) {
        if (selOrX1 instanceof SelectionVar) return selOrX1.randline(y1, x2, y2, roughness, maybeRoughness);
        return new SelectionVar().randline(selOrX1, y1, x2, y2, roughness);
    },
    circle(selOrX, y, r, filled = 0, maybeFilled = 0) {
        if (selOrX instanceof SelectionVar) return selOrX.circle(y, r, filled, maybeFilled);
        return new SelectionVar().circle(selOrX, y, r, filled);
    },
    ellipse(selOrX, y, r1, r2, filled = 0, maybeFilled = 0) {
        if (selOrX instanceof SelectionVar) return selOrX.ellipse(y, r1, r2, filled, maybeFilled);
        return new SelectionVar().ellipse(selOrX, y, r1, r2, filled);
    },
    floodfill(x, y, diagonals = false) {
        const start = resolveSelectionCoord(x, y);
        const level = game.level;
        const sel = new SelectionVar();
        if (!start || !level || !isok(start.x, start.y)) return sel;
        const startTyp = level.at(start.x, start.y)?.typ;
        if (startTyp == null) return sel;
        const seen = new Set();
        const stack = [[start.x, start.y]];
        while (stack.length) {
            const [cx, cy] = stack.pop();
            const key = `${cx},${cy}`;
            if (seen.has(key)) continue;
            seen.add(key);
            if (!isok(cx, cy)) continue;
            if (level.at(cx, cy)?.typ !== startTyp) continue;
            sel.setAbsPoint(cx, cy, 1);
            stack.push([cx + 1, cy], [cx - 1, cy], [cx, cy + 1], [cx, cy - 1]);
            if (diagonals) {
                stack.push([cx + 1, cy + 1], [cx - 1, cy - 1], [cx - 1, cy + 1], [cx + 1, cy - 1]);
            }
        }
        return sel;
    },
    room(arg) {
        if (Number.isInteger(arg) && game.level.rooms && arg >= 0 && arg < game.level.rooms.length) {
            return roomSelection(game.level.rooms[arg]);
        }
        return roomSelection();
    },
    percentage(sel, pct) {
        if (!(sel instanceof SelectionVar)) return new SelectionVar();
        return sel.percentage(pct);
    },
    match: function(pattern) {
        return new SelectionVar().match(pattern);
    },
};
// Utility exports
export function percent(p) { return rn2(100) < p; }
export function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = rn2(i + 1);
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}
// Level state
export const levelState = {
    // C ref: dungeon.c depth() = depth_start + dlevel - 1
    depth: () => {
        const uz = game.u?.uz;
        const dng = game.dungeons?.[uz?.dnum ?? 0];
        return (dng?.depth_start ?? 0) + (uz?.dlevel ?? 1) - 1;
    },
};
// nh namespace for Lua compatibility
export const nh = {
    // C ref: dungeon.c level_difficulty() — uses depth(), not dlevel
    level_difficulty: () => {
        const uz = game.u?.uz;
        const dng = game.dungeons?.[uz?.dnum ?? 0];
        return (dng?.depth_start ?? 0) + (uz?.dlevel ?? 1) - 1;
    },
    rn2: (n) => rn2(n),
    rn1: (x, y) => rn2(x) + y,
    is_genocided: (name) => {
        const needle = String(name || '').toLowerCase();
        if (!needle) return false;
        let mndx = -1;
        for (let i = 0; i < mons.length; i++) {
            if (mons[i]?.mname?.toLowerCase() === needle) {
                mndx = i;
                break;
            }
        }
        if (mndx < 0) return false;
        return !!((game.mvitals?.[mndx]?.mvflags ?? 0) & G_GONE);
    },
    debug_themerm: () => null,
    parse_config: (line) => {
        const text = String(line ?? '');
        if (!text.trim()) return;
        const parsed = parseNethackrc(text);
        applyOptions(parsed, game);
    },
    eckey: (cmd) => {
        // C ref: nhlua.c:1644 nhl_get_cmd_key → cmd_from_ecname
        // Returns the default key binding for a command name.
        // Format: ^X for Ctrl-X, M-X for Alt-X, or the key character.
        const bindings = {
            // Default vi-keys (numpad:0) bindings
            kick: '^D', close: 'c', cast: 'Z', drop: 'd', eat: 'e',
            fire: 'f', glance: ';', jump: 'M-j', loot: 'M-l', pickup: ',',
            puton: 'P', quaff: 'q', quiver: 'Q', read: 'r', remove: 'R',
            run: 'G', search: 's', swap: 'x', takeoff: 'T', throw: 't',
            tip: 'M-T', travel: '_', twoweapon: 'X', untrap: 'M-u',
            wait: '.', wear: 'W', wield: 'w', zap: 'z', down: '>',
            up: '<', help: '?', moveeast: 'l', movewest: 'h',
            movenorth: 'k', movesouth: 'j', movenortheast: 'u',
            movenorthwest: 'y', movesoutheast: 'n', movesouthwest: 'b',
        };
        return bindings[cmd] || '?';
    },
};
export function initLuaMT() {}
// ── nhlib.lua shared functions ──
// C ref: nethack-c/upstream/dat/nhlib.lua
// These functions are shared across all special level scripts.
// C ref: nhlib.lua:44 monkfoodshop()
export function monkfoodshop() {
    if (String(u.role || '') === 'Monk') return 'health food shop';
    return 'food shop';
}
// C ref: nhlib.lua:57 hell_tweaks(protected_area)
// Adds Gehennom terrain features: lava pools, rivers, boulders, iron bars.
export async function hell_tweaks(protected_area) {
    const liquid = 'L';
    const ground = '.';
    const nProt = protected_area?.numpoints?.() ?? 0;
    const prot = protected_area?.negate?.() ?? negate();
    const depth = u.depth || 1;
    // Random pools.
    if (percent(20 + depth)) {
        let pools = new SelectionVar();
        const maxPools = 5 + (rn2(depth) + 1);
        for (let i = 1; i <= maxPools; i++) pools.set();
        pools = pools.union(selection.grow(selection.set(new SelectionVar()), 'west'));
        pools = pools.union(selection.grow(selection.set(new SelectionVar()), 'north'));
        pools = pools.union(selection.grow(selection.set(new SelectionVar()), 'random'));
        pools = pools.intersect(prot);
        if (percent(80)) {
            const poolGround = pools.clone().grow('all').intersect(prot);
            const pval = (rn2(8) + 1) * 10;
            terrain(poolGround.percentage(pval), ground);
        }
        terrain(pools, liquid);
    }
    // Lava river.
    if (percent(50)) {
        let allRivers = new SelectionVar();
        const reqpts = ((COLNO * ROWNO) - nProt) / 12;
        let rpts = 0;
        let riverTries = 0;
        do {
            const floor = selection.match(ground);
            const a = selection.rndcoord(floor);
            const b = selection.rndcoord(floor);
            let lavaRiver = selection.randline(new SelectionVar(), a.x, a.y, b.x, b.y, 10);
            if (percent(50)) lavaRiver = selection.grow(lavaRiver, 'north');
            if (percent(50)) lavaRiver = selection.grow(lavaRiver, 'west');
            allRivers = allRivers.union(lavaRiver);
            allRivers = allRivers.intersect(prot);
            rpts = allRivers.numpoints();
            riverTries++;
        } while (!(rpts > reqpts || riverTries > 7));
        if (percent(60)) {
            const prc = 10 * (rn2(6) + 1);
            let riverBanks = selection.grow(allRivers);
            riverBanks = riverBanks.intersect(prot);
            terrain(selection.percentage(riverBanks, prc), ground);
        }
        terrain(allRivers, liquid);
    }
    // Replacing some walls with boulders.
    if (percent(20)) {
        const amount = 3 * (rn2(8) + 1);
        const hWalls = selection.match('.w.').percentage(amount);
        const vWalls = selection.match('.\nw\n.').percentage(amount);
        let bWalls = hWalls.union(vWalls);
        bWalls = bWalls.intersect(prot);
        await bWalls.iterate(async (x, y) => {
            terrain(x, y, '.');
            await object('boulder', x, y);
        });
    }
    // Replacing some walls with iron bars.
    if (percent(20)) {
        const amount = 3 * (rn2(8) + 1);
        const hWalls = selection.match('.w.').percentage(amount);
        const vWalls = selection.match('.\nw\n.').percentage(amount);
        let fWalls = hWalls.union(vWalls);
        fWalls = selection.grow(fWalls).intersect(selection.match('w'));
        fWalls = fWalls.intersect(prot);
        terrain(fWalls, 'F');
    }
}
// C ref: nhlib.lua table_stringify
export function table_stringify(tbl) { return JSON.stringify(tbl); }
// C ref: nhlib.lua tutorial blacklist and events
const tutorial_blacklist_commands = { save: true };
const tutorial_events = [
    {
        async func() {
            if ((game.u?.uhunger ?? 900) < 148) {
                // C ref: nhlib.lua tutorial_events[1]
                // local o = obj.new("blessed food ration"); o:placeobj(u.ux, u.uy);
                const o = readobjnam('blessed food ration', null);
                if (o) {
                    place_object(o, game.u.ux, game.u.uy);
                    stackobj(o);
                }
                // C ref: nhlua.c nhl_pline(..., true) => pline + display_nhwindow(WIN_MESSAGE, TRUE)
                await pline("Looks like you're getting hungry.  You'll starve to death, unless you eat something.");
                await tty_display_nhwindow('message', true);
                await pline(`Comestibles are eaten with '${nh.eckey('eat')}'`);
                await tty_display_nhwindow('message', true);
                return true;
            }
            return false;
        },
    },
];
// C ref: nhlib.lua:149 tutorial_cmd_before
export function tutorial_cmd_before(cmd) {
    if (tutorial_blacklist_commands[cmd]) return false;
    return true;
}
// C ref: nhlib.lua:156 tutorial_enter
export function tutorial_enter() {
    // C: registers callbacks and saves gamestate
    // nh.callback("cmd_before", "tutorial_cmd_before");
    // nh.callback("end_turn", "tutorial_turn");
    // nh.gamestate();
}
// C ref: nhlib.lua:165 tutorial_leave
export function tutorial_leave() {
    // C: removes callbacks and restores gamestate
    // nh.callback("cmd_before", "tutorial_cmd_before", true);
    // nh.callback("end_turn", "tutorial_turn", true);
    // nh.gamestate(true);
}
// C ref: nhlib.lua:174 tutorial_turn
export async function tutorial_turn() {
    for (let k = tutorial_events.length - 1; k >= 0; k--) {
        const v = tutorial_events[k];
        if (!v) continue;
        const ucoordMatch = !v.ucoord
            || (game.u?.ux === v.ucoord[0] + 3 && game.u?.uy === v.ucoord[1] + 3);
        if (ucoordMatch) {
            if ((await v.func()) || v.remove) {
                tutorial_events.splice(k, 1);
            }
        }
    }
}
// Named export aliases for des.* access via `import * as des`
export { des_map as map };
// ── u namespace for level scripts ──
// Provides hero state that Lua level scripts read.
export const u = {
    get role() { return game.urole?.name?.m || ''; },
    get uenmax() { return game.u?.uenmax ?? 0; },
    get depth() { return dungeonDepth(game.u?.uz); },
};
const containerObjStack = [];
const inventoryMonsterStack = [];
function isFiniteCoord(value) {
    return value && Number.isFinite(value.x) && Number.isFinite(value.y);
}
function normalizeCoord(coord, x, y) {
    if (Array.isArray(coord) && coord.length >= 2) {
        return [coord[0], coord[1]];
    }
    if (isFiniteCoord(coord)) {
        return [coord.x, coord.y];
    }
    // Lua-style calls often pass coord as the 2nd positional arg:
    // des.monster("V", [x, y]) or des.monster("V", {x, y}).
    if (y == null) {
        if (Array.isArray(x) && x.length >= 2) {
            return [x[0], x[1]];
        }
        if (isFiniteCoord(x)) {
            return [x.x, x.y];
        }
    }
    if (Number.isFinite(x) && Number.isFinite(y)) {
        return [x, y];
    }
    return null;
}
function normalizeObjectArgs(args, x, y) {
    if (args == null) return {};
    if (typeof args === 'string') {
        const coord = normalizeCoord(null, x, y);
        const base = args.length === 1 ? { class: args } : { id: args };
        return coord ? { ...base, coord } : base;
    }
    const coord = normalizeCoord(args.coord, args.x, args.y);
    return coord ? { ...args, coord } : args;
}
function normalizeTrapArgs(args, x, y) {
    if (args == null) return {};
    if (Number.isFinite(args)) {
        const coord = normalizeCoord(null, x, y);
        const base = { type: args };
        return coord ? { ...base, coord } : base;
    }
    if (typeof args === 'string') {
        const coord = normalizeCoord(null, x, y);
        return coord ? { type: args, coord } : { type: args };
    }
    const coord = normalizeCoord(args.coord, args.x, args.y);
    return coord ? { ...args, coord } : args;
}
function normalizeMonsterArgs(args, x, y) {
    if (args == null) return {};
    if (typeof args === 'string') {
        const coord = normalizeCoord(null, x, y);
        const base = args.length === 1 ? { class: args } : { id: args };
        return coord ? { ...base, coord } : base;
    }
    const coord = normalizeCoord(args.coord, args.x, args.y);
    return coord ? { ...args, coord } : args;
}
function normalizeEngravingArgs(args) {
    if (!args) return args;
    const coord = normalizeCoord(args.coord, args.x, args.y);
    return coord ? { ...args, coord } : args;
}
function toAbsCoord(coord) {
    if (!coord) return null;
    if (game.currentRoom) {
        return [coord[0] + game.currentRoom.lx, coord[1] + game.currentRoom.ly];
    }
    return [
        coord[0] + (game.sp_xstart ?? 0),
        coord[1] + (game.sp_ystart ?? 0),
    ];
}
function normalizeCoordPair(coordLike, x, y) {
    if (Array.isArray(coordLike) && coordLike.length >= 2) return [coordLike[0], coordLike[1]];
    if (isFiniteCoord(coordLike)) return [coordLike.x, coordLike.y];
    if (Number.isFinite(x) && Number.isFinite(y)) return [x, y];
    return null;
}
function currentMapBounds() {
    const xstart = game.sp_xstart ?? 0;
    const ystart = game.sp_ystart ?? 0;
    const xsize = game.sp_xsize ?? 0;
    const ysize = game.sp_ysize ?? 0;
    if (xsize > 0 && ysize > 0) {
        return {
            lx: xstart,
            ly: ystart,
            hx: Math.min(COLNO - 1, xstart + xsize - 1),
            hy: Math.min(ROWNO - 1, ystart + ysize - 1),
        };
    }
    return { lx: 1, ly: 0, hx: COLNO - 1, hy: ROWNO - 1 };
}
function getLocationSpan() {
    // C ref: sp_lev.c get_location(): mx/my/sx/sy come directly from
    // gx.xstart/ystart/xsize/ysize and are not clipped to map bounds.
    const hasSplevSpan = (game.sp_xsize ?? 0) > 0 && (game.sp_ysize ?? 0) > 0;
    return {
        mx: hasSplevSpan ? (game.sp_xstart ?? 0) : 1,
        my: hasSplevSpan ? (game.sp_ystart ?? 0) : 0,
        sx: hasSplevSpan ? game.sp_xsize : (COLNO - 1),
        sy: hasSplevSpan ? game.sp_ysize : ROWNO,
    };
}
function isFurnitureOrRock(loc) {
    if (!loc) return true;
    const typ = loc.typ;
    return typ === STONE || typ === FOUNTAIN || typ === THRONE || typ === SINK || typ === ALTAR;
}
function chooseSplevCoord(humidity = 'dry', coord = null) {
    if (coord) {
        const [x, y] = toAbsCoord(coord);
        return isok(x, y) ? { x, y } : null;
    }
    const bounds = game.currentRoom
        ? { lx: game.currentRoom.lx, ly: game.currentRoom.ly, hx: game.currentRoom.hx, hy: game.currentRoom.hy }
        : currentMapBounds();
    const width = Math.max(1, bounds.hx - bounds.lx + 1);
    const height = Math.max(1, bounds.hy - bounds.ly + 1);
    for (let attempt = 0; attempt < 100; attempt++) {
        let x;
        let y;
        if (game.currentRoom) {
            // C ref: sp_lev.c get_location(..., croom) uses somexy(croom, &tmpc),
            // and midlog wraps that call in non-mkroom translation units.
            const tmp = { x: 0, y: 0 };
            pushRngLogEntry('>somexy');
            const ok = !!somexy(game.currentRoom, tmp);
            pushRngLogEntry(`<somexy=${ok ? 1 : 0}`);
            if (!ok) continue;
            x = tmp.x;
            y = tmp.y;
        } else {
            x = bounds.lx + rn2(width);
            y = bounds.ly + rn2(height);
        }
        if (!isok(x, y)) continue;
        const loc = game.level?.at(x, y);
        if (!loc) continue;
        if (humidity === 'dry' && isFurnitureOrRock(loc)) continue;
        return { x, y };
    }
    return null;
}
function chooseFilteredCoord(coord, predicate) {
    if (coord) {
        const [x, y] = toAbsCoord(coord);
        return (isok(x, y) && predicate(x, y)) ? { x, y } : null;
    }
    const bounds = game.currentRoom
        ? { lx: game.currentRoom.lx, ly: game.currentRoom.ly, hx: game.currentRoom.hx, hy: game.currentRoom.hy }
        : currentMapBounds();
    const width = Math.max(1, bounds.hx - bounds.lx + 1);
    const height = Math.max(1, bounds.hy - bounds.ly + 1);
    for (let attempt = 0; attempt < 100; attempt++) {
        const x = bounds.lx + rn2(width);
        const y = bounds.ly + rn2(height);
        if (!isok(x, y)) continue;
        if (predicate(x, y)) return { x, y };
    }
    return null;
}
function randomSelectionCoord() {
    const bounds = game.currentRoom
        ? { lx: game.currentRoom.lx, ly: game.currentRoom.ly, hx: game.currentRoom.hx, hy: game.currentRoom.hy }
        : currentMapBounds();
    const width = Math.max(1, bounds.hx - bounds.lx + 1);
    const height = Math.max(1, bounds.hy - bounds.ly + 1);
    return {
        x: bounds.lx + rn2(width),
        y: bounds.ly + rn2(height),
    };
}
function resolveSelectionCoord(x = -1, y = -1) {
    if (x === -1 && y === -1) return randomSelectionCoord();
    const abs = toAbsCoord([x, y]);
    if (!abs) return null;
    return { x: abs[0], y: abs[1] };
}
function selectionDoLine(x1, y1, x2, y2, sel) {
    let d0, dx, dy, ai, bi, xi, yi;
    if (x1 < x2) {
        xi = 1;
        dx = x2 - x1;
    } else {
        xi = -1;
        dx = x1 - x2;
    }
    if (y1 < y2) {
        yi = 1;
        dy = y2 - y1;
    } else {
        yi = -1;
        dy = y1 - y2;
    }
    sel.setAbsPoint(x1, y1, 1);
    if (!dx && !dy) {
        return;
    } else if (dx > dy) {
        ai = (dy - dx) * 2;
        bi = dy * 2;
        d0 = bi - dx;
        do {
            if (d0 >= 0) {
                y1 += yi;
                d0 += ai;
            } else {
                d0 += bi;
            }
            x1 += xi;
            sel.setAbsPoint(x1, y1, 1);
        } while (x1 !== x2);
    } else {
        ai = (dx - dy) * 2;
        bi = dx * 2;
        d0 = bi - dy;
        do {
            if (d0 >= 0) {
                x1 += xi;
                d0 += ai;
            } else {
                d0 += bi;
            }
            y1 += yi;
            sel.setAbsPoint(x1, y1, 1);
        } while (y1 !== y2);
    }
}
function selectionDoRandline(x1, y1, x2, y2, rough, rec, sel) {
    if (rec < 1 || (x2 === x1 && y2 === y1)) return;
    const span = Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1));
    if (rough > span) rough = span;
    let mx, my;
    if (rough < 2) {
        mx = Math.trunc((x1 + x2) / 2);
        my = Math.trunc((y1 + y2) / 2);
    } else {
        do {
            const dx = rn2(rough) - Math.trunc(rough / 2);
            const dy = rn2(rough) - Math.trunc(rough / 2);
            mx = Math.trunc((x1 + x2) / 2) + dx;
            my = Math.trunc((y1 + y2) / 2) + dy;
        } while (mx > COLNO - 1 || mx < 0 || my < 0 || my > ROWNO - 1);
    }
    if (!sel.points.some((pt) => pt.x === mx && pt.y === my)) {
        sel.setAbsPoint(mx, my, 1);
    }
    rough = Math.trunc((rough * 2) / 3);
    rec--;
    selectionDoRandline(x1, y1, mx, my, rough, rec, sel);
    selectionDoRandline(mx, my, x2, y2, rough, rec, sel);
    sel.setAbsPoint(x2, y2, 1);
}
function selectionDoEllipse(sel, xc, yc, a, b, filled) {
    let x = 0;
    let y = b;
    const a2 = a * a;
    const b2 = b * b;
    const crit1 = -(Math.trunc(a2 / 4) + (a % 2) + b2);
    const crit2 = -(Math.trunc(b2 / 4) + (b % 2) + a2);
    const crit3 = -(Math.trunc(b2 / 4) + (b % 2));
    let t = -a2 * y;
    let dxt = 2 * b2 * x;
    let dyt = -2 * a2 * y;
    const d2xt = 2 * b2;
    const d2yt = 2 * a2;
    let width = 1;
    filled = !filled;
    if (!filled) {
        while (y >= 0 && x <= a) {
            sel.setAbsPoint(xc + x, yc + y, 1);
            if (x !== 0 || y !== 0) sel.setAbsPoint(xc - x, yc - y, 1);
            if (x !== 0 && y !== 0) {
                sel.setAbsPoint(xc + x, yc - y, 1);
                sel.setAbsPoint(xc - x, yc + y, 1);
            }
            if (t + b2 * x <= crit1 || t + a2 * y <= crit3) {
                x++;
                dxt += d2xt;
                t += dxt;
            } else if (t - a2 * y > crit2) {
                y--;
                dyt += d2yt;
                t += dyt;
            } else {
                x++;
                dxt += d2xt;
                t += dxt;
                y--;
                dyt += d2yt;
                t += dyt;
            }
        }
    } else {
        while (y >= 0 && x <= a) {
            if (t + b2 * x <= crit1 || t + a2 * y <= crit3) {
                x++;
                dxt += d2xt;
                t += dxt;
                width += 2;
            } else if (t - a2 * y > crit2) {
                for (let i = 0; i < width; i++) sel.setAbsPoint(xc - x + i, yc - y, 1);
                if (y !== 0) {
                    for (let i = 0; i < width; i++) sel.setAbsPoint(xc - x + i, yc + y, 1);
                }
                y--;
                dyt += d2yt;
                t += dyt;
            } else {
                for (let i = 0; i < width; i++) sel.setAbsPoint(xc - x + i, yc - y, 1);
                if (y !== 0) {
                    for (let i = 0; i < width; i++) sel.setAbsPoint(xc - x + i, yc + y, 1);
                }
                x++;
                dxt += d2xt;
                t += dxt;
                y--;
                dyt += d2yt;
                t += dyt;
                width += 2;
            }
        }
    }
}
function withCurrentRoom(rm, fn) {
    const prev = game.currentRoom;
    const coder = ensureDesCoder();
    const prevCoderRoom = coder.croom ?? null;
    game.currentRoom = rm;
    coder.croom = rm ?? null;
    try {
        const out = fn();
        if (out && typeof out.then === 'function') {
            return out.finally(() => {
                game.currentRoom = prev;
                coder.croom = prevCoderRoom;
            });
        }
        game.currentRoom = prev;
        coder.croom = prevCoderRoom;
        return out;
    } catch (err) {
        game.currentRoom = prev;
        coder.croom = prevCoderRoom;
        throw err;
    } finally {
        // Async callbacks restore _currentRoom in Promise.finally() above.
    }
}
function noncoalignment(alignment) {
    const k = rn2(2);
    if (!alignment) return k ? A_CHAOTIC : A_LAWFUL;
    return k ? -alignment : A_NEUTRAL;
}
function isSpecialLevel(lev = game.u?.uz) {
    if (!lev) return null;
    let slev = game.sp_levchn;
    while (slev) {
        const d = slev.dlevel;
        if (d && d.dnum === lev.dnum && d.dlevel === lev.dlevel) return slev;
        slev = slev.next;
    }
    return null;
}
function inducedAlign(pct) {
    const lev = isSpecialLevel(game.u?.uz);
    // C uses Is_special(&u.uz)->flags.align first. Tutorial flow can run level
    // scripts outside the normal special-level chain but still sets the same
    // effective alignment in game.special_level_align.
    const levAlign = (lev?.flags?.align || (game.special_level_align ?? 0));
    if (levAlign && rn2(100) < pct) return levAlign;
    const dnum = game.u?.uz?.dnum ?? 0;
    const dungeonAlign = game.dungeons?.[dnum]?.flags?.align ?? 0;
    if (dungeonAlign && rn2(100) < pct) return dungeonAlign;
    return Align2amask(rn2(3) - 1);
}
function spAmaskToAmask(spAmask) {
    if (spAmask === AM_SPLEV_CO) return Align2amask(game.u?.ualignbase?.[0] ?? A_NONE);
    if (spAmask === AM_SPLEV_NONCO) return Align2amask(noncoalignment(game.u?.ualignbase?.[0] ?? A_NONE));
    if (spAmask === AM_SPLEV_RANDOM) {
        return inducedAlign(80) & AM_MASK;
    }
    return spAmask & AM_MASK;
}
function addDoorToRoom(x, y, room) {
    if (!room || room.hx < 0) return;
    if (!game.level.doors) game.level.doors = [];
    for (let i = 0; i < room.doorct; i++) {
        const d = game.level.doors[room.fdoor + i];
        if (d && d.x === x && d.y === y) return;
    }
    if (room.doorct === 0) room.fdoor = game.level.doorindex || 0;
    room.doorct++;
    const ins = room.fdoor || 0;
    const doorindex = game.level.doorindex || 0;
    // C ref: mklev.c:add_door() insertion semantics used by link_doors_rooms().
    for (let tmp = doorindex; tmp > ins; tmp--) {
        game.level.doors[tmp] = game.level.doors[tmp - 1];
    }
    for (const broom of game.level.rooms || []) {
        if (!broom || broom.hx <= 0 || broom === room || !(broom.doorct > 0)) continue;
        if ((broom.fdoor ?? 0) >= ins) broom.fdoor++;
    }
    for (const prow of game.level.rooms || []) {
        if (!prow || prow.hx <= 0) continue;
        for (let m = 0; m < (prow.nsubrooms || 0); m++) {
            const broom = prow.sbrooms?.[m];
            if (!broom || broom === room || !(broom.doorct > 0)) continue;
            if ((broom.fdoor ?? 0) >= ins) broom.fdoor++;
        }
    }
    game.level.doors[ins] = { x, y };
    game.level.doorindex = doorindex + 1;
}
function sharedWithRoom(x, y, room) {
    const rmno = (room.roomnoidx ?? -1) + ROOMOFFSET;
    if (!isok(x, y)) return false;
    if ((game.level?.at(x, y)?.roomno ?? 0) === rmno && !game.level?.at(x, y)?.edge) return false;
    if (isok(x - 1, y)) {
        const loc = game.level?.at(x - 1, y);
        if (loc && loc.roomno === rmno && x - 1 <= room.hx) return true;
    }
    if (isok(x + 1, y)) {
        const loc = game.level?.at(x + 1, y);
        if (loc && loc.roomno === rmno && x + 1 >= room.lx) return true;
    }
    if (isok(x, y - 1)) {
        const loc = game.level?.at(x, y - 1);
        if (loc && loc.roomno === rmno && y - 1 <= room.hy) return true;
    }
    if (isok(x, y + 1)) {
        const loc = game.level?.at(x, y + 1);
        if (loc && loc.roomno === rmno && y + 1 >= room.ly) return true;
    }
    return false;
}
function maybeAddDoor(x, y, room) {
    const rmno = (room.roomnoidx ?? -1) + ROOMOFFSET;
    const loc = game.level?.at(x, y);
    if (!room || room.hx < 0 || !loc) return;
    const inRect = x >= room.lx && x <= room.hx && y >= room.ly && y <= room.hy;
    if ((!room.irregular && inRect) || loc.roomno === rmno || sharedWithRoom(x, y, room)) {
        addDoorToRoom(x, y, room);
    }
}
function addDoorsToRoom(room) {
    if (!room || !game.level) return;
    for (let x = room.lx - 1; x <= room.hx + 1; x++) {
        for (let y = room.ly - 1; y <= room.hy + 1; y++) {
            const loc = game.level.at(x, y);
            if (loc && (IS_DOOR(loc.typ) || loc.typ === SDOOR)) maybeAddDoor(x, y, room);
        }
    }
    for (const subroom of room.sbrooms || []) addDoorsToRoom(subroom);
}
function linkDoorsRooms() {
    const level = game.level;
    if (!level) return;
    const roomCount = level.nroom ?? 0;
    for (let y = 0; y < ROWNO; y++) {
        for (let x = 0; x < COLNO; x++) {
            const loc = level.at(x, y);
            if (!loc || (!IS_DOOR(loc.typ) && loc.typ !== SDOOR)) continue;
            // C ref: sp_lev.c link_doors_rooms() sets orientation for
            // MAP '+/S' tiles that don't go through explicit door directives.
            setDoorOrientation(x, y);
            for (let i = 0; i < roomCount; i++) {
                const room = level.rooms?.[i];
                if (!room) continue;
                maybeAddDoor(x, y, room);
                for (const subroom of room.sbrooms || []) {
                    maybeAddDoor(x, y, subroom);
                }
            }
        }
    }
}
function rnddoor() {
    const states = [D_NODOOR, D_BROKEN, D_ISOPEN, D_CLOSED, D_LOCKED];
    return states[rn2(states.length)];
}
function setDoorOrientation(x, y) {
    const doorJoin = (nx, ny) => {
        if (!isok(nx, ny)) return true;
        const loc = game.level?.at(nx, ny);
        return !!(loc && (IS_OBSTRUCTED(loc.typ) || loc.typ === IRONBARS));
    };
    const adjDoorish = (nx, ny) => {
        if (!isok(nx, ny)) return false;
        const loc = game.level?.at(nx, ny);
        return !!(loc && (IS_WALL(loc.typ) || IS_DOOR(loc.typ) || loc.typ === SDOOR));
    };
    let wleft = adjDoorish(x - 1, y);
    let wright = adjDoorish(x + 1, y);
    let wup = adjDoorish(x, y - 1);
    let wdown = adjDoorish(x, y + 1);
    if (!wleft && !wright && !wup && !wdown) {
        wleft = doorJoin(x - 1, y);
        wright = doorJoin(x + 1, y);
        wup = doorJoin(x, y - 1);
        wdown = doorJoin(x, y + 1);
    }
    const loc = game.level?.at(x, y);
    if (loc) loc.horizontal = ((wleft || wright) && !(wup && wdown)) ? 1 : 0;
}
function selSetDoor(x, y, typ) {
    const loc = game.level?.at(x, y);
    if (!loc) return;
    if (!IS_DOOR(loc.typ) && loc.typ !== SDOOR) loc.typ = (typ & D_SECRET) ? SDOOR : DOOR;
    if (typ & D_SECRET) {
        typ &= ~D_SECRET;
        if (typ < D_CLOSED) typ = D_CLOSED;
    }
    setDoorOrientation(x, y);
    loc.flags = typ;
    markSpLevMap(x, y);
}
function createDoor(dd, room) {
    if (!room) return null;
    let x = 0;
    let y = 0;
    if (dd.secret === -1) dd.secret = rn2(2);
    if (dd.wall === W_RANDOM) dd.wall = W_ANY;
    if (dd.mask === -1) {
        if (!dd.secret) {
            if (!rn2(3)) {
                if (!rn2(5)) dd.mask = D_ISOPEN;
                else if (!rn2(6)) dd.mask = D_LOCKED;
                else dd.mask = D_CLOSED;
                if (dd.mask !== D_ISOPEN && !rn2(25)) dd.mask |= D_TRAPPED;
            } else {
                dd.mask = D_NODOOR;
            }
        } else {
            dd.mask = !rn2(5) ? D_LOCKED : D_CLOSED;
            if (!rn2(20)) dd.mask |= D_TRAPPED;
        }
    }
    for (let trycnt = 0; trycnt < 100; ++trycnt) {
        const dwall = dd.wall;
        const dpos = dd.pos;
        switch (rn2(4)) {
        case 0:
            if (!(dwall & W_NORTH)) continue;
            y = room.ly - 1;
            x = room.lx + (dpos === -1 ? rn2(1 + room.hx - room.lx) : dpos);
            if (!isok(x, y - 1) || IS_OBSTRUCTED(game.level?.at(x, y - 1)?.typ)) continue;
            break;
        case 1:
            if (!(dwall & W_SOUTH)) continue;
            y = room.hy + 1;
            x = room.lx + (dpos === -1 ? rn2(1 + room.hx - room.lx) : dpos);
            if (!isok(x, y + 1) || IS_OBSTRUCTED(game.level?.at(x, y + 1)?.typ)) continue;
            break;
        case 2:
            if (!(dwall & W_WEST)) continue;
            x = room.lx - 1;
            y = room.ly + (dpos === -1 ? rn2(1 + room.hy - room.ly) : dpos);
            if (!isok(x - 1, y) || IS_OBSTRUCTED(game.level?.at(x - 1, y)?.typ)) continue;
            break;
        case 3:
            if (!(dwall & W_EAST)) continue;
            x = room.hx + 1;
            y = room.ly + (dpos === -1 ? rn2(1 + room.hy - room.ly) : dpos);
            if (!isok(x + 1, y) || IS_OBSTRUCTED(game.level?.at(x + 1, y)?.typ)) continue;
            break;
        }
        if (!game.level?.at(x, y)) continue;
        if (!isok(x, y)) continue;
        if (!(game.level.at(x, y).typ === HWALL || game.level.at(x, y).typ === VWALL) && !IS_DOOR(game.level.at(x, y).typ) && game.level.at(x, y).typ !== SDOOR) continue;
        const bydoor = [
            [1, 0], [-1, 0], [0, 1], [0, -1],
        ].some(([dx, dy]) => {
            const adj = game.level?.at(x + dx, y + dy);
            return !!(adj && (IS_DOOR(adj.typ) || adj.typ === SDOOR));
        });
        if (bydoor) continue;
        const loc = game.level.at(x, y);
        loc.typ = dd.secret ? SDOOR : DOOR;
        loc.flags = dd.mask;
        return { x, y };
    }
    return null;
}
function getTableAlign(align) {
    if (typeof align === 'number') return Align2amask(align);
    switch (String(align || 'random').toLowerCase()) {
    case 'chaos':
    case 'chaotic':
        return Align2amask(A_CHAOTIC);
    case 'neutral':
        return Align2amask(A_NEUTRAL);
    case 'law':
    case 'lawful':
        return Align2amask(A_LAWFUL);
    case 'noalign':
    case 'unaligned':
        return Align2amask(A_NONE);
    case 'coaligned':
        return AM_SPLEV_CO;
    case 'noncoaligned':
        return AM_SPLEV_NONCO;
    case 'random':
    default:
        return AM_SPLEV_RANDOM;
    }
}
// ── des.* API for special levels ──
// C ref: sp_lev.c — these functions are called by Lua level scripts
// (converted to JS in js/levels/*.js).
 // tracks squeaky board traps for choose_trapnote
function resetXyStartSize() {
    // C ref: sp_lev.c reset_xystart_size()
    game.sp_xstart = 1;
    game.sp_ystart = 0;
    game.sp_xsize = COLNO - 1;
    game.sp_ysize = ROWNO;
}
export function reset_des_coder() {
    game.des_coder = null;
    game.splev_init_present = false;
    game.icedpools = false;
    resetXyStartSize();
    game.sp_lev_map = Array.from({ length: COLNO }, () => Array(ROWNO).fill(0));
    game.sqkyBoardCount = 0;
    game.currentRoom = null;
}
function ensureDesCoder() {
    if (!game.des_coder) {
        game.des_coder = {
            premapped: false,
            solidify: false,
            check_inaccessibles: false,
            allow_flips: 3,
            finalized: false,
            croom: null,
            n_subroom: 1,
            lvl_is_joined: false,
            room_stack: 0,
            tmproomlist: Array(MAX_NESTED_ROOMS + 1).fill(null),
            failed_room: Array(MAX_NESTED_ROOMS + 1).fill(false),
        };
        game.splev_init_present = false;
        game.icedpools = false;
        resetXyStartSize();
        if (!game.sp_lev_map) {
            game.sp_lev_map = Array.from({ length: COLNO }, () => Array(ROWNO).fill(0));
        }
    }
    return game.des_coder;
}
function updateCroom() {
    const coder = game.des_coder;
    if (!coder) return;
    coder.croom = coder.n_subroom ? (coder.tmproomlist[coder.n_subroom - 1] ?? null) : null;
}
function spoEndroom(coder) {
    if (!coder) return;
    if (coder.n_subroom > 1) {
        coder.n_subroom--;
        coder.tmproomlist[coder.n_subroom] = null;
        coder.failed_room[coder.n_subroom] = true;
    }
    updateCroom();
}
const ROOM_XALIGN = {
    left: 1,
    'half-left': 2,
    center: 3,
    'half-right': 4,
    right: 5,
    none: -1,
    random: -1,
};
const ROOM_YALIGN = {
    top: 1,
    center: 3,
    bottom: 5,
    none: -1,
    random: -1,
};
const ROOM_TYPES = {
    ordinary: OROOM,
    themed: THEMEROOM,
    throne: COURT,
    swamp: SWAMP,
    vault: VAULT,
    beehive: BEEHIVE,
    morgue: MORGUE,
    barracks: BARRACKS,
    zoo: ZOO,
    delphi: DELPHI,
    temple: TEMPLE,
    anthole: ANTHOLE,
    cocknest: COCKNEST,
    leprehall: LEPREHALL,
    shop: SHOPBASE,
    'armor shop': ARMORSHOP,
    'scroll shop': SCROLLSHOP,
    'potion shop': POTIONSHOP,
    'weapon shop': WEAPONSHOP,
    'food shop': FOODSHOP,
    'ring shop': RINGSHOP,
    'wand shop': WANDSHOP,
    'tool shop': TOOLSHOP,
    'book shop': BOOKSHOP,
    'health food shop': FODDERSHOP,
    'candle shop': CANDLESHOP,
};
function getRoomTypeOpt(type) {
    if (type == null) return OROOM;
    return ROOM_TYPES[String(type).toLowerCase()] ?? OROOM;
}
function buildRoom(roomSpec, parentRoom) {
    const rtype = (!roomSpec.chance || rn2(100) < roomSpec.chance) ? roomSpec.rtype : OROOM;
    let okroom = false;
    let aroom = null;
    if (parentRoom) {
        okroom = create_subroom(
            parentRoom,
            roomSpec.x,
            roomSpec.y,
            roomSpec.w,
            roomSpec.h,
            rtype,
            roomSpec.rlit,
        );
        if (okroom) {
            aroom = game.subrooms?.[game.subrooms.length - 1] ?? null;
        }
    } else {
        okroom = create_room(
            roomSpec.x,
            roomSpec.y,
            roomSpec.w,
            roomSpec.h,
            roomSpec.xalign,
            roomSpec.yalign,
            rtype,
            roomSpec.rlit,
            true,
        );
        if (okroom) {
            aroom = game.level.rooms?.[(game.level.nroom ?? 1) - 1] ?? null;
        }
    }
    if (okroom && aroom) {
        topologize(aroom);
        aroom.needfill = roomSpec.needfill;
        aroom.needjoining = roomSpec.joined;
        return aroom;
    }
    return null;
}
function markSpLevMap(x, y) {
    if (!isok(x, y)) return;
    if (!game.sp_lev_map) {
        game.sp_lev_map = Array.from({ length: COLNO }, () => Array(ROWNO).fill(0));
    }
    game.sp_lev_map[x][y] = 1;
}
function clampInt(v, lo, hi) {
    if (v < lo) return lo;
    if (v > hi) return hi;
    return v;
}
function lvlfill_maze_grid(x1, y1, x2, y2, filling) {
    const level = game.level;
    if (!level) return;
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            const loc = level.at(x, y);
            if (!loc) continue;
            if (level.flags?.corrmaze) {
                loc.typ = STONE;
            } else {
                loc.typ = (y < 2 || ((x % 2) && (y % 2))) ? STONE : filling;
            }
            loc.flags = 0;
            loc.horizontal = 0;
            loc.roomno = 0;
            loc.edge = 0;
        }
    }
}
function setLevlTypLit(x, y, typ, lit) {
    const loc = game.level?.at(x, y);
    if (!loc) return false;
    if (!set_levltyp(x, y, typ)) return false;
    if (lit !== SET_LIT_NOCHANGE) {
        let litstate = lit;
        if (IS_LAVA(typ)) litstate = 1;
        else if (litstate === -1) litstate = rn2(2);
        loc.lit = !!litstate;
        loc.waslit = !!loc.lit;
    }
    return true;
}
function lvlfill_swamp(fg, bg, lit) {
    const xMax = game.x_maze_max ?? ((COLNO - 1) & ~1);
    const yMax = game.y_maze_max ?? ((ROWNO - 1) & ~1);
    lvlfill_solid(bg, lit);
    for (let x = 2; x <= Math.min(xMax, COLNO - 2); x += 2) {
        for (let y = 0; y <= Math.min(yMax, ROWNO - 2); y += 2) {
            let c = 0;
            setLevlTypLit(x, y, fg, lit);
            if (game.level?.at(x + 1, y)?.typ === bg) c++;
            if (game.level?.at(x, y + 1)?.typ === bg) c++;
            if (game.level?.at(x + 1, y + 1)?.typ === bg) c++;
            if (c === 3) {
                switch (rn2(3)) {
                case 0:
                    setLevlTypLit(x + 1, y, fg, lit);
                    break;
                case 1:
                    setLevlTypLit(x, y + 1, fg, lit);
                    break;
                case 2:
                    setLevlTypLit(x + 1, y + 1, fg, lit);
                    break;
                default:
                    break;
                }
            }
        }
    }
}
function createMaze(corrwid, wallthick, rmdeadends) {
    const map = game.level;
    if (!map) return;
    const defaultXMax = (COLNO - 1) & ~1;
    const defaultYMax = (ROWNO - 1) & ~1;
    const tmpXMax = game.x_maze_max ?? defaultXMax;
    const tmpYMax = game.y_maze_max ?? defaultYMax;
    let cw = Number.isFinite(corrwid) ? corrwid : -1;
    let wt = Number.isFinite(wallthick) ? wallthick : -1;
    if (cw === -1) cw = rnd(4);
    if (wt === -1) wt = rnd(4) - cw;
    cw = clampInt(cw, 1, 5);
    wt = clampInt(wt, 1, 5);
    const scale = cw + wt;
    const rdx = Math.trunc(tmpXMax / scale);
    const rdy = Math.trunc(tmpYMax / scale);
    if (map.flags?.corrmaze) {
        for (let x = 2; x < (rdx * 2); x++) {
            for (let y = 2; y < (rdy * 2); y++) {
                const loc = map.at(x, y);
                if (loc) loc.typ = STONE;
            }
        }
    } else {
        for (let x = 2; x <= (rdx * 2); x++) {
            for (let y = 2; y <= (rdy * 2); y++) {
                const loc = map.at(x, y);
                if (!loc) continue;
                loc.typ = ((x % 2) && (y % 2)) ? STONE : HWALL;
            }
        }
    }
    game.x_maze_max = rdx * 2;
    game.y_maze_max = rdy * 2;
    try {
        const xChoices = (game.x_maze_max >> 1) - 1;
        const yChoices = (game.y_maze_max >> 1) - 1;
        const mx = 3 + 2 * rn2(xChoices);
        const my = 3 + 2 * rn2(yChoices);
        walkfrom(mx, my, 0);
        // C ref: mkmaze.c:997-998 — remove dead ends after maze carving
        if (rmdeadends)
            maze_remove_deadends(game.level?.flags?.corrmaze ? CORR : ROOM);
    } finally {
        game.x_maze_max = tmpXMax;
        game.y_maze_max = tmpYMax;
    }
    if (scale > 2) {
        const src = Array.from({ length: COLNO }, () => Array(ROWNO).fill(STONE));
        for (let x = 1; x < tmpXMax; x++) {
            for (let y = 1; y < tmpYMax; y++) {
                src[x][y] = map.at(x, y)?.typ ?? STONE;
            }
        }
        let rx = 2;
        let x = 2;
        while (rx < tmpXMax) {
            const mx = (x % 2) ? cw : ((x === 2 || x === rdx * 2) ? 1 : wt);
            let ry = 2;
            let y = 2;
            while (ry < tmpYMax) {
                const my = (y % 2) ? cw : ((y === 2 || y === rdy * 2) ? 1 : wt);
                for (let dx = 0; dx < mx; dx++) {
                    for (let dy = 0; dy < my; dy++) {
                        if (rx + dx >= tmpXMax || ry + dy >= tmpYMax) break;
                        const loc = map.at(rx + dx, ry + dy);
                        if (loc) loc.typ = src[x][y];
                    }
                }
                ry += my;
                y++;
            }
            rx += mx;
            x++;
        }
    }
}
// des.level_init — C ref: sp_lev.c:5989 lspo_level_init()
export function level_init(args = {}) {
    const coder = ensureDesCoder();
    game.splev_init_present = true;
    const style = String(args.style || 'solidfill').toLowerCase();
    const lit = args.lit;
    const bgArg = args.bg;
    const corrwid = Number.isFinite(args.corrwid) ? args.corrwid : -1;
    const wallthick = Number.isFinite(args.wallthick) ? args.wallthick : -1;
    // C: rm_deadends = !get_table_boolean_opt("deadends", TRUE)
    // Default is TRUE (keep dead ends), so rm_deadends defaults to FALSE.
    // Only rm_deadends when deadends is explicitly set to false/0.
    const deadendsOpt = args.deadends ?? true; // default: keep dead ends
    const rmdeadends = !deadendsOpt;
    const joined = !!args.joined;
    coder.lvl_is_joined = joined;
    const litRandom = (lit == null || lit === 'random' || lit === -1);
    // C ref: splev_initlev() ALWAYS consumes rn2(2) for solidfill when
    // lit is BOOL_RANDOM (sp_lev.c:2991-2992). The initial dungeon level
    // doesn't call level_init (it uses makelevel without a level script),
    // so this code only runs for special levels which always need rn2(2).
    if (style === 'solidfill') {
        // C ref: splev_initlev LVLINIT_SOLIDFILL
        let solidLit = litRandom ? -1 : (lit ? 1 : 0);
        if (litRandom) {
            solidLit = rn2(2);
        }
        // Parse fg for solidfill
        let solidFg = ROOM; // default fg
        if (typeof args.fg === 'string' && args.fg.length > 0) {
            const parsed = splev_chr2typ(args.fg[0]);
            if (parsed >= 0) solidFg = parsed;
        }
        lvlfill_solid(solidFg, solidLit);
    }
    let bg = STONE;
    if (typeof bgArg === 'string' && bgArg.length > 0) {
        const parsed = splev_chr2typ(bgArg[0]);
        if (parsed >= 0 && parsed < MAX_TYPE) bg = parsed;
    }
    // C ref: splev_initlev() — style="maze"
    if (style === 'mazegrid') {
        const xMazeMax = game.x_maze_max ?? ((COLNO - 1) & ~1);
        const yMazeMax = game.y_maze_max ?? ((ROWNO - 1) & ~1);
        lvlfill_maze_grid(2, 0, xMazeMax, yMazeMax, bg);
    } else if (style === 'maze') {
        createMaze(corrwid, wallthick, rmdeadends);
    } else if (style === 'swamp') {
        let swampLit = litRandom ? rn2(2) : (lit ? 1 : 0);
        let swampFg = ROOM;
        if (typeof args.fg === 'string' && args.fg.length > 0) {
            const parsed = splev_chr2typ(args.fg[0]);
            if (parsed >= 0 && parsed < MAX_TYPE) swampFg = parsed;
        }
        let swampBg = MOAT;
        if (typeof bgArg === 'string' && bgArg.length > 0) {
            const parsed = splev_chr2typ(bgArg[0]);
            if (parsed >= 0 && parsed < MAX_TYPE) swampBg = parsed;
        }
        lvlfill_swamp(swampFg, swampBg, swampLit);
    } else if (style === 'mines') {
        // C ref: sp_lev.c LVLINIT_MINES case
        // C: if lit is random, consume rn2(2)
        const mineLit = litRandom ? rn2(2) : (lit ? 1 : 0);
        // Parse fg terrain
        let fg = ROOM; // C default: fg = ROOM (get_table_mapchr_opt "fg" default)
        if (typeof args.fg === 'string' && args.fg.length > 0) {
            const parsed = splev_chr2typ(args.fg[0]);
            if (parsed >= 0) fg = parsed;
        }
        // C: filling defaults to fg. If filling > -1, fill map first.
        const filling = (typeof args.filling === 'string' && args.filling.length > 0)
            ? splev_chr2typ(args.filling[0]) : fg;
        if (filling > -1) {
            lvlfill_solid(filling, 0);
        }
        mkmap({
            bg, fg, smoothed: !!args.smoothed, joined: !!args.joined,
            lit: mineLit, walled: !!args.walled, icedpools: false,
        });
    }
}
// C ref: sp_lev.c lvlfill_solid — fill map area with terrain type
function lvlfill_solid(filling, lit) {
    const map = game.level;
    const xMax = game.x_maze_max ?? ((COLNO - 1) & ~1);
    const yMax = game.y_maze_max ?? ((ROWNO - 1) & ~1);
    for (let x = 2; x <= xMax; x++) {
        for (let y = 0; y <= yMax; y++) {
            const loc = map.at(x, y);
            if (!loc) continue;
            setLevlTypLit(x, y, filling, lit);
            loc.flags = 0;
            loc.horizontal = false;
            loc.roomno = 0;
            loc.edge = false;
        }
    }
}
function inEndgame() {
    return game.u?.uz?.dnum === game.astral_level?.dnum;
}
function isMedusaLevel() {
    const medusa = game.medusa_level;
    const uz = game.u?.uz;
    return !!medusa && !!uz
        && medusa.dnum === uz.dnum
        && medusa.dlevel === uz.dlevel;
}
function isBaalzLevel() {
    const baalz = game.baalzebub_level;
    const uz = game.u?.uz;
    return !!baalz && !!uz
        && baalz.dnum === uz.dnum
        && baalz.dlevel === uz.dlevel;
}
function withinArea(x, y, area) {
    return !!area
        && x >= area.x1 && x <= area.x2
        && y >= area.y1 && y <= area.y2;
}
function baalzFixupMinimal() {
    const level = game.level;
    if (!level) return;
    const inarea = { x1: COLNO, y1: ROWNO, x2: 0, y2: 0 };
    const delarea = { x1: COLNO, y1: ROWNO, x2: 0, y2: 0 };
    const hasNondiggable = (loc) => (((loc?.wall_info ?? 0) & W_NONDIGGABLE) !== 0);
    const clearNondiggable = (loc) => {
        if (!loc) return;
        loc.wall_info &= ~W_NONDIGGABLE;
    };
    const midY = Math.trunc(ROWNO / 2);
    let lastx = 0;
    let x = 0;
    for (x = 0; x < COLNO; ++x) {
        if (hasNondiggable(level.at(x, midY))) {
            if (!lastx) inarea.x1 = x + 1;
            lastx = x;
        }
    }
    inarea.x2 = ((lastx > inarea.x1) ? lastx : x) - 1;
    const anchorX = inarea.x1;
    let lasty = 0;
    let y = 0;
    for (y = 0; y < ROWNO; ++y) {
        if (hasNondiggable(level.at(anchorX, y))) {
            if (!lasty) inarea.y1 = y + 1;
            lasty = y;
        }
    }
    inarea.y2 = ((lasty > inarea.y1) ? lasty : y) - 1;
    for (x = inarea.x1; x <= inarea.x2; ++x) {
        for (y = inarea.y1; y <= inarea.y2; ++y) {
            const loc = level.at(x, y);
            if (!loc) continue;
            if (loc.typ === POOL) {
                loc.typ = HWALL;
                if (delarea.x1 === COLNO) {
                    delarea.x1 = x;
                    delarea.y1 = y;
                } else {
                    delarea.x2 = x;
                    delarea.y2 = y;
                }
            } else if (loc.typ === IRONBARS) {
                if (isok(x - 1, y) && hasNondiggable(level.at(x - 1, y))) {
                    clearNondiggable(level.at(x - 1, y));
                    if (isok(x - 2, y)) clearNondiggable(level.at(x - 2, y));
                } else if (isok(x + 1, y) && hasNondiggable(level.at(x + 1, y))) {
                    clearNondiggable(level.at(x + 1, y));
                    if (isok(x + 2, y)) clearNondiggable(level.at(x + 2, y));
                }
            }
        }
    }
    wall_cleanup_protected(
        Math.max(inarea.x1 - 2, 1),
        Math.max(inarea.y1 - 2, 0),
        Math.min(inarea.x2 + 2, COLNO - 1),
        Math.min(inarea.y2 + 2, ROWNO - 1),
        inarea
    );
    fix_wall_spines(
        Math.max(inarea.x1 - 2, 1),
        Math.max(inarea.y1 - 2, 0),
        Math.min(inarea.x2 + 2, COLNO - 1),
        Math.min(inarea.y2 + 2, ROWNO - 1),
        inarea
    );
    x = delarea.x1;
    y = delarea.y1;
    if (isok(x, y)
        && (level.at(x, y)?.typ === TLWALL || level.at(x, y)?.typ === TRWALL)
        && isok(x, y + 1) && level.at(x, y + 1)?.typ === TUWALL) {
        level.at(x, y).typ = (level.at(x, y).typ === TLWALL) ? BRCORNER : BLCORNER;
        level.at(x, y + 1).typ = HWALL;
        const mtmp = m_at(x, y);
        if (mtmp && !rloc_mkmaze(mtmp)) {
            mtmp.mx = 0;
            mtmp.my = 0;
        }
    }
    x = delarea.x2;
    y = delarea.y2;
    if (isok(x, y)
        && (level.at(x, y)?.typ === TLWALL || level.at(x, y)?.typ === TRWALL)
        && isok(x, y - 1) && level.at(x, y - 1)?.typ === TDWALL) {
        level.at(x, y).typ = (level.at(x, y).typ === TLWALL) ? TRCORNER : TLCORNER;
        level.at(x, y - 1).typ = HWALL;
        const mtmp = m_at(x, y);
        if (mtmp && !rloc_mkmaze(mtmp)) {
            mtmp.mx = 0;
            mtmp.my = 0;
        }
    }
}
function unlinkMonster(mon) {
    if (game.level) game.level.removeMonster(mon);
    if (game.fmon === mon) {
        game.fmon = mon.nmon || null;
    } else {
        for (let prev = game.fmon; prev; prev = prev.nmon) {
            if (prev.nmon === mon) {
                prev.nmon = mon.nmon || null;
                break;
            }
        }
    }
    mon.dead = true;
}
function isOkLocation(x, y, humidity) {
    // C ref: sp_lev.c is_ok_location — accept any spot on Water level
    if (Is_waterlevel(game.u?.uz)) return true;
    const loc = game.level?.at(x, y);
    if (!loc) return false;
    const typ = loc.typ;
    if (humidity & ANY_LOC) {
        return true;
    }
    if ((humidity & SOLID) && IS_OBSTRUCTED(typ)) {
        return true;
    }
    if ((humidity & (DRY | SPACELOC)) && SPACE_POS(typ)) {
        const boulder = !!sobj_at(BOULDER, x, y);
        if (!boulder || (humidity & SOLID)) return true;
    }
    if ((humidity & WET) && is_pool(x, y)) {
        return true;
    }
    if ((humidity & HOT) && is_lava(x, y)) {
        return true;
    }
    return false;
}
function pmToHumidityFlags(pm) {
    let loc = DRY;
    if (!pm) return loc;
    if (pm.mlet === S_EEL || is_amphibious(pm) || is_swimmer(pm))
        loc = WET;
    if (is_flyer(pm) || is_floater(pm))
        loc |= (HOT | WET);
    if (passes_walls(pm) || noncorporeal(pm))
        loc |= SOLID;
    if (likes_fire(pm))
        loc |= HOT;
    return loc;
}
// C ref: sp_lev.c:get_location_coord() for random coords.
// For random packed coords, get_location_coord can invoke get_location() twice
// before returning failure. In JS, randomLocationWithHumidity() models one
// get_location() pass, so we explicitly perform the second pass here.
function randomLocationCoordLikeC(humidity, croom) {
    let pos = randomLocationWithHumidity(humidity, croom, true);
    if (!pos) {
        pos = randomLocationWithHumidity(humidity, croom, false);
    }
    return pos;
}
function randomLocationWithHumidity(humidity, croom, allowFail) {
    const debugGetloc = typeof process !== 'undefined'
        && process?.env?.SPLEV_GETLOC_DEBUG === '1';
    const useSomexyLog = !!croom;
    if (useSomexyLog) pushRngLogEntry('>somexy');
    let mx;
    let my;
    let sx;
    let sy;
    if (croom) {
        mx = croom.lx;
        my = croom.ly;
        sx = croom.hx - croom.lx + 1;
        sy = croom.hy - croom.ly + 1;
    } else {
        const span = getLocationSpan();
        mx = span.mx;
        my = span.my;
        sx = span.sx;
        sy = span.sy;
    }
    if (debugGetloc) {
        pushRngLogEntry(`^dbg_getloc_span[mx=${mx} my=${my} sx=${sx} sy=${sy} croom=${croom ? 1 : 0} h=${humidity}]`);
    }
    let x = -1;
    let y = -1;
    for (let cpt = 0; cpt < 100; cpt++) {
        if (croom) {
            const tmp = { x: -1, y: -1 };
            const ok = !!somexy(croom, tmp);
            if (!ok) continue;
            x = tmp.x;
            y = tmp.y;
        } else {
            x = mx + rn2(sx);
            y = my + rn2(sy);
        }
        const inBounds = isok(x, y);
        const typ = inBounds ? (game.level?.at(x, y)?.typ ?? -1) : -1;
        const bould = inBounds ? (sobj_at(BOULDER, x, y) ? 1 : 0) : -1;
        let bouldScan = -1;
        if (inBounds) {
            bouldScan = (game.level?.objects || []).some((obj) => obj?.otyp === BOULDER && obj?.ox === x && obj?.oy === y) ? 1 : 0;
        }
        const ok = inBounds && isOkLocation(x, y, humidity);
        if (debugGetloc) {
            pushRngLogEntry(`^dbg_getloc_try[cpt=${cpt} x=${x} y=${y} typ=${typ} b=${bould} bs=${bouldScan} h=${humidity} ok=${ok ? 1 : 0}]`);
        }
        if (ok) {
            if (useSomexyLog) pushRngLogEntry('<somexy=1');
            return { x, y };
        }
    }
    // C ref: sp_lev.c:get_location()
    // Even with NO_LOC_WARN (allowFail=true), C still performs a deterministic
    // full-area "last try" scan before giving up.
    for (let xx = 0; xx < sx; xx++) {
        for (let yy = 0; yy < sy; yy++) {
            x = mx + xx;
            y = my + yy;
            if (isok(x, y) && isOkLocation(x, y, humidity)) {
                if (useSomexyLog) pushRngLogEntry('<somexy=1');
                return { x, y };
            }
        }
    }
    if (allowFail) {
        if (useSomexyLog) pushRngLogEntry('<somexy=0');
        return null;
    }
    if (useSomexyLog) pushRngLogEntry('<somexy=0');
    return null;
}
function maze1xy(humidity) {
    const xMazeMax = (COLNO - 1) & ~1;
    const yMazeMax = (ROWNO - 1) & ~1;
    let x = 0;
    let y = 0;
    let tryct = 2000;
    do {
        x = rn1(xMazeMax - 3, 3);
        y = rn1(yMazeMax - 3, 3);
        if (--tryct < 0) break;
    } while (!(x % 2) || !(y % 2) || game.sp_lev_map?.[x]?.[y]
        || !isOkLocation(x, y, humidity));
    return { x, y };
}
function rndTrapSplev(mktrapflags = MKTRAP_MAZEFLAG) {
    const lvl = level_difficulty();
    let rtrap;
    do {
        rtrap = rnd(TRAPNUM - 1);
        switch (rtrap) {
        case TRAPPED_DOOR:
        case TRAPPED_CHEST:
        case MAGIC_PORTAL:
        case VIBRATING_SQUARE:
            rtrap = NO_TRAP;
            break;
        case ROLLING_BOULDER_TRAP:
        case SLP_GAS_TRAP:
            if (lvl < 2) rtrap = NO_TRAP;
            break;
        case LEVEL_TELEP:
            if (lvl < 5 || game.level?.flags?.noteleport || Is_knox_level(game.u?.uz)) rtrap = NO_TRAP;
            break;
        case SPIKED_PIT:
            if (lvl < 5) rtrap = NO_TRAP;
            break;
        case LANDMINE:
            if (lvl < 6) rtrap = NO_TRAP;
            break;
        case WEB:
            if (lvl < 7) rtrap = NO_TRAP;
            break;
        case STATUE_TRAP:
        case POLY_TRAP:
            if (lvl < 8) rtrap = NO_TRAP;
            break;
        case FIRE_TRAP:
            if (!Inhell()) rtrap = NO_TRAP;
            break;
        case TELEP_TRAP:
            if (game.level?.flags?.noteleport) rtrap = NO_TRAP;
            break;
        case HOLE:
            if (rn2(7)) rtrap = NO_TRAP;
            break;
        default:
            break;
        }
    } while (rtrap === NO_TRAP);
    return rtrap;
}
// C ref: mklev.c:2002 traptype_roguelvl()
function traptypeRogueLevel() {
    switch (rn2(7)) {
    default:
        return BEAR_TRAP; // 0
    case 1:
        return ARROW_TRAP;
    case 2:
        return DART_TRAP;
    case 3:
        return TRAPDOOR;
    case 4:
        return PIT;
    case 5:
        return SLP_GAS_TRAP;
    case 6:
        return RUST_TRAP;
    }
}
// C ref: mklev.c:mktrap() trap-kind selection.
function pickMktrapKind(num, mktrapFlags) {
    if (num > NO_TRAP && num < TRAPNUM) {
        return num;
    }
    if (Is_rogue_level(game.u?.uz)) {
        return traptypeRogueLevel();
    }
    if (Inhell() && !rn2(5)) {
        // Bias fire traps in Gehennom.
        return FIRE_TRAP;
    }
    return rndTrapSplev(mktrapFlags);
}
// C ref: sp_lev.c:1159 rndtrap()
function rndTrapSpecialLevel() {
    let rtrap;
    do {
        rtrap = rnd(TRAPNUM - 1);
        switch (rtrap) {
        case HOLE: /* no random holes on special levels */
        case VIBRATING_SQUARE:
        case MAGIC_PORTAL:
            rtrap = NO_TRAP;
            break;
        case TRAPDOOR:
            if (!Can_dig_down(game.u?.uz))
                rtrap = NO_TRAP;
            break;
        case LEVEL_TELEP:
        case TELEP_TRAP:
            if (game.level?.flags?.noteleport)
                rtrap = NO_TRAP;
            break;
        case ROLLING_BOULDER_TRAP:
        case ROCKTRAP:
            if (inEndgame())
                rtrap = NO_TRAP;
            break;
        default:
            break;
        }
    } while (rtrap === NO_TRAP);
    return rtrap;
}
async function fillEmptyMaze() {
    const xMazeMax = (COLNO - 1) & ~1;
    const yMazeMax = (ROWNO - 1) & ~1;
    let mapcountmax = (xMazeMax - 2) * (yMazeMax - 2);
    let mapcount = mapcountmax;
    mapcountmax = Math.trunc(mapcountmax / 2);
    for (let x = 2; x < xMazeMax; x++) {
        for (let y = 0; y < yMazeMax; y++) {
            if (game.sp_lev_map?.[x]?.[y]) mapcount--;
        }
    }
    if (mapcount <= Math.trunc(mapcountmax / 10)) return;
    const mapfact = Math.trunc((mapcount * 100) / mapcountmax);
    for (let x = rnd(Math.trunc((20 * mapfact) / 100)); x; x--) {
        const mm = maze1xy(DRY);
        mkobj_at(rn2(2) ? GEM_CLASS : RANDOM_CLASS, mm.x, mm.y, true);
    }
    for (let x = rnd(Math.trunc((12 * mapfact) / 100)); x; x--) {
        const mm = maze1xy(DRY);
        const ttmp = t_at(mm.x, mm.y);
        if (ttmp && (is_pit(ttmp.ttyp) || is_hole(ttmp.ttyp))) continue;
        mksobj_at(BOULDER, mm.x, mm.y, true, false);
    }
    for (let x = rn2(2); x; x--) {
        const mm = maze1xy(DRY);
        await makemon(mons[PM_MINOTAUR], mm.x, mm.y, 0);
    }
    for (let x = rnd(Math.trunc((12 * mapfact) / 100)); x; x--) {
        const mm = maze1xy(DRY);
        await makemon(null, mm.x, mm.y, 0);
    }
    for (let x = rn2(Math.trunc((15 * mapfact) / 100)); x; x--) {
        const mm = maze1xy(DRY);
        mkgold(0, mm.x, mm.y);
    }
    for (let x = rn2(Math.trunc((15 * mapfact) / 100)); x; x--) {
        const mm = maze1xy(DRY);
        let trytrap = rndTrapSpecialLevel();
        if (sobj_at(BOULDER, mm.x, mm.y)) {
            while (is_pit(trytrap) || is_hole(trytrap)) {
                trytrap = rndTrapSpecialLevel();
            }
        }
        await maketrap(mm.x, mm.y, trytrap);
    }
}
// des.mazewalk — C ref: sp_lev.c:5769 lspo_mazewalk()
export async function mazewalk(...rawArgs) {
    const dirMap = {
        north: W_NORTH,
        south: W_SOUTH,
        east: W_EAST,
        west: W_WEST,
        random: W_RANDOM,
    };
    ensureDesCoder();
    let mx;
    let my;
    let ftyp = ROOM;
    let fstocked = 1;
    let dir = -1;
    if (rawArgs.length === 3) {
        mx = rawArgs[0];
        my = rawArgs[1];
        dir = dirMap[String(rawArgs[2] || 'random').toLowerCase()] ?? W_RANDOM;
    } else {
        const args = rawArgs[0] ?? {};
        const coord = normalizeCoordPair(args.coord, args.x, args.y);
        if (!coord) return;
        [mx, my] = coord;
        if (args.typ != null) ftyp = splev_chr2typ(args.typ);
        fstocked = args.stocked == null ? 1 : Number(!!args.stocked);
        dir = dirMap[String(args.dir || 'random').toLowerCase()] ?? W_RANDOM;
    }
    const pos = chooseFilteredCoord([mx, my], () => true);
    if (!pos) {
        throw new Error('mazewalk coord not ok');
    }
    let x = pos.x;
    let y = pos.y;
    if (ftyp < 1) {
        ftyp = game.level?.flags?.corrmaze ? CORR : ROOM;
    }
    if (dir === W_RANDOM) dir = randomWdir();
    switch (dir) {
    case W_NORTH: --y; break;
    case W_SOUTH: y++; break;
    case W_EAST: x++; break;
    case W_WEST: --x; break;
    default:
        throw new Error('mazewalk: Bad direction');
    }
    if (!IS_DOOR(game.level?.at(x, y)?.typ ?? STONE)) {
        const loc = game.level?.at(x, y);
        if (loc) {
            loc.typ = ftyp;
            loc.flags = 0;
        }
    }
    if (!(x % 2)) {
        x += (dir === W_EAST) ? 1 : -1;
        const loc = game.level?.at(x, y);
        if (loc) {
            loc.typ = ftyp;
            loc.flags = 0;
        }
    }
    if (!(y % 2)) {
        y += (dir === W_SOUTH) ? 1 : -1;
    }
    walkfrom(x, y, ftyp);
    if (fstocked) await fillEmptyMaze();
}
// des.drawbridge — C ref: sp_lev.c:5720 lspo_drawbridge()
export function drawbridge(args = {}) {
    const dirMap = {
        north: DB_NORTH,
        south: DB_SOUTH,
        west: DB_WEST,
        east: DB_EAST,
        random: -1,
    };
    const stateMap = {
        open: 1,
        closed: 0,
        random: -1,
    };
    ensureDesCoder();
    const coord = normalizeCoordPair(args.coord, args.x, args.y);
    if (!coord) return;
    let dir = dirMap[String(args.dir || 'random').toLowerCase()] ?? -1;
    let dbOpen = stateMap[String(args.state || 'random').toLowerCase()] ?? -1;
    let [x, y] = coord;
    const pos = chooseFilteredCoord(coord, () => true);
    if (!pos) return;
    x = pos.x;
    y = pos.y;
    if (dbOpen === -1) dbOpen = !rn2(2);
    if (dir === -1) {
        const dirs = [DB_NORTH, DB_SOUTH, DB_WEST, DB_EAST];
        dir = dirs[rn2(4)];
    }
    create_drawbridge(x, y, dir, !!dbOpen);
    markSpLevMap(x, y);
}
// des.random_corridors — C ref: sp_lev.c:4557 lspo_random_corridors()
export async function random_corridors() {
    ensureDesCoder();
    await makecorridors();
}
function searchDoor(croom, wall, cnt) {
    let dx = 0;
    let dy = 0;
    let xx = 0;
    let yy = 0;
    switch (wall) {
    case W_SOUTH:
        dx = 1; dy = 0; xx = croom.lx; yy = croom.hy + 1;
        break;
    case W_NORTH:
        dx = 1; dy = 0; xx = croom.lx; yy = croom.ly - 1;
        break;
    case W_EAST:
        dx = 0; dy = 1; xx = croom.hx + 1; yy = croom.ly;
        break;
    case W_WEST:
        dx = 0; dy = 1; xx = croom.lx - 1; yy = croom.ly;
        break;
    default:
        return null;
    }
    while (xx <= croom.hx + 1 && yy <= croom.hy + 1) {
        const loc = game.level?.at(xx, yy);
        if (loc && (IS_DOOR(loc.typ) || loc.typ === SDOOR)) {
            if (cnt-- <= 0) return { x: xx, y: yy };
        }
        xx += dx;
        yy += dy;
    }
    return null;
}
async function createCorridor(corr) {
    if (corr.src.room === -1) {
        await makecorridors();
        return;
    }
    if (corr.src.wall === W_ANY || corr.src.wall === W_RANDOM
        || corr.dest.wall === W_ANY || corr.dest.wall === W_RANDOM) {
        return;
    }
    const srcRoom = game.level.rooms?.[corr.src.room];
    const destRoom = game.level.rooms?.[corr.dest.room];
    if (!srcRoom || !destRoom) return;
    const orgDoor = searchDoor(srcRoom, corr.src.wall, corr.src.door);
    const destDoor = searchDoor(destRoom, corr.dest.wall, corr.dest.door);
    if (!orgDoor || !destDoor) return;
    const org = { ...orgDoor };
    const dest = { ...destDoor };
    switch (corr.src.wall) {
    case W_NORTH: org.y--; break;
    case W_SOUTH: org.y++; break;
    case W_WEST: org.x--; break;
    case W_EAST: org.x++; break;
    default: break;
    }
    switch (corr.dest.wall) {
    case W_NORTH: dest.y--; break;
    case W_SOUTH: dest.y++; break;
    case W_WEST: dest.x--; break;
    case W_EAST: dest.x++; break;
    default: break;
    }
    dig_corridor(org, dest, null, false, CORR, STONE);
}
export async function corridor(args = {}) {
    const wallMap = {
        all: W_ANY,
        random: W_RANDOM,
        north: W_NORTH,
        west: W_WEST,
        east: W_EAST,
        south: W_SOUTH,
    };
    ensureDesCoder();
    const corr = {
        src: {
            room: Number.isInteger(args.srcroom) ? args.srcroom : -1,
            door: Number.isInteger(args.srcdoor) ? args.srcdoor : -1,
            wall: wallMap[String(args.srcwall || 'all').toLowerCase()] ?? W_ANY,
        },
        dest: {
            room: Number.isInteger(args.destroom) ? args.destroom : -1,
            door: Number.isInteger(args.destdoor) ? args.destdoor : -1,
            wall: wallMap[String(args.destwall || 'all').toLowerCase()] ?? W_ANY,
        },
    };
    await createCorridor(corr);
}
// des.level_flags — C ref: sp_lev.c:5966 lspo_level_flags()
export function level_flags(...flags) {
    const coder = ensureDesCoder();
    const levFlags = game.level?.flags;
    if (!levFlags) return;
    for (const rawFlag of flags) {
        const flag = String(rawFlag || '').toLowerCase();
        switch (flag) {
        case 'noteleport':
            levFlags.noteleport = true;
            break;
        case 'hardfloor':
            levFlags.hardfloor = true;
            break;
        case 'nommap':
            levFlags.nommap = true;
            break;
        case 'shortsighted':
            levFlags.shortsighted = true;
            break;
        case 'arboreal':
            levFlags.arboreal = true;
            break;
        case 'shroud':
            levFlags.hero_memory = true;
            break;
        case 'graveyard':
            levFlags.graveyard = true;
            break;
        case 'mazelevel':
            levFlags.is_maze_lev = true;
            break;
        case 'icedpools':
            game.icedpools = true;
            break;
        case 'corrmaze':
            levFlags.corrmaze = true;
            break;
        case 'premapped':
            coder.premapped = true;
            break;
        case 'solidify':
            coder.solidify = true;
            break;
        case 'sokoban':
            game.Sokoban = true;
            break;
        case 'inaccessibles':
            coder.check_inaccessibles = true;
            break;
        case 'noflipx':
            coder.allow_flips &= ~2;
            break;
        case 'noflipy':
            coder.allow_flips &= ~1;
            break;
        case 'noflip':
            coder.allow_flips = 0;
            break;
        case 'temperate':
            levFlags.temperature = 0;
            break;
        case 'hot':
            levFlags.temperature = 1;
            break;
        case 'cold':
            levFlags.temperature = -1;
            break;
        case 'nomongen':
            levFlags.rndmongen = false;
            break;
        case 'nodeathdrops':
            levFlags.deathdrops = false;
            break;
        case 'noautosearch':
            levFlags.noautosearch = true;
            break;
        case 'fumaroles':
            levFlags.fumaroles = true;
            break;
        case 'stormy':
            levFlags.stormy = true;
            break;
        case '':
            break;
        default:
            throw new Error(`Unknown level flag ${rawFlag}`);
        }
    }
}
// des.non_diggable — C ref: sp_lev.c:4253
function setWallPropertyInSelection(sel, prop) {
    const points = sel instanceof SelectionVar ? sel.points : fullLevelSelection().points;
    for (const pt of points) {
        const loc = game.level?.at(pt.x, pt.y);
        if (!loc) continue;
        if (IS_STWALL(loc.typ) || IS_TREE(loc.typ) || loc.typ === IRONBARS) {
            loc.wall_info |= prop;
        }
    }
}
export function non_diggable(sel) {
    setWallPropertyInSelection(sel, W_NONDIGGABLE);
}
export function non_passwall(sel) {
    setWallPropertyInSelection(sel, W_NONPASSWALL);
}
function normalizeRegionRect(region) {
    if (!Array.isArray(region) || region.length < 4) return null;
    return [region[0], region[1], region[2], region[3]];
}
function getLregion(args = {}) {
    const region = normalizeRegionRect(args.region);
    if (!region) return null;
    const exclude = normalizeRegionRect(args.exclude) || [-1, -1, -1, -1];
    const in_islev = !!args.region_islev;
    let del_islev = !!args.exclude_islev;
    if (exclude[0] < 0) del_islev = true;
    return {
        inarea: { x1: region[0], y1: region[1], x2: region[2], y2: region[3] },
        delarea: { x1: exclude[0], y1: exclude[1], x2: exclude[2], y2: exclude[3] },
        in_islev,
        del_islev,
        padding: 0,
        rname: { str: null },
        rtype: 0,
    };
}
function resolveLregionCorner(x, y, islev) {
    if (islev) return { x, y };
    const abs = toAbsCoord([x, y]);
    return abs ? { x: abs[0], y: abs[1] } : { x, y };
}
function levregionAdd(lregion) {
    if (!lregion.in_islev) {
        const p1 = resolveLregionCorner(lregion.inarea.x1, lregion.inarea.y1, false);
        const p2 = resolveLregionCorner(lregion.inarea.x2, lregion.inarea.y2, false);
        lregion.inarea.x1 = p1.x;
        lregion.inarea.y1 = p1.y;
        lregion.inarea.x2 = p2.x;
        lregion.inarea.y2 = p2.y;
    }
    if (!lregion.del_islev) {
        const p1 = resolveLregionCorner(lregion.delarea.x1, lregion.delarea.y1, false);
        const p2 = resolveLregionCorner(lregion.delarea.x2, lregion.delarea.y2, false);
        lregion.delarea.x1 = p1.x;
        lregion.delarea.y1 = p1.y;
        lregion.delarea.x2 = p2.x;
        lregion.delarea.y2 = p2.y;
    }
    if (!Array.isArray(game.lregions)) game.lregions = [];
    game.lregions.push(structuredClone(lregion));
    game.num_lregions = game.lregions.length;
}
// des.teleport_region — C ref: sp_lev.c:5435 lspo_teleport_region()
export function teleport_region(args = {}) {
    const teledirs = { both: LR_TELE, down: LR_DOWNTELE, up: LR_UPTELE };
    const tmplregion = getLregion(args);
    if (!tmplregion) return null;
    tmplregion.rtype = teledirs[String(args.dir || 'both').toLowerCase()] ?? LR_TELE;
    tmplregion.padding = 0;
    tmplregion.rname = { str: null };
    const destRegion = structuredClone(tmplregion);
    levregionAdd(destRegion);
    const dest = {
        lx: destRegion.inarea.x1,
        ly: destRegion.inarea.y1,
        hx: destRegion.inarea.x2,
        hy: destRegion.inarea.y2,
        nlx: destRegion.delarea.x1,
        nly: destRegion.delarea.y1,
        nhx: destRegion.delarea.x2,
        nhy: destRegion.delarea.y2,
    };
    if (tmplregion.rtype === LR_TELE || tmplregion.rtype === LR_UPTELE) game.updest = { ...dest };
    if (tmplregion.rtype === LR_TELE || tmplregion.rtype === LR_DOWNTELE) game.dndest = { ...dest };
    return destRegion;
}
// C ref: mkmaze.c:45 iswall() — checks wall/door/lavawall/water/sdoor/ironbars
function isWallTile(x, y) {
    if (x < 1 || x >= COLNO || y < 0 || y >= ROWNO) return false;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return !!IS_WALL(typ) || !!IS_DOOR(typ)
        || typ === LAVAWALL || typ === WATER
        || typ === SDOOR || typ === IRONBARS;
}
// C ref: mkmaze.c:58 iswall_or_stone() — out of bounds = stone
function isWallOrStone(x, y) {
    if (!isok(x, y)) return true;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return typ === STONE || isWallTile(x, y);
}
function isSolidTile(x, y) {
    if (x < 1 || x >= COLNO || y < 0 || y >= ROWNO) return true;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return IS_STWALL(typ);
}
function extend_spine(locale, wallThere, dx, dy) {
    const nx = 1 + dx;
    const ny = 1 + dy;
    if (!wallThere) return 0;
    if (dx) {
        if (locale[1][0] && locale[1][2] && locale[nx][0] && locale[nx][2]) {
            return 0;
        }
        return 1;
    }
    if (locale[0][1] && locale[2][1] && locale[0][ny] && locale[2][ny]) {
        return 0;
    }
    return 1;
}
// wall_cleanup: imported from mklev.js
function wall_cleanup_protected(x1, y1, x2, y2, protectedArea = null) {
    const level = game.level;
    if (!level) return;
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            if (withinArea(x, y, protectedArea)) continue;
            const loc = level.at(x, y);
            const typ = loc?.typ ?? STONE;
            if (!(IS_WALL(typ) && typ !== DBWALL)) continue;
            if (isSolidTile(x - 1, y - 1) && isSolidTile(x - 1, y)
                && isSolidTile(x - 1, y + 1) && isSolidTile(x, y - 1)
                && isSolidTile(x, y + 1) && isSolidTile(x + 1, y - 1)
                && isSolidTile(x + 1, y) && isSolidTile(x + 1, y + 1)) {
                loc.typ = STONE;
            }
        }
    }
}
function fix_wall_spines(x1, y1, x2, y2, protectedArea = null) {
    const spineArray = [VWALL, HWALL, HWALL, HWALL,
        VWALL, TRCORNER, TLCORNER, TDWALL,
        VWALL, BRCORNER, BLCORNER, TUWALL,
        VWALL, TLWALL, TRWALL, CROSSWALL];
    const level = game.level;
    if (!level) return;
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            const loc = level.at(x, y);
            const typ = loc?.typ ?? STONE;
            if (!(IS_WALL(typ) && typ !== DBWALL)) continue;
            const locFn = withinArea(x, y, protectedArea) ? isWallTile : isWallOrStone;
            const locale = [
                [locFn(x - 1, y - 1), locFn(x - 1, y), locFn(x - 1, y + 1)],
                [locFn(x, y - 1), 0, locFn(x, y + 1)],
                [locFn(x + 1, y - 1), locFn(x + 1, y), locFn(x + 1, y + 1)],
            ];
            const bits = (extend_spine(locale, isWallTile(x, y - 1), 0, -1) << 3)
                | (extend_spine(locale, isWallTile(x, y + 1), 0, 1) << 2)
                | (extend_spine(locale, isWallTile(x + 1, y), 1, 0) << 1)
                | extend_spine(locale, isWallTile(x - 1, y), -1, 0);
            if (bits) loc.typ = spineArray[bits];
        }
    }
}
// wallification: imported from mklev.js
function removeBoundarySyms() {
    let hasBounds = false;
    for (let x = 0; x < COLNO - 1 && !hasBounds; x++) {
        for (let y = 0; y < ROWNO - 1; y++) {
            if (game.level?.at(x, y)?.typ === CROSSWALL) {
                hasBounds = true;
                break;
            }
        }
    }
    if (!hasBounds) return;
    const xMazeMax = (COLNO - 1) & ~1;
    const yMazeMax = (ROWNO - 1) & ~1;
    for (let x = 0; x < xMazeMax; x++) {
        for (let y = 0; y < yMazeMax; y++) {
            const loc = game.level?.at(x, y);
            if (loc?.typ === CROSSWALL && game.sp_lev_map?.[x]?.[y]) {
                loc.typ = ROOM;
            }
        }
    }
}
function solidifyMap() {
    for (let x = 0; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const loc = game.level?.at(x, y);
            if (loc && IS_STWALL(loc.typ) && !game.sp_lev_map?.[x]?.[y]) {
                loc.wall_info |= (W_NONDIGGABLE | W_NONPASSWALL);
            }
        }
    }
}
function selectionHasPoint(sel, x, y) {
    if (!(sel instanceof SelectionVar)) return false;
    return sel.points.some((pt) => pt.x === x && pt.y === y);
}
function selectionFloodFillAccessible(sel, sx, sy) {
    if (!(sel instanceof SelectionVar)) return;
    if (!isok(sx, sy)) return;
    const level = game.level;
    if (!level) return;
    const floodfillchkMatchAccessible = (x, y) => {
        const typ = level.at(x, y)?.typ ?? STONE;
        return ACCESSIBLE(typ) || typ === SDOOR || typ === SCORR;
    };
    const stack = [[sx, sy]];
    const queued = new Set([`${sx},${sy}`]);
    const visited = new Set();
    while (stack.length) {
        const [x, y] = stack.pop();
        queued.delete(`${x},${y}`);
        const key = `${x},${y}`;
        if (visited.has(key)) continue;
        visited.add(key);
        if (!isok(x, y)) continue;
        if (!selectionHasPoint(sel, x, y)) sel.setAbsPoint(x, y, 1);
        const neighbors = [
            [x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1],
            [x + 1, y + 1], [x - 1, y - 1], [x - 1, y + 1], [x + 1, y - 1],
        ];
        for (const [nx, ny] of neighbors) {
            const nkey = `${nx},${ny}`;
            if (!isok(nx, ny)) continue;
            if (!floodfillchkMatchAccessible(nx, ny)) continue;
            if (visited.has(nkey) || queued.has(nkey)) continue;
            stack.push([nx, ny]);
            queued.add(nkey);
        }
    }
}
function selectionRndcoordAbs(sel, removeit) {
    if (!(sel instanceof SelectionVar) || !sel.points.length) return null;
    const bounds = sel.bounds();
    const pointSet = new Set(sel.points.map((pt) => `${pt.x},${pt.y}`));
    let idx = 0;
    for (let x = bounds.lx; x <= bounds.hx; x++) {
        for (let y = bounds.ly; y <= bounds.hy; y++) {
            if (pointSet.has(`${x},${y}`)) idx++;
        }
    }
    if (!idx) return null;
    let c = rn2(idx);
    for (let x = bounds.lx; x <= bounds.hx; x++) {
        for (let y = bounds.ly; y <= bounds.hy; y++) {
            const key = `${x},${y}`;
            if (!pointSet.has(key)) continue;
            if (c === 0) {
                if (removeit) {
                    sel.points = sel.points.filter((pt) => !(pt.x === x && pt.y === y));
                }
                return { x, y };
            }
            c--;
        }
    }
    return null;
}
async function generateWayOutMethod(nx, ny, ov) {
    const escapeItems = [PICK_AXE, DWARVISH_MATTOCK, WAN_DIGGING, WAN_TELEPORTATION, SCR_TELEPORTATION, RIN_TELEPORTATION];
    const ov2 = selection.new();
    selectionFloodFillAccessible(ov2, nx, ny);
    let ov3 = ov2.clone();
    let res = true;
    let pos = null;
    while ((pos = selectionRndcoordAbs(ov3, true))) {
        const { x, y } = pos;
        if (isok(x + 1, y) && !selectionHasPoint(ov, x + 1, y)
            && IS_WALL(game.level?.at(x + 1, y)?.typ ?? STONE)
            && isok(x + 2, y) && selectionHasPoint(ov, x + 2, y)
            && ACCESSIBLE(game.level?.at(x + 2, y)?.typ ?? STONE)) {
            game.level.at(x + 1, y).typ = SDOOR;
            return res;
        }
        if (isok(x - 1, y) && !selectionHasPoint(ov, x - 1, y)
            && IS_WALL(game.level?.at(x - 1, y)?.typ ?? STONE)
            && isok(x - 2, y) && selectionHasPoint(ov, x - 2, y)
            && ACCESSIBLE(game.level?.at(x - 2, y)?.typ ?? STONE)) {
            game.level.at(x - 1, y).typ = SDOOR;
            return res;
        }
        if (isok(x, y + 1) && !selectionHasPoint(ov, x, y + 1)
            && IS_WALL(game.level?.at(x, y + 1)?.typ ?? STONE)
            && isok(x, y + 2) && selectionHasPoint(ov, x, y + 2)
            && ACCESSIBLE(game.level?.at(x, y + 2)?.typ ?? STONE)) {
            game.level.at(x, y + 1).typ = SDOOR;
            return res;
        }
        if (isok(x, y - 1) && !selectionHasPoint(ov, x, y - 1)
            && IS_WALL(game.level?.at(x, y - 1)?.typ ?? STONE)
            && isok(x, y - 2) && selectionHasPoint(ov, x, y - 2)
            && ACCESSIBLE(game.level?.at(x, y - 2)?.typ ?? STONE)) {
            game.level.at(x, y - 1).typ = SDOOR;
            return res;
        }
    }
    if (Can_dig_down(game.u?.uz)) {
        ov3 = ov2.clone();
        while ((pos = selectionRndcoordAbs(ov3, true))) {
            const trapType = rn2(2) ? HOLE : TRAPDOOR;
            if (await maketrap(pos.x, pos.y, trapType)) {
                return res;
            }
        }
    }
    pos = selectionRndcoordAbs(ov2, false);
    if (pos) {
        const item = escapeItems[rn2(escapeItems.length)];
        mksobj_at(item, pos.x, pos.y, true, false);
        return res;
    }
    res = false;
    return res;
}
async function ensureWayOut() {
    const ov = selection.new();
    const uz = game.u?.uz;
    for (let stway = game.stairs; stway; stway = stway.next) {
        if (stway.tolev?.dnum === uz?.dnum) {
            selectionFloodFillAccessible(ov, stway.sx, stway.sy);
        }
    }
    for (let ttmp = game.ftrap; ttmp; ttmp = ttmp.ntrap) {
        if ((undestroyable_trap(ttmp.ttyp) || is_hole(ttmp.ttyp))
            && !selectionHasPoint(ov, ttmp.tx, ttmp.ty)) {
            selectionFloodFillAccessible(ov, ttmp.tx, ttmp.ty);
        }
    }
    let ret;
    do {
        ret = true;
        for (let x = 1; x < COLNO; x++) {
            for (let y = 0; y < ROWNO; y++) {
                const typ = game.level?.at(x, y)?.typ ?? STONE;
                if (ACCESSIBLE(typ) && !selectionHasPoint(ov, x, y)) {
                    if (await generateWayOutMethod(x, y, ov)) {
                        selectionFloodFillAccessible(ov, x, y);
                    }
                    ret = false;
                    break;
                }
            }
            if (!ret) break;
        }
    } while (!ret);
}
function isBranchLev() {
    const uz = game.u?.uz;
    if (!uz || !Array.isArray(game.branches)) return false;
    for (const br of game.branches) {
        if (!br) continue;
        const e1 = br.end1;
        const e2 = br.end2;
        if ((e1?.dnum === uz.dnum && e1?.dlevel === uz.dlevel)
            || (e2?.dnum === uz.dnum && e2?.dlevel === uz.dlevel)) {
            return true;
        }
    }
    return false;
}
async function fixupSpecialRegions() {
    const mkBubbleRngOnly = (x, y, xmax, ymax, n, onWaterLevel, bubblesOut) => {
        // C ref: mkmaze.c mk_bubble() early return still consumes rn2(7) in caller.
        if (x >= xmax || y >= ymax) return;
        const bubbleMasks = [
            { w: 2, h: 1, rows: [0x3] },
            { w: 3, h: 2, rows: [0x7, 0x7] },
            { w: 4, h: 3, rows: [0x6, 0xf, 0x6] },
            { w: 5, h: 3, rows: [0xe, 0x1f, 0xe] },
            { w: 6, h: 4, rows: [0x1e, 0x3f, 0x3f, 0x1e] },
            { w: 7, h: 4, rows: [0x3e, 0x7f, 0x7f, 0x3e] },
            { w: 8, h: 4, rows: [0x7e, 0xff, 0xff, 0x7e] },
        ];
        const idx = (n >= 0 && n < bubbleMasks.length) ? n : (bubbleMasks.length - 1);
        const mask = bubbleMasks[idx];
        let bx = x;
        let by = y;
        if ((bx + mask.w - 1) > xmax) bx = xmax - mask.w + 1;
        if ((by + mask.h - 1) > ymax) by = ymax - mask.h + 1;
        // C ref: mkmaze.c mk_bubble() — b->dx = 1 - rn2(3); b->dy = 1 - rn2(3);
        const dx = 1 - rn2(3);
        const dy = 1 - rn2(3);
        bubblesOut.push({ x: bx, y: by, dx, dy, w: mask.w, h: mask.h, rows: [...mask.rows] });
        // C ref: mkmaze.c mv_bubble(..., ini=TRUE) draw pass.
        for (let i = 0; i < mask.w; i++) {
            for (let j = 0; j < mask.h; j++) {
                if ((mask.rows[j] & (1 << i)) === 0) continue;
                const tx = bx + i;
                const ty = by + j;
                const loc = game.level?.at(tx, ty);
                if (!loc) continue;
                loc.typ = onWaterLevel ? AIR : CLOUD;
                loc.lit = 1;
            }
        }
    };
    const setupWaterOrAirLevel = () => {
        // C ref: mkmaze.c fixup_special() + setup_waterlevel()
        const uz = game.u?.uz;
        const map = game.level;
        if (!uz || !map) return;
        if (!Is_waterlevel(uz) && !Is_airlevel(uz)) return;
 
        map.flags.hero_memory = false;
 
        // C macros in mkmaze.c:
        // gbxmin = svx.xmin + 1, gbymin = svy.ymin + 1
        // gbxmax = svx.xmax - 1, gbymax = svy.ymax - 1
        const xmin = 4;
        const ymin = 2;
        const xmax = Math.min(77, (COLNO - 1) - 2);
        const ymax = Math.min(19, (ROWNO - 1) - 1);
        const typ = Is_waterlevel(uz) ? WATER : AIR;
 
        for (let x = 1; x <= COLNO - 1; x++) {
            for (let y = 0; y <= ROWNO - 1; y++) {
                const loc = map.at(x, y);
                if (loc?.typ === STONE) {
                    loc.typ = typ;
                }
            }
        }
 
        const onWaterLevel = Is_waterlevel(uz);
        const bubbles = [];
        const xskip = onWaterLevel ? (10 + rn2(10)) : (6 + rn2(4));
        const yskip = onWaterLevel ? (4 + rn2(4)) : (3 + rn2(3));
        for (let x = xmin; x <= xmax; x += xskip) {
            for (let y = ymin; y <= ymax; y += yskip) {
                const n = rn2(7);
                mkBubbleRngOnly(x, y, xmax, ymax, n, onWaterLevel, bubbles);
            }
        }
        game.plane_bubbles = bubbles;
        game.plane_bubble_bounds = { xmin, ymin, xmax, ymax };
        // C ref: mkmaze.c movebubbles() uses static `up` that persists across
        // level transitions; do not reset traversal direction on setup.
        if (typeof game.plane_bubble_up !== 'boolean') {
            game.plane_bubble_up = false;
        }
    };
    setupWaterOrAirLevel();
 
    const tt_oname = (otmp) => {
        if (!otmp) return null;
        const maxrank = game.sysopt?.tt_oname_maxrank ?? 10;
        // C always rolls rank in get_rnd_toptenentry(); score file may still yield no entry.
        rnd(maxrank);
        return null;
    };
    const mk_tt_object = (objtype, x, y) => {
        const initialize = (objtype !== STATUE);
        const otmp = mksobj_at(objtype, x, y, initialize, false);
        if (!otmp) return null;
        // C mk_tt_object(): tt_oname() first, then role-random fallback.
        if (!tt_oname(otmp)) {
            set_corpsenm(otmp, rn1(PM_WIZARD - PM_ARCHEOLOGIST + 1, PM_ARCHEOLOGIST));
        }
        return otmp;
    };
    const roomX = (croom) => rn1(croom.hx - croom.lx + 1, croom.lx);
    const roomY = (croom) => rn1(croom.hy - croom.ly + 1, croom.ly);
    const regions = Array.isArray(game.lregions) ? game.lregions : [];
    let addedBranch = false;
    const uz = game.u?.uz || { dnum: 0, dlevel: 1 };
    for (const r of regions) {
        if (!r) continue;
        switch (r.rtype) {
        case LR_BRANCH:
            addedBranch = true;
            await place_lregion(
                r.inarea.x1, r.inarea.y1, r.inarea.x2, r.inarea.y2,
                r.delarea.x1, r.delarea.y1, r.delarea.x2, r.delarea.y2,
                r.rtype, null
            );
            break;
        case LR_PORTAL: {
            let lev = { dnum: uz.dnum, dlevel: uz.dlevel };
            const name = r.rname?.str || '';
            if (/^\d+$/.test(name)) {
                lev = { dnum: uz.dnum, dlevel: parseInt(name, 10) || uz.dlevel };
            } else {
                const sp = find_level(name);
                if (sp?.dlevel) lev = { dnum: sp.dlevel.dnum, dlevel: sp.dlevel.dlevel };
            }
            await place_lregion(
                r.inarea.x1, r.inarea.y1, r.inarea.x2, r.inarea.y2,
                r.delarea.x1, r.delarea.y1, r.delarea.x2, r.delarea.y2,
                r.rtype, lev
            );
            break;
        }
        case LR_UPSTAIR:
        case LR_DOWNSTAIR:
            await place_lregion(
                r.inarea.x1, r.inarea.y1, r.inarea.x2, r.inarea.y2,
                r.delarea.x1, r.delarea.y1, r.delarea.x2, r.delarea.y2,
                r.rtype, null
            );
            break;
        case LR_TELE:
        case LR_UPTELE:
        case LR_DOWNTELE:
            if (r.rtype === LR_TELE || r.rtype === LR_UPTELE) {
                game.updest = {
                    lx: r.inarea.x1, ly: r.inarea.y1, hx: r.inarea.x2, hy: r.inarea.y2,
                    nlx: r.delarea.x1, nly: r.delarea.y1, nhx: r.delarea.x2, nhy: r.delarea.y2,
                };
            }
            if (r.rtype === LR_TELE || r.rtype === LR_DOWNTELE) {
                game.dndest = {
                    lx: r.inarea.x1, ly: r.inarea.y1, hx: r.inarea.x2, hy: r.inarea.y2,
                    nlx: r.delarea.x1, nly: r.delarea.y1, nhx: r.delarea.x2, nhy: r.delarea.y2,
                };
            }
            break;
        default:
            break;
        }
    }
    if (!addedBranch && isBranchLev()) {
        await place_lregion(0, 0, 0, 0, 0, 0, 0, 0, LR_BRANCH, null);
    }
    // C ref: mkmaze.c:649-686 (fixup_special medusa-statue population).
    if (isMedusaLevel()) {
        const croom = game.level.rooms?.[0];
        if (croom) {
            let otmp = null;
            for (let tryct = rnd(4); tryct; tryct--) {
                const x = roomX(croom);
                const y = roomY(croom);
                if (goodpos(x, y, null, 0)) {
                    let tryct2 = 0;
                    otmp = mk_tt_object(STATUE, x, y);
                    while (++tryct2 < 100 && otmp
                        && (poly_when_stoned(mons[otmp.corpsenm])
                            || pm_resists_ston(mons[otmp.corpsenm]))) {
                        set_corpsenm(otmp, rndmonnum());
                    }
                }
            }
            if (rn2(2)) {
                otmp = mk_tt_object(STATUE, roomX(croom), roomY(croom));
            } else {
                otmp = mkcorpstat(STATUE, null, null, roomX(croom), roomY(croom), CORPSTAT_NONE);
            }
            if (otmp) {
                let tryct = 0;
                while (++tryct < 100
                    && (pm_resists_ston(mons[otmp.corpsenm])
                        || poly_when_stoned(mons[otmp.corpsenm]))) {
                    set_corpsenm(otmp, rndmonnum());
                }
            }
        }
    } else if (isBaalzLevel()) {
        baalzFixupMinimal();
    }
    game.lregions = [];
    game.num_lregions = 0;
}
// C ref: sp_lev.c:968 flip_level_rnd()
function flipLevelRnd(flp, _extras = false) {
    let c = 0;
    if ((flp & 1) && rn2(2)) c |= 1;
    if ((flp & 2) && rn2(2)) c |= 2;
    if (c) {
        let { xmin: minx, ymin: miny, xmax: maxx, ymax: maxy } = get_level_extends();
        if (miny < 0) miny = 0;
        if (minx < 1) minx = 1;
        if (maxx >= COLNO) maxx = COLNO - 1;
        if (maxy >= ROWNO) maxy = ROWNO - 1;
        const flipX = (x) => ((maxx - x) + minx);
        const flipY = (y) => ((maxy - y) + miny);
        const inFlipArea = (x, y) => (
            Number.isFinite(x) && Number.isFinite(y)
            && x >= minx && x <= maxx && y >= miny && y <= maxy
        );
        const map = game.level;
        if (!map) return;
        const flipDbridgeHorizontal = (loc) => {
            if (!loc || !IS_DRAWBRIDGE(loc.typ)) return;
            const dir = loc.drawbridgemask & DB_DIR;
            if (dir === DB_WEST) {
                loc.drawbridgemask &= ~DB_DIR;
                loc.drawbridgemask |= DB_EAST;
            } else if (dir === DB_EAST) {
                loc.drawbridgemask &= ~DB_DIR;
                loc.drawbridgemask |= DB_WEST;
            }
        };
        const flipDbridgeVertical = (loc) => {
            if (!loc || !IS_DRAWBRIDGE(loc.typ)) return;
            const dir = loc.drawbridgemask & DB_DIR;
            if (dir === DB_NORTH) {
                loc.drawbridgemask &= ~DB_DIR;
                loc.drawbridgemask |= DB_SOUTH;
            } else if (dir === DB_SOUTH) {
                loc.drawbridgemask &= ~DB_DIR;
                loc.drawbridgemask |= DB_NORTH;
            }
        };
        // Flip map only inside C's computed level extents.
        if (c & 1) {
            for (let x = minx; x <= maxx; x++) {
                for (let y = miny; y < (miny + Math.trunc((maxy - miny + 1) / 2)); y++) {
                    const ny = flipY(y);
                    flipDbridgeVertical(map.locations[x][y]);
                    flipDbridgeVertical(map.locations[x][ny]);
                    const trm = map.locations[x][y];
                    map.locations[x][y] = map.locations[x][ny];
                    map.locations[x][ny] = trm;
                }
            }
        }
        if (c & 2) {
            for (let x = minx; x < (minx + Math.trunc((maxx - minx + 1) / 2)); x++) {
                for (let y = miny; y <= maxy; y++) {
                    const nx = flipX(x);
                    flipDbridgeHorizontal(map.locations[x][y]);
                    flipDbridgeHorizontal(map.locations[nx][y]);
                    const trm = map.locations[x][y];
                    map.locations[x][y] = map.locations[nx][y];
                    map.locations[nx][y] = trm;
                }
            }
        }
        const flipPoint = (pt, xk, yk, { requireX = false, areaBounded = false } = {}) => {
            if (!pt || !Number.isFinite(pt[xk]) || !Number.isFinite(pt[yk])) return;
            if (requireX && !pt[xk]) return;
            if (areaBounded && !inFlipArea(pt[xk], pt[yk])) return;
            if (c & 2) pt[xk] = flipX(pt[xk]);
            if (c & 1) pt[yk] = flipY(pt[yk]);
        };
        const flipRange = (r, lx, hx, ly, hy) => {
            if (!r) return;
            if (c & 2) {
                if (Number.isFinite(r[lx])) r[lx] = flipX(r[lx]);
                if (Number.isFinite(r[hx])) r[hx] = flipX(r[hx]);
                if (Number.isFinite(r[lx]) && Number.isFinite(r[hx]) && r[lx] > r[hx]) {
                    const t = r[lx]; r[lx] = r[hx]; r[hx] = t;
                }
            }
            if (c & 1) {
                if (Number.isFinite(r[ly])) r[ly] = flipY(r[ly]);
                if (Number.isFinite(r[hy])) r[hy] = flipY(r[hy]);
                if (Number.isFinite(r[ly]) && Number.isFinite(r[hy]) && r[ly] > r[hy]) {
                    const t = r[ly]; r[ly] = r[hy]; r[hy] = t;
                }
            }
        };
        // Rooms, doors, stairs, traps, objects, monsters, engravings.
        for (const room of game.level.rooms || []) {
            flipRange(room, 'lx', 'hx', 'ly', 'hy');
        }
        for (const d of game.level.doors || []) flipPoint(d, 'x', 'y', { requireX: true, areaBounded: true });
        flipPoint(map.upstair, 'x', 'y');
        flipPoint(map.dnstair, 'x', 'y');
        for (const s of map.stairs || []) {
            flipPoint(s, 'x', 'y');
            if (s.to) flipPoint(s.to, 'sx', 'sy');
        }
        for (const t of map.traps || []) flipPoint(t, 'tx', 'ty', { areaBounded: true });
        for (const o of map.objects || []) flipPoint(o, 'ox', 'oy', { areaBounded: true });
        const flipCoord = (pt) => {
            if (!pt || !Number.isFinite(pt.x) || !Number.isFinite(pt.y)) return;
            if (c & 2) pt.x = flipX(pt.x);
            if (c & 1) pt.y = flipY(pt.y);
        };
        for (const m of map.monsters || []) {
            if (!m || !Number.isFinite(m.mx) || !Number.isFinite(m.my)) continue;
            // C ref: sp_lev.c flip_level_rnd() skips out-of-area monsters.
            if (!inFlipArea(m.mx, m.my)) continue;
            if (c & 2) m.mx = flipX(m.mx);
            if (c & 1) m.my = flipY(m.my);
            // C ref: Flip_coord(mtmp->mgoal)
            flipCoord(m.mgoal);
            if (m.ispriest) {
                // C ref: Flip_coord(EPRI(mtmp)->shrpos)
                const epri = m.epri || m.mextra?.epri;
                flipCoord(epri?.shrpos);
            } else if (m.isshk) {
                // C ref: Flip_coord(ESHK(mtmp)->shk/shd)
                const eshk = m.eshk || m.mextra?.eshk;
                flipCoord(eshk?.shk);
                flipCoord(eshk?.shd);
            }
            // NOTE: long-worm segment flipping is not implemented in JS yet.
        }
        for (const e of map.engravings || []) flipPoint(e, 'x', 'y');
        for (let s = game.stairs; s; s = s.next) flipPoint(s, 'sx', 'sy');
        // Flip level regions used by fixup_special().
        for (const r of game.lregions || []) {
            if (!r) continue;
            flipRange(r.inarea, 'x1', 'x2', 'y1', 'y2');
            flipRange(r.delarea, 'x1', 'x2', 'y1', 'y2');
        }
        // Flip teleport destination ranges only when active.
        // Keep all-zero sentinel ranges unchanged.
        const activeDest = (d) => !!d && !(
            d.lx === 0 && d.ly === 0 && d.hx === 0 && d.hy === 0
            && d.nlx === 0 && d.nly === 0 && d.nhx === 0 && d.nhy === 0
        );
        if (activeDest(game.updest)) {
            flipRange(game.updest, 'lx', 'hx', 'ly', 'hy');
            flipRange(game.updest, 'nlx', 'nhx', 'nly', 'nhy');
        }
        if (activeDest(game.dndest)) {
            flipRange(game.dndest, 'lx', 'hx', 'ly', 'hy');
            flipRange(game.dndest, 'nlx', 'nhx', 'nly', 'nhy');
        }
        // Flip exclusion zones.
        for (const ez of map.exclusionZones || []) {
            flipRange(ez, 'lx', 'hx', 'ly', 'hy');
        }
    }
}
// des.finalize_level — C ref: sp_lev.c:6406
export async function finalize_level() {
    const coder = ensureDesCoder();
    if (coder.finalized) return true;
    coder.finalized = true;
    // C ref: sp_lev.c lspo_finalize_level()/load_special()
    // link_doors_rooms() happens before remove_boundary_syms().
    linkDoorsRooms();
    removeBoundarySyms();
    if (coder.check_inaccessibles) await ensureWayOut();
    map_cleanup();
    // C ref: sp_lev.c:6037/6479 — skip global wallification for corrmaze maps.
    if (!game.level?.flags?.corrmaze) {
        wallification(1, 0, COLNO - 1, ROWNO - 1);
    }
    flipLevelRnd(coder.allow_flips, false);
    // C ref: sp_lev.c:915 — after flip, re-compute wall spines and wall_info
    // because flip swaps cells without converting wall types (TLCORNER → TRCORNER etc.)
    if (coder.allow_flips) {
        if (!game.level?.flags?.corrmaze) {
            wallification(1, 0, COLNO - 1, ROWNO - 1);
        }
        set_wall_state();
    }
    if (coder.solidify) solidifyMap();
    await fixupSpecialRegions();
    if (coder.premapped) premapDetect();
    return true;
}
// C ref: sp_lev.c:329 map_cleanup — remove boulders/traps/engravings from liquid
function map_cleanup() {
    for (let x = 0; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const loc = game.level?.at(x, y);
            if (!loc) continue;
            if (IS_LAVA(loc.typ) || IS_POOL(loc.typ)) {
                // remove boulders from liquid
                let otmp;
                while ((otmp = sobj_at(BOULDER, x, y))) {
                    obj_extract_self(otmp);
                    obfree(otmp, null);
                }
                // remove traps from liquid
                const ttmp = t_at(x, y);
                if (ttmp && !undestroyable_trap(ttmp.ttyp))
                    deltrap(ttmp);
                // remove engravings from liquid
                const etmp = engr_at(x, y);
                if (etmp) del_engr(etmp);
            }
        }
    }
}
function skipPremapDetect(x, y) {
    const loc = game.level?.at(x, y);
    if (!loc) return true;
    return loc.typ === STONE && !!(loc.wall_info & (W_NONDIGGABLE | W_NONPASSWALL));
}
function premapDetect() {
    for (let x = 1; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const loc = game.level?.at(x, y);
            if (!loc || skipPremapDetect(x, y)) continue;
            loc.seenv = SVALL;
            loc.waslit = true;
            if (loc.typ === SDOOR) {
                loc.wall_info = 0;
            }
            map_background(x, y, 1);
            const boulder = sobj_at(BOULDER, x, y);
            if (boulder) map_object(boulder, 1);
        }
    }
    for (const trap of game.level?.traps || []) {
        trap.tseen = 1;
        map_trap(trap, 1);
    }
}
export function message(msg) {
    if (typeof msg !== 'string' || !msg.length) return;
    const old = game.lev_message || '';
    game.lev_message = old ? `${old}\n${msg}` : msg;
}
// des.stair — C ref: sp_lev.c:3671 lspo_stair()
function goodStairLoc(x, y) {
    const typ = game.level?.at(x, y)?.typ;
    return typ === ROOM || typ === CORR || typ === ICE;
}
function createSpecialStairway(up, coord, usingLadder) {
    const croomActive = !!ensureDesCoder()?.croom;
    const randomRoomCoord = !coord && !!game.currentRoom && croomActive;
    if (randomRoomCoord) pushRngLogEntry('>somexy');
    let pos = null;
    if (coord) {
        const abs = toAbsCoord(coord);
        if (abs && isok(abs[0], abs[1])) {
            pos = { x: abs[0], y: abs[1] };
        }
    } else {
        pos = chooseFilteredCoord(null, goodStairLoc);
    }
    if (randomRoomCoord) pushRngLogEntry(`<somexy=${pos ? 1 : 0}`);
    if (!pos) return null;
    const trap = t_at(pos.x, pos.y);
    if (trap) deltrap(trap);
    const loc = game.level?.at(pos.x, pos.y);
    if (!loc) return null;
    markSpLevMap(pos.x, pos.y);
    if (usingLadder) {
        loc.typ = LADDER;
        loc.ladder = up ? LA_UP : LA_DOWN;
        const uz = game.u?.uz || { dnum: 0, dlevel: 1 };
        stairway_add(pos.x, pos.y, up, true, {
            dnum: uz.dnum,
            dlevel: uz.dlevel + (up ? -1 : 1),
        });
        return { x: pos.x, y: pos.y, up, isladder: true };
    }
    loc.typ = STAIRS;
    const uz = game.u?.uz || { dnum: 0, dlevel: 1 };
    stairway_add(pos.x, pos.y, up, false, {
        dnum: uz.dnum,
        dlevel: uz.dlevel + (up ? -1 : 1),
    });
    if (up) game.level.upstair = { x: pos.x, y: pos.y };
    else game.level.dnstair = { x: pos.x, y: pos.y };
    return { x: pos.x, y: pos.y, up, isladder: false };
}
export function stair(args, x, y) {
    let up = false;
    let coord = null;
    if (typeof args === 'string') {
        up = String(args).toLowerCase() === 'up';
        // C accepts stair("down", {x,y}) as well as stair("down", x, y).
        coord = normalizeCoordPair(x, null, null);
        if (!coord) coord = normalizeCoordPair(null, x, y);
    } else if (args && typeof args === 'object') {
        up = String(args.dir || 'down').toLowerCase() === 'up';
        coord = normalizeCoordPair(args.coord, args.x, args.y);
    } else {
        coord = normalizeCoordPair(null, x, y);
    }
    return createSpecialStairway(up, coord, false);
}
export function ladder(args, x, y) {
    let up = false;
    let coord = null;
    if (typeof args === 'string') {
        up = String(args).toLowerCase() === 'up';
        // C accepts ladder("up", {x,y}) as well as ladder("up", x, y).
        coord = normalizeCoordPair(x, null, null);
        if (!coord) coord = normalizeCoordPair(null, x, y);
    } else if (args && typeof args === 'object') {
        up = String(args.dir || 'down').toLowerCase() === 'up';
        coord = normalizeCoordPair(args.coord, args.x, args.y);
    } else {
        coord = normalizeCoordPair(null, x, y);
    }
    return createSpecialStairway(up, coord, true);
}
// des.engraving — C ref: sp_lev.c:3571 lspo_engraving()
export function engraving(args, typeArg = null, textArg = null) {
    let spec = null;
    let wipeout = true;
    let guardobjects = false;
    if (args && typeof args === 'object' && !Array.isArray(args) && !isFiniteCoord(args)) {
        // C argc==1 table form
        spec = normalizeEngravingArgs(args);
        wipeout = (spec?.degrade !== undefined) ? !!spec.degrade : true;
        guardobjects = (spec?.guardobjects !== undefined) ? !!spec.guardobjects : false;
    } else {
        // C argc==3 positional form: engraving(coord, type, text)
        const coord = normalizeCoord(args, null, null);
        spec = coord ? { coord, type: typeArg, text: textArg } : null;
    }
    if (!spec?.coord) return;
    const typeName = String(spec.type || 'engrave').toLowerCase();
    let etyp = ENGRAVE;
    if (typeName === 'dust') etyp = DUST;
    else if (typeName === 'burn') etyp = BURN;
    else if (typeName === 'mark') etyp = MARK;
    else if (typeName === 'blood') etyp = ENGR_BLOOD;
    // Create real engraving state and emit C-matching ^engr[type,x,y] event.
    const [ax, ay] = toAbsCoord(spec.coord);
    make_engr_at(ax, ay, spec.text || '', null, 0, etyp);
    // C ref: sp_lev.c lspo_engraving() — ep->guardobjects, ep->nowipeout
    const ep = engr_at(ax, ay);
    if (ep) {
        ep.guardobjects = guardobjects ? 1 : 0;
        ep.nowipeout = wipeout ? 0 : 1;
    }
}
// des.door — C ref: sp_lev.c:3625 lspo_door()
export function door(args) {
    const stateMap = {
        random: -1,
        open: D_ISOPEN,
        closed: D_CLOSED,
        locked: D_LOCKED,
        nodoor: D_NODOOR,
        broken: D_BROKEN,
        secret: D_SECRET,
    };
    const wallMap = {
        all: W_ANY,
        random: W_ANY,
        north: W_NORTH,
        west: W_WEST,
        east: W_EAST,
        south: W_SOUTH,
    };
    let msk = -1;
    let coord = null;
    let wall = W_ANY;
    let pos = -1;
    if (typeof args === 'string') {
        msk = stateMap[String(args).toLowerCase()] ?? -1;
        coord = normalizeCoordPair(null, arguments[1], arguments[2]);
    } else if (args && typeof args === 'object') {
        msk = stateMap[String(args.state || 'random').toLowerCase()] ?? -1;
        coord = normalizeCoordPair(args.coord, args.x, args.y);
        wall = wallMap[String(args.wall || 'all').toLowerCase()] ?? W_ANY;
        pos = Number.isFinite(args.pos) ? args.pos : -1;
    }
    const typ = msk === -1 ? rnddoor() : msk;
    if (!coord || (coord[0] === -1 && coord[1] === -1)) {
        return createDoor({
            // C ref: lspo_door() sets tmpd.secret to 0 or 1, never -1.
            secret: typ === D_SECRET ? 1 : 0,
            mask: msk,
            pos,
            wall,
        }, game.currentRoom);
    }
    const abs = chooseFilteredCoord(coord, () => true);
    if (!abs) return null;
    selSetDoor(abs.x, abs.y, typ);
    return { x: abs.x, y: abs.y };
}
// des.region — C ref: sp_lev.c:4174 lspo_region()
export async function region(args, litArg) {
    // C ref: sp_lev.c spo_region — two calling conventions:
    // 1. des.region(selection, "lit"/"unlit") — set lighting for all tiles in selection
    // 2. des.region({region:[x1,y1,x2,y2], ...}) — create a room region
    if (args instanceof SelectionVar
        && (litArg === 'lit' || litArg === 'unlit')) {
        const sel = args.clone();
        const lit = litArg === 'lit';
        if (lit) growSelection(sel, W_ANY);
        const level = game.level;
        if (level) {
            for (const pt of sel.points) {
                const loc = level.at(pt.x, pt.y);
                if (loc) {
                    loc.lit = IS_LAVA(loc.typ) || lit;
                    loc.waslit = !!loc.lit;
                }
            }
        }
        return null;
    }
    if (!args || !Array.isArray(args.region) || args.region.length < 4) {
        return null;
    }
    const p1 = chooseFilteredCoord([args.region[0], args.region[1]], () => true);
    const p2 = chooseFilteredCoord([args.region[2], args.region[3]], () => true);
    if (!p1 || !p2) return null;
    const x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y;
    const rtype = getRoomTypeOpt(args.type);
    const rlit = args.lit ?? -1;
    const irregular = !!args.irregular;
    const filled = args.filled ?? 0;
    const joined = args.joined ?? true;
    const arrivalRoom = !!args.arrival_room;
    // C ref: sp_lev.c:5645 — litstate_rnd uses depth(&u.uz), not dlevel
    const _d = (game.dungeons?.[game.u?.uz?.dnum ?? 0]?.depth_start ?? 0) + (game.u?.uz?.dlevel ?? 1) - 1;
    const resolvedLit = rlit < 0 ? (rnd(1 + Math.abs(_d)) < 11 && rn2(77) ? 1 : 0) : (rlit ? 1 : 0);
    const roomNotNeeded = (rtype === OROOM && !irregular && !arrivalRoom && !game.in_mk_themerooms);
    if (roomNotNeeded || (game.level.nroom ?? 0) >= MAXNROFROOMS) {
        lightRegion(x1, y1, x2, y2, resolvedLit);
        return null;
    }
    let rm = null;
    if (irregular) {
        rm = des_region(x1, y1, x2, y2, rtype, resolvedLit, true, filled);
    } else {
        add_room(x1, y1, x2, y2, resolvedLit, rtype, true);
        rm = game.level.rooms?.[(game.level.nroom ?? 1) - 1] || null;
        if (rm) topologize(rm);
    }
    if (!rm) return null;
    rm.needfill = filled;
    rm.needjoining = !!joined;
    if (typeof args.contents === 'function') {
        const out = withCurrentRoom(rm, () => args.contents(rm));
        if (out && typeof out.then === 'function') await out;
    }
    // C ref: sp_lev.c:lspo_region() — always refresh room door metadata
    // for created regions, regardless of whether contents callback exists.
    addDoorsToRoom(rm);
    return rm;
}
// des.trap — C ref: sp_lev.c:1838 create_trap()
export async function trap(args, x, y) {
    args = normalizeTrapArgs(args, x, y);
    const requestedType = (args.type ?? null);
    const croomActive = !!ensureDesCoder()?.croom;
    let tx = null;
    let ty = null;
    if (args.coord) {
        [tx, ty] = toAbsCoord(args.coord);
    } else if (game.currentRoom) {
        if (croomActive) pushRngLogEntry('>somexy');
        let tryct = 0;
        do {
            tx = rn1(game.currentRoom.hx - game.currentRoom.lx + 1, game.currentRoom.lx);
            ty = rn1(game.currentRoom.hy - game.currentRoom.ly + 1, game.currentRoom.ly);
        } while (!isOkLocation(tx, ty, DRY) && ++tryct < 100);
        if (croomActive) pushRngLogEntry(`<somexy=${isOkLocation(tx, ty, DRY) ? 1 : 0}`);
    } else {
        // C ref: sp_lev.c create_trap() + get_location_coord(..., DRY,...)
        // Retry for dry squares and avoid stairs/ladder.
        const span = getLocationSpan();
        let tryct = 0;
        while (tryct <= 100) {
            tx = rn2(span.sx) + span.mx;
            ty = rn2(span.sy) + span.my;
            if (!isOkLocation(tx, ty, DRY)) {
                tryct++;
                continue;
            }
            const typ = game.level?.at(tx, ty)?.typ ?? STONE;
            if (typ === STAIRS || typ === LADDER) {
                tryct++;
                continue;
            }
            break;
        }
        if (tryct > 100) return;
    }
    // C ref: sp_lev.c:4320-4347 trap_types[] (exact name table).
    const trapTypes = {
        'arrow': 1,
        'dart': 2,
        'falling rock': 3,
        'board': 4,
        'bear': 5,
        'land mine': 6,
        'rolling boulder': 7,
        'sleep gas': 8,
        'rust': 9,
        'fire': 10,
        'pit': 11,
        'spiked pit': 12,
        'hole': 13,
        'trap door': 14,
        'teleport': 15,
        'level teleport': 16,
        'magic portal': 17,
        'web': 18,
        'statue': 19,
        'magic': 20,
        'anti magic': 21,
        'polymorph': 22,
        'vibrating square': 23,
        'random': -1,
    };
    let trapNum = NO_TRAP;
    let mktrapFlags = MKTRAP_MAZEFLAG;
    if (args.spider_on_web === false) mktrapFlags |= MKTRAP_NOSPIDERONWEB;
    if (args.seen) mktrapFlags |= MKTRAP_SEEN;
    if (args.victim === false) mktrapFlags |= MKTRAP_NOVICTIM;
    if (requestedType != null) {
        if (Number.isFinite(requestedType)) {
            trapNum = requestedType;
        } else {
            trapNum = trapTypes[String(requestedType).toLowerCase()] ?? NO_TRAP;
        }
    }
    if (typeof requestedType === 'string' && trapNum === NO_TRAP) {
        throw new Error(`Unknown trap type: ${requestedType}`);
    }
    trapNum = pickMktrapKind(trapNum, mktrapFlags);
    // C ref: mklev.c:2079 — convert holes/trapdoors when Can_fall_thru is false
    if (is_hole(trapNum) && !Can_fall_thru(game.u?.uz))
        trapNum = ROCKTRAP;
    // C ref: sp_lev.c:1846 create_trap → mktrap()
    pushRngLogEntry('>mktrap');
    // C ref: mklev.c mktrap() logs trap creation after type-specific side effects
    // (spider/statue/victim), so suppress maketrap's immediate ^trap emission.
    const ttmp = (tx != null && ty != null)
        ? await maketrap(tx, ty, trapNum, { suppressEvent: true })
        : null;
    const kind = ttmp ? ttmp.ttyp : NO_TRAP;
    // C ref: mklev.c:2118-2120 — mktrap() tutorial return portal destination.
    if (ttmp && kind === MAGIC_PORTAL
        && ((game.u?.ucamefrom?.dnum || 0) || (game.u?.ucamefrom?.dlevel || 0))) {
        ttmp.dst.dnum = game.u.ucamefrom.dnum;
        ttmp.dst.dlevel = game.u.ucamefrom.dlevel;
    }
    if (ttmp && (mktrapFlags & MKTRAP_SEEN)) {
        ttmp.tseen = true;
    }
    // C ordering: ^trap is emitted after maketrap() initialization.
    // For WEB traps, spider spawn happens in mktrap() after ^trap.
    // mk_trap_statue is now handled inside maketrap() (trap.js),
    // so STATUE_TRAP's ^trap event is also emitted from there.
    if (ttmp && kind !== NO_TRAP) {
        pushRngLogEntry(`^trap[${kind},${ttmp.tx},${ttmp.ty}]`);
    }
    if (kind === WEB && !(mktrapFlags & MKTRAP_NOSPIDERONWEB) && tx != null && ty != null) {
        await makemon(mons[PM_GIANT_SPIDER], tx, ty, 0);
    }
    // mk_trap_statue for STATUE_TRAP is now handled inside maketrap() (trap.js)
    {
        if (game.in_mklev && ttmp && kind !== NO_TRAP && !(mktrapFlags & MKTRAP_NOVICTIM)) {
            // C ref: mklev.c:2137 — uses level_difficulty(), not raw dlevel
            const lvl = level_difficulty();
            const roll = rnd(4);
            const noBoulderPath = (kind === ROLLING_BOULDER_TRAP
                && ttmp.launch?.x === ttmp.tx && ttmp.launch?.y === ttmp.ty);
            if (lvl <= roll
                && kind !== SQKY_BOARD && kind !== RUST_TRAP
                && !noBoulderPath
                && !is_pit(kind) && (kind < HOLE || kind === MAGIC_TRAP)) {
                if (kind === LANDMINE) {
                    ttmp.ttyp = PIT;
                    ttmp.tseen = true;
                }
                mktrap_victim(ttmp);
            }
        }
    }
    pushRngLogEntry('<mktrap');
}
// C ref: sp_lev.c:3467 find_objtype()
// Strips class prefixes ("ring of ", "potion of ", etc.) and matches by oc_name.
function find_objtype(name, oclass) {
    if (!name) return -1;
    // RING_CLASS, POTION_CLASS, SCROLL_CLASS, SPBOOK_CLASS, WAND_CLASS
    // imported from objects.js at top of file
    const prefixes = [
        { prefix: 'ring of ', oclass: RING_CLASS },
        { prefix: 'potion of ', oclass: POTION_CLASS },
        { prefix: 'scroll of ', oclass: SCROLL_CLASS },
        { prefix: 'spellbook of ', oclass: SPBOOK_CLASS },
        { prefix: 'wand of ', oclass: WAND_CLASS },
    ];
    let searchName = name;
    let searchClass = 0;
    if (name.includes(' of ')) {
        for (const { prefix, oclass: cls } of prefixes) {
            if (name.toLowerCase().startsWith(prefix)) {
                searchClass = cls;
                searchName = name.substring(prefix.length);
                break;
            }
        }
    }
    // Find by oc_name
    for (let i = 0; i < game.objects.length; i++) {
        const od = game.objects[i];
        if (!od) continue;
        if (searchClass && od.oc_class !== searchClass) continue;
        if (od.oc_name && od.oc_name.toLowerCase() === searchName.toLowerCase())
            return i;
    }
    // Find by oc_descr
    for (let i = 0; i < game.objects.length; i++) {
        const od = game.objects[i];
        if (!od) continue;
        if (od.oc_descr && od.oc_descr.toLowerCase() === searchName.toLowerCase())
            return i;
    }
    // Direct match without prefix stripping
    for (let i = 0; i < game.objects.length; i++) {
        const od = game.objects[i];
        if (!od) continue;
        if (od.oc_name && od.oc_name.toLowerCase() === name.toLowerCase())
            return i;
    }
    return -1;
}
function def_char_to_monclass(ch) {
    if (typeof ch !== 'string' || ch.length !== 1) return 0;
    for (let i = 1; i < def_monsyms.length; i++) {
        if ((def_monsyms[i]?.sym || '') === ch) return i;
    }
    return 0;
}
// des.object — C ref: sp_lev.c:2300 lspo_object()
// This is the most RNG-heavy function. Creates objects via mksobj_core/mkobj.
export async function object(args, x, y) {
    args = normalizeObjectArgs(args, x, y);
    const croomActive = !!ensureDesCoder()?.croom;
    const named = !!args.name;
    const isContained = containerObjStack.length > 0;
    const carryingMonster = inventoryMonsterStack.length > 0
        ? inventoryMonsterStack[inventoryMonsterStack.length - 1]
        : null;
    const hasContentsField = Object.prototype.hasOwnProperty.call(args, 'contents')
        && args.contents !== null
        && args.contents !== undefined;
    // C ref: sp_lev.c:2300 lspo_object → create_object
    // C order: get_location FIRST (for positioning), THEN mksobj_core/mkobj.
    // Step 1: Position — C ref: get_location_coord/get_location.
    // If we're inside a room definition, random picks come from somex/somey.
    // Otherwise random picks use map bounds rn2(sx), rn2(sy).
    let randX = 0, randY = 0;
    if (!args.coord) {
        const pos = randomLocationWithHumidity(DRY, game.currentRoom, false);
        if (pos) {
            randX = pos.x;
            randY = pos.y;
        } else {
            // keep C-shaped fallback behavior if location search fails
            randX = game.x_maze_max ?? ((COLNO - 1) & ~1);
            randY = game.y_maze_max ?? ((ROWNO - 1) & ~1);
        }
    }
    // Step 2: Create object via mksobj_core or mkobj
    let obj;
    let objAlreadyPlaced = false;
    let forcedCorpsenm = null;
    let corpsenmDirective = null;
    let speDirective = Number.isInteger(args.spe) ? args.spe : null;
    const quantityDirective = Number.isInteger(args.quantity) ? args.quantity : null;
    if (args.id) {
        let otyp = find_objtype(args.id, args.class);
        if (args.id === 'corpse' && args.montype) {
            otyp = 265; // CORPSE
        }
        if ((otyp === STATUE || otyp === CORPSE) && speDirective == null) {
            // C ref: sp_lev.c lspo_object() -> tmpobj.spe from
            // historic/male/female flags (defaults to 0).
            let lflags = 0;
            if (args.historic) lflags |= CORPSTAT_HISTORIC;
            if (args.male) lflags |= CORPSTAT_MALE;
            if (args.female) lflags |= CORPSTAT_FEMALE;
            speDirective = lflags;
        }
        if (otyp === STATUE || otyp === FIGURINE || otyp === CORPSE
            || otyp === EGG || otyp === TIN) {
            const montype = typeof args.montype === 'string' ? args.montype : '';
            // C ref: sp_lev.c:3682 lspo_object — TIN with montype "spinach"
            // or "empty" (and EGG with "empty") short-circuits to a
            // non-monster object: corpsenm=NON_PM and spe is 1 (spinach)
            // or 0 (empty/generic egg).
            const mtLow = montype.toLowerCase();
            const isSpinachTin = otyp === TIN && mtLow === 'spinach';
            const isEmptyTin   = otyp === TIN && mtLow === 'empty';
            const isEmptyEgg   = otyp === EGG && mtLow === 'empty';
            if (isSpinachTin || isEmptyTin || isEmptyEgg) {
                forcedCorpsenm = NON_PM;
                speDirective = isSpinachTin ? 1 : 0;
            } else if (montype.length === 1) {
                const monclass = def_char_to_monclass(montype);
                if (monclass > 0) {
                    const pm = mkclass(monclass, G_NOGEN | G_IGNORE);
                    if (pm) {
                        const idx = mons.indexOf(pm);
                        if (idx >= 0) forcedCorpsenm = idx;
                    }
                }
            } else if (montype.length > 1) {
                const mgender = { val: NEUTRAL };
                let mndx = name_to_monplus(montype, null, mgender);
                if (mndx < 0) {
                    const roleAlias = {
                        cavewoman: 'caveman',
                        priestess: 'priest',
                    };
                    const aliased = roleAlias[montype.toLowerCase()];
                    if (aliased) mndx = name_to_monplus(aliased, null, mgender);
                }
                if (mndx >= 0) forcedCorpsenm = mndx;
            }
        }
        if (otyp >= 0) {
            obj = mksobj_core(otyp, true, !named);
        } else {
            rnd(2); // unknown item fallback
            return;
        }
    } else if (args.class) {
        const oclass = def_char_to_objclass(args.class);
        if (oclass === MAXOCLASSES) {
            throw new Error(`create_object: unexpected object class '${args.class}'`);
        }
        if (oclass === COIN_CLASS) {
            const [ax, ay] = args.coord ? toAbsCoord(args.coord) : [randX, randY];
            obj = mkgold(0, ax, ay);
            objAlreadyPlaced = true;
        } else {
            obj = mkobj(oclass, !named);
        }
    } else {
        // C ref: create_object(): no class specified -> mkobj_at(RANDOM_CLASS,...)
        obj = mkobj(RANDOM_CLASS, !named);
    }
    if (Number.isInteger(args.corpsenm)) {
        corpsenmDirective = args.corpsenm;
    } else if (forcedCorpsenm != null) {
        corpsenmDirective = forcedCorpsenm;
    }
    // Step 3: Place on map (apply cvt_to_abscoord offset)
    let pushedContainer = false;
    if (obj) {
        if (speDirective != null) {
            obj.spe = speDirective;
        }
        // C ref: sp_lev.c:2234 — apply BUC (blessed/uncursed/cursed) state
        if (args.buc) {
            switch (args.buc) {
            case 'blessed': bless(obj); break;
            case 'uncursed': obj.blessed = false; obj.cursed = false; break;
            case 'cursed': curse(obj); break;
            case 'not-cursed': obj.cursed = false; break;
            case 'not-blessed': obj.blessed = false; break;
            case 'not-uncursed': blessorcurse(obj, 1); break;
            // 'random' or default: keep mkobj result
            }
        }
        // C ref: sp_lev.c create_object(): corpsenm is "empty" if NON_PM,
        // random if NON_PM-1, otherwise specific PM index. For the explicit
        // spinach/empty TIN and empty EGG cases (montype="spinach"/"empty"),
        // we must force corpsenm=NON_PM to override any mksobj-picked mndx.
        if (corpsenmDirective === NON_PM) {
            obj.corpsenm = NON_PM;
        } else if (corpsenmDirective != null) {
            if (corpsenmDirective === NON_PM - 1) {
                set_corpsenm(obj, rndmonnum());
            } else {
                set_corpsenm(obj, corpsenmDirective);
            }
        }
        // C ref: sp_lev.c:2267-2268 — name the object (may create artifact)
        if (named && args.name) {
            obj = oname(obj, args.name, ONAME_LEVEL_DEF);
        }
        // C ref: sp_lev.c:create_object() — apply quantity only for
        // mergeable object types (o->quan > 0 && objects[otyp].oc_merge).
        if (quantityDirective != null
            && quantityDirective > 0
            && game.objects[obj.otyp]?.oc_merge) {
            obj.quan = quantityDirective;
            obj.owt = weight(obj);
        }
        // C ref: sp_lev.c:create_object() object table flags.
        // Preserve locked/broken/trapped precedence exactly:
        // - explicit locked 0/1 wins;
        // - otherwise broken forces obroken=1 and olocked=0;
        // - trapped and trap_known only apply when explicitly specified.
        if (args.locked === false || args.locked === true) {
            obj.olocked = args.locked ? 1 : 0;
        } else if (args.broken) {
            obj.obroken = 1;
            obj.olocked = 0;
        }
        if (args.trapped === false || args.trapped === true) {
            obj.otrapped = args.trapped ? 1 : 0;
        }
        if (args.trapped && (args.trap_known === false || args.trap_known === true)) {
            obj.tknown = args.trap_known ? 1 : 0;
        }
        obj.greased = args.greased ? 1 : 0;
        const [ax, ay] = args.coord ? toAbsCoord(args.coord) : [randX, randY];
        if (!objAlreadyPlaced) {
            place_object(obj, ax, ay);
        }
        if (isContained) {
            const parent = containerObjStack[containerObjStack.length - 1];
            // C: remove_object(otmp) then add_to_container — NOT obj_extract_self
            remove_object(obj);
            if (parent) {
                obj.where = OBJ_CONTAINED;
                obj.ocontainer = parent;
                obj.nobj = parent.cobj || null;
                parent.cobj = obj;
            }
        } else if (carryingMonster) {
            // C ref: sp_lev.c:create_object() invent_carrying_monster path.
            remove_object(obj);
            await mpickobj(carryingMonster, obj);
        }
        if (hasContentsField) {
            // C ref: sp_lev.c:2344-2345 — when a container has a Lua
            // contents callback, C deletes the random items that mksobj_init
            // (mkbox_cnts) already placed, so the callback starts with an
            // empty container. Without this, JS would have both the random
            // mkbox_cnts items AND the callback items.
            delete_contents(obj);
            obj.cobj = null;
            containerObjStack.push(obj);
            pushedContainer = true;
        }
        // C ref: sp_lev.c create_object() Medusa statue special case.
        // Random statues on Medusa level become petrified monsters and can
        // inherit that monster's inventory.
        if (obj.otyp === STATUE && isMedusaLevel()
            && (args.montype == null || args.montype === '')
            && forcedCorpsenm == null) {
            const createObjectRndmonnum = () => {
                pushRngLogEntry('>rndmonnum');
                const mndx = rndmonnum();
                pushRngLogEntry(`<rndmonnum=${mndx}`);
                return mndx;
            };
            let was = null;
            let wastyp = (Number.isInteger(obj.corpsenm) && obj.corpsenm >= 0)
                ? obj.corpsenm
                : createObjectRndmonnum();
            for (let i = 0; i < 1000; i++, wastyp = createObjectRndmonnum()) {
                const pm = mons[wastyp] || null;
                was = await makemon(pm, 0, 0, MM_NOCOUNTBIRTH | MM_NOMSG);
                if (!was) continue;
                if (!resists_ston(was) && !poly_when_stoned(mons[wastyp])) {
                    break;
                }
                unlinkMonster(was);
                was = null;
            }
            if (was) {
                if (wastyp >= 0) obj.corpsenm = wastyp;
                while (was.minvent) {
                    const inv = was.minvent;
                    was.minvent = inv.nobj || null;
                    inv.nobj = obj.cobj || null;
                    inv.where = OBJ_CONTAINED;
                    inv.ocontainer = obj;
                    obj.cobj = inv;
                }
                unlinkMonster(was);
            }
        }
    }
    // C ref: sp_lev.c:2423-2438 — stackobj + burial happen BEFORE the
    // contents callback. In C, create_object returns to Lua, which then
    // runs the callback. So the object is stacked and buried before any
    // contents are added. We must match this order.
    if (obj && !isContained) {
        stackobj(obj);
        // C ref: sp_lev.c create_object() o->buried path: calls bury_an_obj
        // after stackobj, which calls obj_resists(otmp, 0, 0) (consumes rn2)
        // and then buries the object.
        if (args.buried) {
            const dealloced_ref = { value: false };
            bury_an_obj(obj, dealloced_ref);
            if (dealloced_ref.value) {
                obj = null;
            }
        }
    }
    // Step 4: Contents callback (for containers)
    // C ref: In C, create_object() returns to Lua AFTER burial. Then Lua
    // runs the contents callback. We run it here, after burial, to match.
    if (obj && typeof args.contents === 'function') {
        const out = args.contents(obj);
        if (out && typeof out.then === 'function') {
            await out;
        }
    }
    if (pushedContainer) {
        containerObjStack.pop();
    }
    // Attach Lua-style timer methods for themed room contents functions.
    // C ref: nhlib.lua obj:stop_timer(name) and obj:start_timer(name, time)
    // map to timeout.c stop_timer(func_index, arg) / start_timer(when, TIMER_OBJECT, func_index, arg).
    if (obj) {
        const _timerNameMap = { 'rot-corpse': ROT_CORPSE, 'zombify-mon': ZOMBIFY_MON };
        obj.stop_timer = function(name) {
            const tp = _timerNameMap[name];
            if (tp !== undefined) stop_timer(tp, { a_obj: obj });
        };
        obj.start_timer = function(name, time) {
            const tp = _timerNameMap[name];
            if (tp !== undefined) start_timer(time, TIMER_OBJECT, tp, { a_obj: obj });
        };
    }
    return obj;
}
// des.monster — C ref: sp_lev.c:3147 lspo_monster()
export async function monster(args, x, y) {
    args = normalizeMonsterArgs(args, x, y);
    const hasRandomCoord = Array.isArray(args.coord)
        && args.coord.length >= 2
        && args.coord[0] === -1
        && args.coord[1] === -1;
    const debugMonsterCoord = typeof process !== 'undefined'
        && process?.env?.SPLEV_MON_COORD_DEBUG === '1';
    // C ref: sp_lev.c:1925 create_monster
    // 1. find_montype to resolve name → PM index
    // 2. induced_align for alignment
    // 3. makemon for creation (heavy RNG)
    let mndx = -1;
    let classSym = 0;
    // C ref: sp_lev.c:3230 — gender determined here, applied after makemon.
    const mgender = { val: NEUTRAL };
    if (typeof args.class === 'string' && args.class.length === 1) {
        classSym = def_char_to_monclass(args.class);
    }
    if (args.id) {
        // C ref: sp_lev.c find_montype/name_to_monplus gender flow.
        mndx = name_to_monplus(args.id, null, mgender);
        if (mndx >= 0) {
            if (is_male(mons[mndx]) || is_female(mons[mndx])) {
                mgender.val = is_female(mons[mndx]) ? FEMALE : MALE;
            } else {
                mgender.val = (mgender.val === FEMALE) ? FEMALE
                    : (mgender.val === MALE) ? MALE : rn2(2);
            }
        }
    }
    // C ref: sp_lev.c create_monster(): amask = sp_amask_to_amask(m->sp_amask)
    // This consumes RNG only for RANDOM/COALIGNED/NONCOALIGNED align modes.
    const tableAlign = getTableAlign(args.align ?? args.aligned);
    const _amask = spAmaskToAmask(tableAlign);
    let ptr = null;
    let forceRandom = false;
    if (mndx >= 0) {
        const pm = mons[mndx];
        const gMvflags = game.mvitals?.[mndx]?.mvflags ?? 0;
        // C ref: sp_lev.c:1949-1953 create_monster() explicit id handling.
        if ((pm?.geno & G_UNIQ) && (gMvflags & G_EXTINCT))
            return;
        if (gMvflags & G_GONE)
            forceRandom = true;
        else
            ptr = pm;
    } else if (classSym > 0 && !forceRandom) {
        ptr = mkclass(classSym, G_NOGEN) || null;
    }
    // C ref: sp_lev.c create_monster() race-monster randomization in Mines.
    if (In_mines(game.u?.uz) && ptr && your_race(ptr)
        && (Race_if(PM_DWARF) || Race_if(PM_GNOME)) && rn2(3)) {
        ptr = null;
    }
    let ax;
    let ay;
    if (debugMonsterCoord) {
        const coordStr = Array.isArray(args.coord) ? `${args.coord[0]},${args.coord[1]}` : 'none';
        pushRngLogEntry(`^dbg_moncoord[id=${args.id || ''} class=${args.class || ''} coord=${coordStr} random=${hasRandomCoord ? 1 : 0}]`);
        const cr = game.currentRoom;
        if (cr) {
            pushRngLogEntry(`^dbg_monroom[lx=${cr.lx} ly=${cr.ly} hx=${cr.hx} hy=${cr.hy} nsub=${cr.nsubrooms || 0}]`);
        } else {
            pushRngLogEntry('^dbg_monroom[none]');
        }
        const hdbg = ptr ? pmToHumidityFlags(ptr) : DRY;
        pushRngLogEntry(`^dbg_montype[classSym=${classSym} mndx=${mndx} ptr=${ptr ? (ptr.mname || '') : ''} mlet=${ptr ? (ptr.mlet || '') : ''} h=${hdbg} sx=${game.sp_xstart ?? -1} sy=${game.sp_ystart ?? -1} sw=${game.sp_xsize ?? -1} sh=${game.sp_ysize ?? -1}]`);
    }
    if (args.coord && !hasRandomCoord) {
        [ax, ay] = toAbsCoord(args.coord);
    } else {
        const humidity = ptr ? pmToHumidityFlags(ptr) : DRY;
        let pos = randomLocationCoordLikeC(humidity, game.currentRoom);
        if (!pos && ptr) {
            // C ref: create_monster() fallback loc |= DRY.
            pos = randomLocationCoordLikeC(humidity | DRY, game.currentRoom);
        } else if (!pos) {
            pos = randomLocationCoordLikeC(DRY, game.currentRoom);
        }
        if (!pos) return;
        ax = pos.x;
        ay = pos.y;
    }
    // C ref: sp_lev.c:1976-1978 — if occupied, try adjacent relocation.
    const occupiedAtChoice = !!m_at(ax, ay);
    if (occupiedAtChoice) {
        const cc = { x: 0, y: 0 };
        if (enexto_core(cc, ax, ay, ptr, GP_CHECKSCARY | GP_AVOID_MONPOS)) {
            ax = cc.x;
            ay = cc.y;
        }
    }
    // C ref: sp_lev.c:1981-1982 create_monster().
    if (game.currentRoom && !inside_room(game.currentRoom, ax, ay)) {
        return;
    }
    let mmFlags = Number.isInteger(args.mm_flags) ? args.mm_flags : 0;
    if (args.tail === false) mmFlags |= MM_NOTAIL;
    if (args.group === false) mmFlags |= MM_NOGRP;
    if (args.adjacentok === true) mmFlags |= MM_ADJACENTOK;
    if (args.ignorewater === true) mmFlags |= MM_IGNOREWATER;
    if (args.countbirth === false) mmFlags |= MM_NOCOUNTBIRTH;
    let mtmp = null;
    // C ref: sp_lev.c:1984-1989 create_monster().
    if (tableAlign !== AM_SPLEV_RANDOM) {
        const roamerAlign = Amask2align(_amask);
        const roamerPeaceful = (args.peaceful === 0 || args.peaceful === false) ? 0 : 1;
        mtmp = await mk_roamer(ptr, roamerAlign, ax, ay, roamerPeaceful);
    } else if (mndx >= PM_ARCHEOLOGIST && mndx <= PM_WIZARD) {
        mtmp = await mk_mplayer(ptr, ax, ay, false);
    } else {
        mtmp = await makemon(ptr, ax, ay, mmFlags);
    }
    if (!mtmp) return;
    // C ref: sp_lev.c:2126 — override makemon's rn2(2) gender with
    // the sp_lev rn2(2) gender determined earlier. Both C and JS
    // consume two rn2(2) calls per monster (sp_lev + makemon), but
    // C uses sp_lev's result while JS was using makemon's.
    if (mgender.val === FEMALE) mtmp.female = true;
    else if (mgender.val === MALE) mtmp.female = false;
    if (args.peaceful === 0 || args.peaceful === 1)
        mtmp.mpeaceful = !!args.peaceful;
    if (args.asleep === 0 || args.asleep === 1 || args.asleep === true || args.asleep === false)
        mtmp.msleeping = args.asleep ? 1 : 0;
    if (args.waiting)
        mtmp.mstrategy |= STRAT_WAITFORU;
    // C ref: sp_lev.c:2162-2166 — waiting vampshifter reverts to base form via newcham().
    if (args.waiting && vampshifted(mtmp) && is_vampshifter(mtmp)) {
        const base = mtmp.cham;
        if (base >= 0 && base < mons.length) {
            apply_init_newcham(mtmp, base);
        }
    }
    if (args.cancelled)
        mtmp.mcan = 1;
    if (args.revived)
        mtmp.mrevived = 1;
    if (args.avenge)
        mtmp.mavenge = 1;
    if (args.stunned)
        mtmp.mstun = 1;
    if (args.confused)
        mtmp.mconf = 1;
    if (args.invisible) {
        mtmp.minvis = 1;
        mtmp.perminvis = 1;
    }
    if (args.blinded) {
        mtmp.mcansee = 0;
        mtmp.mblinded = args.blinded % 127;
    }
    if (args.paralyzed) {
        mtmp.mcanmove = 0;
        mtmp.mfrozen = args.paralyzed % 127;
    }
    if (args.fleeing) {
        mtmp.mflee = 1;
        mtmp.mfleetim = args.fleeing % 127;
    }
    const hasCustomInventory = typeof args.inventory === 'function';
    const keepDefaultInventory = !!args.keep_default_invent;
    // C ref: sp_lev.c:2177-2186 create_monster() inventory policy:
    // custom inventory drops default minvent unless keep_default_invent=true.
    if (hasCustomInventory && !keepDefaultInventory) {
        await mdrop_special_objs(mtmp);
        while (mtmp.minvent) {
            const otmp = mtmp.minvent;
            await extract_from_minvent(mtmp, otmp, true, true);
            obfree(otmp, null);
        }
    }
    if (hasCustomInventory) {
        inventoryMonsterStack.push(mtmp);
        try {
            const out = args.inventory(mtmp);
            if (out && typeof out.then === 'function') {
                await out;
            }
        } finally {
            inventoryMonsterStack.pop();
        }
        // C ref: sp_lev.c:3037-3041 spo_end_moninvent().
        await m_dowear(mtmp, true);
    }
}
export function gold(args, x, y) {
    let amount = -1;
    let coord = null;
    if (typeof args === 'number') {
        amount = args;
        coord = normalizeCoordPair(null, x, y);
    } else if (args && typeof args === 'object') {
        amount = Number.isFinite(args.amount) ? args.amount : -1;
        coord = normalizeCoordPair(args.coord, args.x, args.y);
    } else {
        coord = normalizeCoordPair(null, x, y);
    }
    let pos = null;
    if (coord) {
        const abs = toAbsCoord(coord);
        if (abs && isok(abs[0], abs[1])) {
            pos = { x: abs[0], y: abs[1] };
        }
    } else {
        // C ref: lspo_gold() -> get_location_coord(..., DRY, croom, ...)
        pos = randomLocationWithHumidity(DRY, game.currentRoom, false);
    }
    if (!pos) return null;
    if (amount < 0) {
        amount = rnd(200);
    }
    return mkgold(amount, pos.x, pos.y);
}
function roomFromPos(x, y, wantedType = null) {
    // game.level.rooms is where des_region/add_room stores rooms during level gen
    const rooms = game.level.rooms || [];
    let fallback = null;
    for (let i = 0; i < (game.level.nroom || rooms.length); i++) {
        const r = rooms[i];
        if (!r || !(x >= r.lx && x <= r.hx && y >= r.ly && y <= r.hy)) {
            continue;
        }
        if (wantedType == null || r.rtype === wantedType) {
            return r;
        }
        if (!fallback) fallback = r;
    }
    return fallback;
}
export async function altar(args = {}) {
    const coord = normalizeCoordPair(args.coord, args.x, args.y);
    const pos = chooseSplevCoord('dry', coord);
    if (!pos) return null;
    const loc = game.level?.at(pos.x, pos.y);
    if (!loc) return null;
    loc.typ = ALTAR;
    const rawAlign = args.align ?? args.aligned;
    const tableAlign = getTableAlign(rawAlign);
    // TODO(parity): C consumes a second noncoalignment() rn2(2) before
    // first object placement on this seed/path; preserve current parity
    // until the missing structural callsite is identified.
    if (tableAlign === AM_SPLEV_NONCO) {
        spAmaskToAmask(tableAlign);
    }
    let mask = spAmaskToAmask(tableAlign);
    const type = String(args.type || 'altar').toLowerCase();
    loc.flags = mask;
    // C ref: sp_lev.c:2474-2487 — shrine/sanctum handling
    // Determine shrine value: 0=altar, 1=shrine, 2=sanctum, -1=random
    let shrine = (type === 'shrine') ? 1 : (type === 'sanctum') ? 2 : 0;
    if (shrine < 0) shrine = rn2(2); // random case
    // Check if altar is in a temple room
    // C ref: lspo_altar() receives croom from current generation context.
    // During nested des.makeRoom contents, room may not yet be in
    // game.level.rooms, so prefer active currentRoom over global lookup.
    const activeRoom = game.currentRoom;
    const activeIsTempleAtPos = !!activeRoom
        && activeRoom.rtype === TEMPLE
        && pos.x >= activeRoom.lx && pos.x <= activeRoom.hx
        && pos.y >= activeRoom.ly && pos.y <= activeRoom.hy;
    const croom = activeIsTempleAtPos
        ? activeRoom
        : roomFromPos(pos.x, pos.y, TEMPLE);
    const croom_is_temple = croom && croom.rtype === TEMPLE;
    if (croom_is_temple && shrine) {
        await priestini(game.u?.uz, croom, pos.x, pos.y, shrine > 1);
        loc.flags |= AM_SHRINE;
        if (shrine === 2) loc.flags |= AM_SANCTUM;
        if (game.level?.flags) game.level.flags.has_temple = true;
    }
    return { x: pos.x, y: pos.y };
}
export function grave(...args) {
    let coord = null;
    let text = null;
    if (args.length === 3 && Number.isFinite(args[0]) && Number.isFinite(args[1])) {
        coord = normalizeCoordPair(null, args[0], args[1]);
        text = args[2] ?? null;
    } else if (args.length >= 1 && args[0] && typeof args[0] === 'object' && !(args[0] instanceof SelectionVar)) {
        const opts = args[0];
        coord = normalizeCoordPair(opts.coord, opts.x, opts.y);
        text = typeof opts.text === 'string' ? opts.text : null;
    }
    const pos = chooseSplevCoord('dry', coord && coord[0] === -1 && coord[1] === -1 ? null : coord);
    if (!pos) return null;
    const loc = game.level?.at(pos.x, pos.y);
    if (!loc || t_at(pos.x, pos.y)) return null;
    make_grave(pos.x, pos.y, text);
    return { x: pos.x, y: pos.y };
}
export function feature(args, x, y) {
    let type;
    let coord;
    let flagsSource = null;
    if (typeof args === 'string') {
        type = args;
        coord = normalizeCoordPair(x, null, null);
        if (!coord) coord = normalizeCoordPair(null, x, y);
    } else {
        flagsSource = args || {};
        type = flagsSource.type;
        coord = normalizeCoordPair(flagsSource.coord, flagsSource.x, flagsSource.y);
    }
    const typeMap = {
        fountain: FOUNTAIN,
        sink: SINK,
        pool: POOL,
        throne: THRONE,
        tree: TREE,
    };
    const typ = typeMap[String(type || '').toLowerCase()];
    if (!typ) return null;
    const pos = chooseSplevCoord(coord ? 'any' : 'dry', coord);
    if (!pos) return null;
    const loc = game.level?.at(pos.x, pos.y);
    if (!loc) return null;
    if (IS_FURNITURE(loc.typ)) return null;
    if (!set_levltyp(pos.x, pos.y, typ)) return null;
    if (!flagsSource) return { x: pos.x, y: pos.y };
    switch (typ) {
    case FOUNTAIN:
        if ('looted' in flagsSource) loc.flags = flagsSource.looted ? (loc.flags | F_LOOTED) : (loc.flags & ~F_LOOTED);
        if ('warned' in flagsSource) loc.flags = flagsSource.warned ? (loc.flags | F_WARNED) : (loc.flags & ~F_WARNED);
        break;
    case SINK:
        if ('pudding' in flagsSource) loc.flags = flagsSource.pudding ? (loc.flags | S_LPUDDING) : (loc.flags & ~S_LPUDDING);
        if ('dishwasher' in flagsSource) loc.flags = flagsSource.dishwasher ? (loc.flags | S_LDWASHER) : (loc.flags & ~S_LDWASHER);
        if ('ring' in flagsSource) loc.flags = flagsSource.ring ? (loc.flags | S_LRING) : (loc.flags & ~S_LRING);
        break;
    case THRONE:
        if ('looted' in flagsSource) loc.flags = flagsSource.looted ? (loc.flags | T_LOOTED) : (loc.flags & ~T_LOOTED);
        break;
    case TREE:
        if ('looted' in flagsSource) loc.flags = flagsSource.looted ? (loc.flags | TREE_LOOTED) : (loc.flags & ~TREE_LOOTED);
        if ('swarm' in flagsSource) loc.flags = flagsSource.swarm ? (loc.flags | TREE_SWARM) : (loc.flags & ~TREE_SWARM);
        break;
    default:
        break;
    }
    return { x: pos.x, y: pos.y };
}
export function levregion(args = {}) {
    const typeMap = {
        'stair-down': LR_DOWNSTAIR,
        'stair-up': LR_UPSTAIR,
        portal: LR_PORTAL,
        branch: LR_BRANCH,
        teleport: LR_TELE,
        'teleport-up': LR_UPTELE,
        'teleport-down': LR_DOWNTELE,
    };
    const lregion = getLregion(args);
    if (!lregion) return null;
    lregion.rtype = typeMap[String(args.type || 'stair-down').toLowerCase()] ?? LR_DOWNSTAIR;
    lregion.padding = args.padding ?? 0;
    lregion.rname = { str: args.name ?? null };
    levregionAdd(lregion);
    return lregion;
}
export function wallify(args) {
    let x1 = -1, y1 = -1, x2 = -1, y2 = -1;
    if (args && typeof args === 'object') {
        x1 = args.x1 ?? -1;
        y1 = args.y1 ?? -1;
        x2 = args.x2 ?? -1;
        y2 = args.y2 ?? -1;
    }
    const span = getLocationSpan();
    wallifyMap(
        x1 < 0 ? (span.mx - 1) : x1,
        y1 < 0 ? (span.my - 1) : y1,
        x2 < 0 ? (span.mx + span.sx + 1) : x2,
        y2 < 0 ? (span.my + span.sy + 1) : y2,
    );
}
function wallifyMap(x1, y1, x2, y2) {
    // C ref: sp_lev.c wallify_map()
    const map = game.level;
    if (!map) return;
    const minX = Math.max(1, x1);
    const minY = Math.max(0, y1);
    const maxX = Math.min(COLNO - 1, x2);
    const maxY = Math.min(ROWNO - 1, y2);
    for (let y = minY; y <= maxY; y++) {
        const loY = (y > 0) ? (y - 1) : 0;
        const hiY = (y < maxY) ? (y + 1) : maxY;
        for (let x = minX; x <= maxX; x++) {
            const loc = map.at(x, y);
            if (!loc || loc.typ !== STONE) continue;
            const loX = (x > 1) ? (x - 1) : 1;
            const hiX = (x < maxX) ? (x + 1) : maxX;
            let found = false;
            for (let yy = loY; yy <= hiY && !found; yy++) {
                for (let xx = loX; xx <= hiX; xx++) {
                    const near = map.at(xx, yy);
                    if (!near) continue;
                    if (IS_ROOM(near.typ) || near.typ === CROSSWALL) {
                        loc.typ = (yy !== y) ? HWALL : VWALL;
                        found = true;
                        break;
                    }
                }
            }
        }
    }
}
// des.room — C ref: sp_lev.c:4028 lspo_room()
// Creates a room during themed room generation.
export async function makeRoom(args) {
    const coder = ensureDesCoder();
    if (game.in_mk_themerooms && game.themeroom_failed) {
        return;
    }
    if (coder.n_subroom > MAX_NESTED_ROOMS) {
        throw new Error('Too deeply nested rooms');
    }
    const coord = normalizeCoordPair(args?.coord, args?.x, args?.y);
    const x = coord ? coord[0] : -1;
    const y = coord ? coord[1] : -1;
    if ((x === -1 || y === -1) && x !== y) {
        throw new Error('Room must have both x and y');
    }
    const hasW = Number.isFinite(args?.w);
    const hasH = Number.isFinite(args?.h);
    if (hasW !== hasH) {
        throw new Error('Room must have both w and h');
    }
    const roomSpec = {
        x,
        y,
        w: hasW ? args.w : -1,
        h: hasH ? args.h : -1,
        xalign: ROOM_XALIGN[String(args?.xalign ?? 'random').toLowerCase()] ?? -1,
        yalign: ROOM_YALIGN[String(args?.yalign ?? 'random').toLowerCase()] ?? -1,
        rtype: getRoomTypeOpt(args?.type),
        chance: args?.chance ?? 100,
        rlit: args?.lit ?? -1,
        needfill: args?.filled ?? (game.in_mk_themerooms ? 0 : 1),
        joined: args?.joined ?? true,
    };
    if (!coder.failed_room[coder.n_subroom - 1]) {
        const room = buildRoom(roomSpec, coder.croom);
        if (room) {
            const n = coder.n_subroom;
            coder.tmproomlist[n] = room;
            coder.failed_room[n] = false;
            if (coder.tmproomlist[n - 1]) {
                coder.tmproomlist[n - 1].irregular = true;
            }
            coder.n_subroom++;
            updateCroom();
            if (typeof args?.contents === 'function') {
                // C ref: sp_lev.c Lua mkroom binding exposes .width and .height
                // as computed fields (hx-lx+1 and hy-ly+1). Contents callbacks
                // like the Mausoleum's inner room use these to compute positions.
                if (!Number.isFinite(room.width)) room.width = room.hx - room.lx + 1;
                if (!Number.isFinite(room.height)) room.height = room.hy - room.ly + 1;
                const out = withCurrentRoom(room, () => args.contents(room));
                if (out && typeof out.then === 'function') await out;
            }
            spoEndroom(coder);
            addDoorsToRoom(room);
            return;
        }
        if (game.in_mk_themerooms) {
            game.themeroom_failed = true;
        }
    }
    coder.tmproomlist[coder.n_subroom] = null;
    coder.failed_room[coder.n_subroom] = true;
    coder.n_subroom++;
    updateCroom();
    spoEndroom(coder);
    if (game.in_mk_themerooms) {
        game.themeroom_failed = true;
    }
}
// Allow sp_lev to set the "current room" for coordinate offsets
// C ref: sp_lev.c croom context — must update both _currentRoom and coder.croom
// so that croomActive is true and >somexy/<somexy=1 midlogs get emitted.
export function setCurrentRoom(rm) {
    game.currentRoom = rm;
    ensureDesCoder().croom = rm ?? null;
}
// Stubs for des.* functions used by themerms.js fill callbacks.
export function exclusion(args = {}) {
    const typeMap = {
        teleport: LR_TELE,
        'teleport-up': LR_UPTELE,
        'teleport-down': LR_DOWNTELE,
        'monster-generation': LR_MONGEN,
    };
    const region = [...(args.region || [0, 0, 0, 0])];
    const p1 = chooseFilteredCoord([region[0], region[1]], () => true);
    const p2 = chooseFilteredCoord([region[2], region[3]], () => true);
    if (!p1 || !p2) return null;
    const zone = {
        zonetype: typeMap[String(args.type || 'teleport').toLowerCase()] ?? LR_TELE,
        lx: p1.x,
        ly: p1.y,
        hx: p2.x,
        hy: p2.y,
    };
    if (!Array.isArray(game.level?.exclusionZones)) return zone;
    game.level.exclusionZones.push(zone);
    return zone;
}
export function gas_cloud(args = {}) {
    if (!args || typeof args !== 'object') return null;
    let cloud = null;
    if (args.selection instanceof SelectionVar) {
        cloud = {
            points: args.selection.points.map((pt) => ({ x: pt.x, y: pt.y })),
        };
    } else {
        const coord = normalizeCoordPair(args.coord, args.x, args.y);
        const pos = chooseFilteredCoord(coord, () => true);
        if (!pos) return null;
        cloud = { x: pos.x, y: pos.y, radius: 1 };
    }
    cloud.damage = args.damage ?? 0;
    cloud.ttl = args.ttl ?? -2;
    if (!Array.isArray(game.level?.gasClouds)) return cloud;
    game.level.gasClouds.push(cloud);
    return cloud;
}
function fullLevelSelection() {
    const points = [];
    for (let x = 1; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            points.push({ x, y });
        }
    }
    return new SelectionVar(points);
}
function regionSelection(args = {}) {
    const region = args.region || [args.x1, args.y1, args.x2, args.y2];
    if (!Array.isArray(region) || region.length < 4) return null;
    const p1 = chooseFilteredCoord([region[0], region[1]], () => true);
    const p2 = chooseFilteredCoord([region[2], region[3]], () => true);
    if (!p1 || !p2) return null;
    const lx = Math.min(p1.x, p2.x);
    const hx = Math.max(p1.x, p2.x);
    const ly = Math.min(p1.y, p2.y);
    const hy = Math.max(p1.y, p2.y);
    const points = [];
    for (let x = lx; x <= hx; x++) {
        for (let y = ly; y <= hy; y++) {
            points.push({ x, y });
        }
    }
    return new SelectionVar(points);
}
function parseMatchMapChr(s) {
    if (typeof s !== 'string' || s.length !== 1) return -1;
    if (s === 'w') return MATCH_WALL;
    return splev_chr2typ(s);
}
function matchMapTyps(matchTyp, levlTyp) {
    if (matchTyp === MATCH_WALL) return IS_STWALL(levlTyp);
    if (matchTyp === MAX_TYPE) return true;
    return matchTyp === levlTyp;
}
function mapfragFromStr(str) {
    if (typeof str !== 'string') return null;
    const data = str.replace(/[0-9]/g, '');
    const rows = data.split('\n');
    if (rows.length && rows[rows.length - 1] === '') rows.pop();
    const wid = rows.reduce((m, row) => Math.max(m, row.length), 0);
    const hei = rows.length;
    if (!(wid % 2) || !(hei % 2) || wid < 1 || hei < 1) return null;
    return { rows, wid, hei };
}
function mapfragGet(mf, x, y) {
    const row = mf.rows[y] || '';
    const ch = row[x] ?? '\0';
    return parseMatchMapChr(ch);
}
function mapfragMatch(mf, x, y) {
    const xoff = Math.trunc(mf.wid / 2);
    const yoff = Math.trunc(mf.hei / 2);
    for (let rx = -xoff; rx <= xoff; rx++) {
        for (let ry = -yoff; ry <= yoff; ry++) {
            const mapc = mapfragGet(mf, rx + xoff, ry + yoff);
            const levc = isok(x + rx, y + ry) ? game.level?.at(x + rx, y + ry)?.typ : STONE;
            if (!matchMapTyps(mapc, levc)) return false;
        }
    }
    return true;
}
export function replace_terrain(args = {}) {
    const totyp = parseMatchMapChr(args.toterrain);
    if (totyp < 0 || totyp >= MAX_TYPE) return;
    const chance = args.chance ?? 100;
    const tolit = args.lit ?? SET_LIT_NOCHANGE;
    const fromtyp = args.fromterrain != null ? parseMatchMapChr(args.fromterrain) : -1;
    const mapfrag = fromtyp < 0 ? mapfragFromStr(args.mapfragment) : null;
    if (fromtyp < 0 && !mapfrag) return;
    let sel = null;
    if (args.selection instanceof SelectionVar) sel = args.selection;
    else sel = regionSelection(args);
    if (!sel) sel = fullLevelSelection();
    const terr = { ter: totyp, tlit: tolit };
    for (const pt of sel.points) {
        const loc = game.level?.at(pt.x, pt.y);
        if (!loc) continue;
        const matches = mapfrag
            ? mapfragMatch(mapfrag, pt.x, pt.y)
            : matchMapTyps(fromtyp, loc.typ);
        if (!matches) continue;
        if (rn2(100) >= chance) continue;
        setTerrainCell(pt.x, pt.y, terr);
    }
}
function setTerrainCell(x, y, terr) {
    const loc = game.level?.at(x, y);
    if (!loc) return;
    setLevlTypLit(x, y, terr.ter, terr.tlit);
    loc.icedpool = 0;
    if (loc.typ === SDOOR || IS_DOOR(loc.typ)) {
        if (loc.typ === SDOOR) loc.flags = D_CLOSED;
        if (x > 0) {
            const left = game.level?.at(x - 1, y);
            if (left && (IS_WALL(left.typ) || left.horizontal)) loc.horizontal = 1;
        }
    } else if (loc.typ === HWALL || loc.typ === IRONBARS) {
        loc.horizontal = 1;
    } else if (game.splev_init_present && loc.typ === ICE) {
        loc.icedpool = game.icedpools ? ICED_POOL : ICED_MOAT;
    } else if (loc.typ === CLOUD) {
        game.level.engravings = game.level.engravings.filter((e) => !(e.x === x && e.y === y));
    }
}
export function terrain(arg1, arg2, arg3) {
    const terr = { tlit: SET_LIT_NOCHANGE, ter: -1 };
    let sel = null;
    let x = 0, y = 0;
    if (arguments.length === 1 && arg1 && typeof arg1 === 'object' && !(arg1 instanceof SelectionVar)) {
        const tx = arg1.x ?? arg1.coord?.[0] ?? -1;
        const ty = arg1.y ?? arg1.coord?.[1] ?? -1;
        x = tx;
        y = ty;
        if (tx === -1 && ty === -1 && arg1.selection instanceof SelectionVar) {
            sel = arg1.selection;
        }
        terr.ter = splev_chr2typ(arg1.typ);
        terr.tlit = arg1.lit ?? SET_LIT_NOCHANGE;
    } else if (arguments.length === 2 && arg1 && typeof arg1 === 'object' && !(arg1 instanceof SelectionVar)) {
        const coord = normalizeCoordPair(arg1, arg1?.x, arg1?.y);
        if (!coord) return;
        [x, y] = coord;
        terr.ter = splev_chr2typ(arg2);
    } else if (arguments.length >= 2 && arg1 instanceof SelectionVar) {
        sel = arg1;
        terr.ter = splev_chr2typ(arg2);
        if (arguments.length >= 3) terr.tlit = arg3;
    } else if (arguments.length === 3) {
        x = arg1;
        y = arg2;
        terr.ter = splev_chr2typ(arg3);
    } else {
        return;
    }
    if (terr.ter < 0 || terr.ter >= MAX_TYPE) return;
    if (sel) {
        for (const pt of sel.points) setTerrainCell(pt.x, pt.y, terr);
        return;
    }
    const coord = chooseFilteredCoord([x, y], () => true);
    if (!coord) return;
    setTerrainCell(coord.x, coord.y, terr);
}
export default {
    splev_chr2typ, des_map, des_region, selection, percent,
    shuffle, levelState, nh, initLuaMT,
    // des.* API for level scripts
    level_init, level_flags, map: des_map, region, makeRoom,
    non_diggable, teleport_region, finalize_level, message,
    non_passwall,
    stair, ladder, engraving, door, trap, object, monster, gold, levregion,
    setCurrentRoom,
    altar, corridor, exclusion, feature, gas_cloud, grave, replace_terrain, terrain, wallify,
    drawbridge, mazewalk, random_corridors,
};
export function init_sp_lev_globals() {
    game.currentRoom = null;
    game.sqkyBoardCount = 0;
}