aboutsummaryrefslogtreecommitdiff
path: root/Northstar.CustomServers/mod/scripts/vscripts/_utility.gnut
blob: 3546e3b7a9c8f0524c931bb976eb556209de1cb5 (plain)
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
globalize_all_functions

//=========================================================
//	_utility
//
//=========================================================

int functionref( bool = false ) ornull te = null
int EntTracker = 0

global const C_PLAYFX_SINGLE	= 0
global const C_PLAYFX_MULTIPLE	= 1
global const C_PLAYFX_LOOP		= 2

global const MUTEALLFADEIN 		= 2

global struct ZipLine
{
	entity start
	entity mid
	entity end
}

global int HUMAN_RAGDOLL_IMPACT_TABLE_IDX = -1

global struct ArrayDotResultStruct
{
	entity ent
	float dot
}

global struct ShieldDamageModifier
{
	float permanentDamageFrac = TITAN_SHIELD_PERMAMENT_DAMAGE_FRAC
	bool normalizeShieldDamage = false
	float damageScale = 1.0
}


struct
{
	bool isSkyboxView = false
} file

void function Utility_Init()
{
	te = TotalEnts
	EntTracker = 0

	#document( "SetDeathFuncName", "Sets the name of a function that runs when the NPC dies." )
	#document( "CenterPrint", "Print to the screen" )
	#document( "GetAllSoldiers", "Get all living soldiers." )
	#document( "ClearDeathFuncName", "Clears the script death function." )

	HUMAN_RAGDOLL_IMPACT_TABLE_IDX = PrecacheImpactEffectTable( "ragdoll_human" )

	RegisterSignal( "PetTitanUpdated" )
	RegisterSignal( "WaitDeadTimeOut" )
	RegisterSignal( "InventoryChanged" )

	AddClientCommandCallback( "OnDevnetBugScreenshot", ClientCommand_OnDevnetBugScreenshot )
	#if DEV
		FlagInit( "AimAssistSwitchTest_Enabled" )
		AddClientCommandCallback( "DoomTitan", ClientCommand_DoomTitan )
	#endif
}

void function GiveAllTitans()
{

	array<entity> players = GetPlayerArray()
	foreach ( player in players )
	{
		#if MP
		GiveTitanToPlayer( player )
		#endif

		if ( player.IsTitan() )
		{
			entity soul = player.GetTitanSoul()
			if ( soul )
			{
				SoulTitanCore_SetNextAvailableTime( soul, 1 )
			}
		}
	}

	array<entity> titans = GetNPCArrayByClass( "npc_titan" )
	foreach ( titan in titans )
	{
		entity soul = titan.GetTitanSoul()
		if ( soul )
			SoulTitanCore_SetNextAvailableTime( soul, 1 )
	}
}

#if DEV

void function KillAllBadguys()
{
	array<entity> npcs = GetNPCArrayOfEnemies( GetPlayerArray()[0].GetTeam() )
	foreach ( n in npcs )
	{
		if ( n.GetClassName() == "npc_bullseye" )
			continue

		if ( !IsAlive( n ) )
			continue
		n.Die()
	}
}

bool function ClientCommand_DoomTitan( entity player, array<string> args )
{
	entity titan
	if ( player.IsTitan() )
		titan = player
	else
		titan = player.GetPetTitan()

	if ( !IsAlive( titan ) )
		return true

	if ( GetDoomedState( titan ) )
		return true

	entity soul = titan.GetTitanSoul()
	soul.SetShieldHealth( 0 )

	titan.TakeDamage( titan.GetHealth(), null, null, { damageSourceId=damagedef_suicide, scriptType = DF_SKIP_DAMAGE_PROT } )

	return true
}
#endif

void function PrintPlaylists()
{
	printt( "=== PLAYLIST NAMES: ===" )

	int count = GetPlaylistCount()
	for ( int i = 0; i < count; i++ )
	{
		printt( "--", GetPlaylistName( i ) )
	}
}

entity function CreateEntity( string name )
{
//	if ( name == "npc_titan" )
//	{
//		DumpStack(3)
//	}
//	if ( name == "info_particle_system" )
//	{
//		printl( " " )
//		DumpStack(3)
//	}
	return Entities_CreateByClassname( name )
}

// used from the console to quick-test fields
void function setnpcfields( string key, var val )
{
	array<entity> npcs = GetNPCArrayByClass( "npc_soldier" )
	foreach ( npc in npcs )
	{
		npc.kv[ key ] = val
	}
}

void function WaitUntilNumDead( array<entity> guys, int numDead )
{
	Assert( numDead <= guys.len(), "asked for " + numDead + " guys to die, but only passed in an array of " + guys.len() + " guys." )
	float timeout = -1
	__WaitUntilDeadInternal( guys, numDead, timeout, __WaitUntilDeadTracker )
}

void function WaitUntilNumDeadWithTimeout( array<entity> guys, int numDead, float timeout )
{
	Assert( numDead <= guys.len(), "asked for " + numDead + " guys to die, but only passed in an array of " + guys.len() + " guys." )
	Assert( timeout > 0 )
	__WaitUntilDeadInternal( guys, numDead, timeout, __WaitUntilDeadTracker )
}

void function WaitUntilAllDead( array<entity> guys )
{
	int count = guys.len()
	float timeout = -1
	__WaitUntilDeadInternal( guys, count, timeout, __WaitUntilDeadTracker )
}

void function WaitUntilAllDeadWithTimeout( array<entity> guys, float timeout )
{
	int count = guys.len()
	Assert( timeout > 0 )
	__WaitUntilDeadInternal( guys, count, timeout, __WaitUntilDeadTracker )
}

void function WaitUntilNumDeadOrLeeched( array<entity> guys, int numDead )
{
	Assert( numDead <= guys.len(), "asked for " + numDead + " guys to die, but only passed in an array of " + guys.len() + " guys." )
	float timeout = -1
	__WaitUntilDeadInternal( guys, numDead, timeout, __WaitUntilDeadOrLeechedTracker )
}

void function WaitUntilNumDeadOrLeechedWithTimeout( array<entity> guys, int numDead, float timeout )
{
	Assert( numDead <= guys.len(), "asked for " + numDead + " guys to die, but only passed in an array of " + guys.len() + " guys." )
	Assert( timeout > 0 )
	__WaitUntilDeadInternal( guys, numDead, timeout, __WaitUntilDeadOrLeechedTracker )
}

void function WaitUntilAllDeadOrLeeched( array<entity> guys )
{
	int count = guys.len()
	float timeout = -1
	__WaitUntilDeadInternal( guys, count, timeout, __WaitUntilDeadOrLeechedTracker )
}

void function WaitUntilAllDeadOrLeechedWithTimeout( array<entity> guys, float timeout )
{
	int count = guys.len()
	Assert( timeout > 0 )
	__WaitUntilDeadInternal( guys, count, timeout, __WaitUntilDeadOrLeechedTracker )
}

void function __WaitUntilDeadInternal( array<entity> guys, int numDead, float timeout, void functionref( entity, table<string, int> ) deathTrackerFunc )
{
	table<string, int> master = { count = numDead }

	if ( timeout > 0.0 )
		thread __WaitUntilDeadTrackerDelayedSignal( master, "WaitDeadTimeOut", timeout )

	//when the thread ends, let child threads know
	OnThreadEnd(
		function() : ( master )
		{
			Signal( master, "OnDestroy" )
		}
	)

	foreach ( guy in guys )
		thread deathTrackerFunc( guy, master )

	while ( master.count > 0 )
	{
		table result = WaitSignal( master, "OnDeath", "WaitDeadTimeOut" )
		if ( result.signal == "WaitDeadTimeOut" ) //can't do endsignal, because it will kill the calling function too
			return
	}
}

void function __WaitUntilDeadTrackerDelayedSignal( table<string, int> master, string signal, float delay )
{
	EndSignal( master, signal )

	wait delay
	if ( IsValid( master ) )
		Signal( master, signal )
}

void function __WaitUntilDeadTracker( entity guy, table<string, int> master )
{
	EndSignal( master, "OnDestroy" )
	if ( IsAlive( guy ) )
		WaitSignal( guy, "OnDeath", "OnDestroy" )

	master.count--
	Signal( master, "OnDeath" )
}

void function __WaitUntilDeadOrLeechedTracker( entity guy, table<string, int> master )
{
	EndSignal( master, "OnDestroy" )
	if ( IsAlive( guy ) )
		WaitSignal( guy, "OnDeath", "OnDestroy", "OnLeeched" )

	master.count--
	Signal( master, "OnDeath" )
}

void function SetRebreatherMaskVisible( entity ent, bool visible )
{
	asset modelname = ent.GetModelName()

	int maskIdx = ent.FindBodyGroup( "mask" )
	if ( maskIdx == -1 )
		return

	int visibleIdx = 1
	if ( !visible )
		visibleIdx = 0

	ent.SetBodygroup( maskIdx, visibleIdx )
}

int function EntHasSpawnflag( entity ent, int spawnflagHexVal )
{
	return ( expect int( ent.kv.spawnflags ) & spawnflagHexVal )
}

entity function CreateInfoTarget( vector origin = <0,0,0>, vector angles = <0,0,0> )
{
	entity info_target = CreateEntity( "info_target" )
	info_target.SetOrigin( origin )
	info_target.SetAngles( angles )
	DispatchSpawn( info_target )
	return info_target
}

entity function CreateExpensiveScriptMover( vector origin = <0.0, 0.0, 0.0>, vector angles = <0.0, 0.0, 0.0>, int solidType = 0 )
{
	entity script_mover = CreateEntity( "script_mover" )
	script_mover.kv.solid = solidType
	script_mover.SetValueForModelKey( $"models/dev/empty_model.mdl" )
	script_mover.kv.SpawnAsPhysicsMover = 0
	script_mover.SetOrigin( origin )
	script_mover.SetAngles( angles )

	DispatchSpawn( script_mover )
	return script_mover
}

entity function CreateScriptMover( vector origin = <0.0, 0.0, 0.0>, vector angles = <0.0, 0.0, 0.0>, int solidType = 0 )
{
	entity script_mover = CreateEntity( "script_mover_lightweight" )
	script_mover.kv.solid = solidType
	script_mover.SetValueForModelKey( $"models/dev/empty_model.mdl" )
	script_mover.kv.SpawnAsPhysicsMover = 0
	script_mover.SetOrigin( origin )
	script_mover.SetAngles( angles )
	DispatchSpawn( script_mover )
	return script_mover
}

entity function CreateScriptMoverModel( asset model, vector origin = <0.0, 0.0, 0.0>, vector angles = <0.0, 0.0, 0.0>, int solidType = 0, float fadeDist = -1 )
{
	entity script_mover = CreateEntity( "script_mover_lightweight" )
	script_mover.kv.solid = solidType
	script_mover.kv.fadedist = fadeDist
	script_mover.SetValueForModelKey( model )
	script_mover.kv.SpawnAsPhysicsMover = 0
	script_mover.SetOrigin( origin )
	script_mover.SetAngles( angles )
	DispatchSpawn( script_mover )
	return script_mover
}

entity function CreateExpensiveScriptMoverModel( asset model, vector origin = <0.0, 0.0, 0.0>, vector angles = <0.0, 0.0, 0.0>, int solidType = 0, float fadeDist = -1 )
{
	entity script_mover = CreateEntity( "script_mover" )
	script_mover.kv.solid = solidType
	script_mover.kv.fadedist = fadeDist
	script_mover.SetValueForModelKey( model )
	script_mover.kv.SpawnAsPhysicsMover = 0
	script_mover.SetOrigin( origin )
	script_mover.SetAngles( angles )
	DispatchSpawn( script_mover )
	return script_mover
}

entity function CreateOwnedScriptMover( entity owner )
{
	entity script_mover = CreateEntity( "script_mover" )
	script_mover.kv.solid = 0
	script_mover.SetValueForModelKey( $"models/dev/empty_model.mdl" )
	script_mover.kv.SpawnAsPhysicsMover = 0
	script_mover.SetOrigin( owner.GetOrigin() )
	script_mover.SetAngles( owner.GetAngles() )
	DispatchSpawn( script_mover )
	script_mover.Hide()

	script_mover.SetOwner( owner )
	return script_mover
}

// useful for finding out what ents are in a level. Should only be used for debugging.
int function TotalEnts( bool hidden = false )
{
	array<entity> entities

	EntTracker++

	entity ent = Entities_FindInSphere( null, < 0, 0, 0 >, 90000 )
	string name
	for ( ;; )
	{
		if ( ent == null )
			break

		entities.append( ent )

		name = ent.GetTargetName()

		string strPrefix = "Old ent"
		if ( ent.e.totalEntsStoredID == 0 )
		{
			string strPrefix = "* New ent"
			ent.e.totalEntsStoredID = EntTracker
		}

		string strPostfix = ""
		if ( name != "" )
			strPostfix = " \"" + name + "\""

		if ( !hidden )
			printl( strPrefix + " (" + ent.e.totalEntsStoredID + "): " + ent + strPostfix )

		ent = Entities_FindInSphere( ent, < 0, 0, 0 >, 90000 )
	}

	if ( !hidden )
		printl( "Total entities " + entities.len() )

	return entities.len()
}

bool function IsThreadTop()
{
	return getstackinfos( 3 ) == null
}

string function ThisFunc()
{
	return expect string( expect table( getstackinfos( 2 ) )[ "func" ] )
}

entity function ge( int index ) // shorthand version for typing from console
{
	return GetEntByIndex( index )
}

entity function GetEnt( string name )
{
	entity ent = Entities_FindByName( null, name )
	if ( ent == null )
	{
		ent = Entities_FindByClassname( null, name )
		Assert( Entities_FindByClassname( ent, name ) == null, "Tried to GetEnt but there were multiple entities with that name" )
	}
	else
	{
		Assert( Entities_FindByName( ent, name ) == null, "Tried to GetEnt but there were multiple entities with name " + name )
	}

	return ent
}

array<entity> function ArrayWithinCenter( array<entity> ents, vector start, int range )
{
	array<entity> Array
	foreach ( ent in ents )
	{
		if ( Distance( start, ent.GetWorldSpaceCenter() ) > range )
			continue

		Array.append( ent )
	}

	return Array
}

vector function GetCenter( array<entity> ents )
{
	vector total

	foreach ( ent in ents )
	{
		total += ent.GetOrigin()
	}

	total.x /= float( ents.len() )
	total.y /= float( ents.len() )
	total.z /= float( ents.len() )

	return total
}

void function TableRemoveInvalid( table<entity, entity> Table )
{
	array<entity> deleteKey = []

	foreach ( entity key, entity value in Table )
	{
		if ( !IsValid_ThisFrame( key ) )
			deleteKey.append( key )

		if ( !IsValid_ThisFrame( value ) )
			deleteKey.append( key )
	}

	foreach ( key in deleteKey )
	{
		// in this search, two things could end up on the same key
		if ( key in Table )
			delete Table[ key ]
	}
}

void function TableRemoveInvalidByValue( table<entity, entity> Table )
{
	array<entity> deleteKey = []

	foreach ( key, entity value in Table )
	{
		if ( !IsValid_ThisFrame( value ) )
			deleteKey.append( key )
	}

	foreach ( key in deleteKey )
	{
		delete Table[ key ]
	}
}

void function TableRemoveDeadByKey( table<entity, entity> Table )
{
	array<entity> deleteKey = []

	foreach ( key, value in Table )
	{
		if ( !IsAlive( key ) )
			deleteKey.append( key )
	}

	foreach ( key in deleteKey )
	{
		delete Table[ key ]
	}
}


void function ArrayDump( array<var> Array )
{
	for ( int i = 0; i < Array.len(); i++ )
	{
		printl( "index " + i + " is: " + Array[i] )
	}
}


int function DotCompareLargest( ArrayDotResultStruct a, ArrayDotResultStruct b )
{
	if ( a.dot < b.dot )
		return 1
	else if ( a.dot > b.dot )
		return -1

	return 0
}

int function DotCompareSmallest( ArrayDotResultStruct a, ArrayDotResultStruct b )
{
	if ( a.dot > b.dot )
		return 1
	else if ( a.dot < b.dot )
		return -1

	return 0
}

array<ArrayDotResultStruct> function ArrayDotResults( array<entity> Array, entity ent )
{
	array<ArrayDotResultStruct> allResults

	foreach ( arrayEnt in Array )
	{
		ArrayDotResultStruct results

		results.dot = VectorDot_EntToEnt( ent, arrayEnt )
		results.ent = arrayEnt
		allResults.append( results )
	}

	return allResults
}


// Return an array of entities ordered from closest to furthest from the facing of the entity
array<entity> function ArrayClosestToView( array<entity> Array, entity ent )
{
	Assert( type( Array ) == "array" )
	array<ArrayDotResultStruct> allResults = ArrayDotResults( Array, ent )

	allResults.sort( DotCompareLargest )

	array<entity> returnEntities = []

	foreach ( index, result in allResults )
	{
		//printl( "Results are " + result.dot )
		returnEntities.insert( index, result.ent )
	}

	// the actual distances aren't returned
	return returnEntities
}


entity function SpawnRefEnt( entity ent )
{
	printl( "Ent model " + ent.GetValueForModelKey() )
	int attach = ent.LookupAttachment( "ref" )
	vector origin = ent.GetAttachmentOrigin( attach )
	vector angles = ent.GetAttachmentAngles( attach )

	entity ref = CreateEntity( "prop_dynamic" )
	//ref.kv.SpawnAsPhysicsMover = 0
	ref.SetValueForModelKey( $"models/dev/empty_model.mdl" )
	DispatchSpawn( ref )

	ref.SetOrigin( origin )
	ref.SetAngles( angles )
	ref.Hide()
	return ref
}

entity function CreateScriptRef( vector ornull origin = null, vector ornull angles = null )
{
	entity ent = CreateEntity( "script_ref" )

	if ( origin )
		ent.SetOrigin( expect vector( origin ) )

	if ( angles )
		ent.SetAngles( expect vector( angles ) )

	DispatchSpawn( ent )
	return ent
}

entity function CreateScriptRefMinimap( vector origin, vector angles )
{
	entity ent = CreateEntity( "script_ref_minimap" )

	ent.SetOrigin( origin )
	ent.SetAngles( angles )

	DispatchSpawn( ent )

	return ent
}

bool function exists( table tbl, string val )
{
	if ( !(val in tbl) )
		return false

	return tbl[ val ] != null
}

var function TableRandomIndex( table Table )
{
	array Array = []

	foreach ( index, _ in Table )
	{
		Array.append( index )
	}

	return Array.getrandom()
}

// should improve this
float function YawDifference( float yaw1, float yaw2 )
{
	Assert( yaw1 >= 0 )
	Assert( yaw1 <= 360 )
	Assert( yaw2 >= 0 )
	Assert( yaw2 <= 360 )

	float diff = fabs( yaw1 - yaw2 )

	if ( diff > 180 )
	    return 360 - diff
	else
	    return diff

	unreachable
}



/*function TrackIsTouching( ent )
{
	return // now uses IsTouching

	//ent.s.touching <- {}
	//ent.ConnectOutput( "OnStartTouch", TrackIsTouching_OnStartTouch )
	//ent.ConnectOutput( "OnEndTouch", TrackIsTouching_OnEndTouch )
}

void function TrackIsTouching_OnStartTouch( entity self, entity activator, entity caller, var value )
{
	if ( activator )
	{
		self.s.touching[ activator ] <- true
	}
}

void function TrackIsTouching_OnEndTouch( entity self, entity activator, entity caller, var value )
{
	if ( activator )
	{
		if ( activator in self.s.touching )
		{
			delete self.s.touching[ activator ]
		}
	}
}*/

void function NPC_NoTarget( entity self )
{
	self.SetNoTarget( true )
	self.SetNoTargetSmartAmmo( true )
}

vector function GetSimpleTraceEnd( vector start, vector end, float frac )
{
	vector vec = end - start
	vec *= frac
	return start + vec
}

bool function LoadedMain()
{
	if ( "LoadedMain" in level )
		return true

	level.LoadedMain <- true

	return false
}

void function Warning( string msg )
{
	printl( "*** WARNING ***" )
	printl( msg )
	DumpStack()
	printl( "*** WARNING ***" )
}

void function TimeOut( float time )
{
	table Table = {}
	EndSignal( Table, "OnDeath" )
	delaythread( time ) Signal( Table, "OnDeath" )
}

string function GetActiveWeaponClass( entity player )
{
	entity weapon = player.GetActiveWeapon()
	Assert( weapon != null )

	string weaponclass = weapon.GetWeaponClassName()
	return weaponclass
}

bool function HasWeapon( entity ent, string weaponClassName, array<string> mods = [] )
{
	Assert( ent.IsPlayer() || ent.IsNPC() )

	array<entity> weaponArray = ent.GetMainWeapons()
	foreach ( weapon in weaponArray )
	{
		if ( weapon.GetWeaponClassName() == weaponClassName )
		{
			if ( WeaponHasSameMods( weapon, mods ) )
				return true
		}
	}

	return false
}

bool function HasOrdnance( entity ent, string weaponClassName, array<string> mods = [] )
{
	return HasOffhandForSlot( ent, OFFHAND_ORDNANCE, weaponClassName, mods )
}

bool function HasCoreAbility( entity ent, string weaponClassName, array<string> mods = [] )
{
	return HasOffhandForSlot( ent, OFFHAND_EQUIPMENT, weaponClassName, mods )
}

bool function HasSpecial( entity ent, string weaponClassName, array<string> mods = [] )
{
	return HasOffhandForSlot( ent, OFFHAND_SPECIAL, weaponClassName, mods )
}

bool function HasAntiRodeo( entity ent, string weaponClassName, array<string> mods = [] )
{
	return HasOffhandForSlot( ent, OFFHAND_ANTIRODEO, weaponClassName, mods )
}

bool function HasMelee( entity ent, string weaponClassName, array<string> mods = [] )
{
	return HasOffhandForSlot( ent, OFFHAND_MELEE, weaponClassName, mods )
}

bool function HasOffhandForSlot( entity ent, int slot, string weaponClassName, array<string> mods = [] )
{
	Assert( ent.IsPlayer() || ent.IsNPC() )

	entity weapon = ent.GetOffhandWeapon( slot )
	if ( !IsValid( weapon ) )
		return false

	if ( weapon.GetWeaponClassName() != weaponClassName )
		return false

	return WeaponHasSameMods( weapon, mods )
}

bool function WeaponHasSameMods( entity weapon, array<string> mods = [] )
{
	array hasMods = clone mods
	foreach ( mod in weapon.GetMods() )
	{
		hasMods.removebyvalue( mod )
	}

	// has all the same mods.
	return hasMods.len() == 0
}

bool function HasOffhandWeapon( entity ent, string weaponClassName )
{
	Assert( ent.IsPlayer() || ent.IsNPC() )

	array<entity> weaponArray = ent.GetOffhandWeapons()
	foreach ( weapon in weaponArray )
	{
		if ( weapon.GetWeaponClassName() == weaponClassName )
			return true
	}

	return false
}

float function GetFraction( float value, float min, float max )
{
	return ( value - min ) / ( max - min )
}

float function GetFractionClamped( float value, float min, float max )
{
	float frac = GetFraction( value, min, max )
	return clamp( frac, 0.0, 1.0 )
}

float function GetValueFromFraction( float value, float value_min, float value_max, float return_min, float return_max )
{
	float frac = GetFractionClamped( value, value_min, value_max )
	float retVal = return_min + ( ( return_max - return_min ) * frac )
	return clamp( retVal, return_min, return_max )
}

bool function VectorCompare( vector vec1, vector vec2 )
{
	if ( vec1.x != vec2.x )
		return false

	if ( vec1.y != vec2.y )
		return false

	return vec1.z == vec2.z
}

// returns vectordot from viewEnt to targetEnt
float function VectorDot_EntToEnt( entity viewEnt, entity targetEnt )
{
	vector maxs = targetEnt.GetBoundingMaxs()
	vector mins = targetEnt.GetBoundingMins()
	maxs += mins
	maxs.x *= 0.5
	maxs.y *= 0.5
	maxs.z *= 0.5
	vector targetOrg = targetEnt.GetOrigin() + maxs

	maxs = viewEnt.GetBoundingMaxs()
	mins = viewEnt.GetBoundingMins()
	maxs += mins
	maxs.x *= 0.5
	maxs.y *= 0.5
	maxs.z *= 0.5
	vector viewOrg = viewEnt.GetOrigin() + maxs

	//DebugDrawLine( targetOrg, viewOrg, 255, 255, 255, true, 0.5 )
	vector vecToEnt = ( targetOrg - viewOrg )
	vecToEnt = Normalize( vecToEnt )

	float dotVal = DotProduct( vecToEnt, viewEnt.GetForwardVector() )
	return dotVal
}

void function PrecacheEffect( asset effectName )
{
	entity warningParticle = CreateEntity( "info_particle_system" )
	warningParticle.SetValueForEffectNameKey( effectName )
	warningParticle.kv.start_active = 0
	DispatchSpawn( warningParticle )
	warningParticle.Destroy()
}

void function PrecacheEntity( string entName, asset model = $"" )
{
	entity tempEnt = CreateEntity( entName )

	if ( model != $"" )
		tempEnt.SetValueForModelKey( model )

	tempEnt.kv.spawnflags = SF_NPC_ALLOW_SPAWN_SOLID

	DispatchSpawn( tempEnt )
	tempEnt.Destroy()
}

void function PrecacheProjectileEntity( string entName, string weaponClassName, asset model = $"" )
{
	entity tempEnt = Entities_CreateProjectileByClassname( entName, weaponClassName )

	if ( model != $"" )
		tempEnt.SetValueForModelKey( model )

	tempEnt.kv.spawnflags = SF_NPC_ALLOW_SPAWN_SOLID

	DispatchSpawn( tempEnt )
	tempEnt.Destroy()
}

void function PrecacheSprite( asset spriteName )
{
	entity sprite = CreateEntity( "env_sprite_oriented" )
	sprite.SetValueForModelKey( spriteName )
	sprite.kv.spawnflags = 1
	DispatchSpawn( sprite )
	sprite.Destroy()
}

entity function CreatePointMessage( string msg, vector origin, int displayRadius = 512 )
{
	entity point_message = CreateEntity( "point_message" )
	point_message.SetOrigin( origin )
	point_message.kv.message = msg
	point_message.kv.radius = displayRadius

	DispatchSpawn( point_message )

	return point_message
}

entity function CreateGameText( string msg, float xPos, float yPos, int channel, string color = "255 255 255", float fadein = 2, float fadeout = 0.5, float holdtime = 2 )
{
	entity game_text = CreateEntity( "game_text" )

	game_text.SetScriptName( "gt" + UniqueString()  )
	game_text.kv.message = msg
	game_text.kv["x"] = xPos
	game_text.kv["y"] = yPos
	game_text.kv.channel = channel
	game_text.kv.color = color
	game_text.kv.color2 = "240 110 0"  // doesn't appear to do anything atm, not supporting in params
	game_text.kv.fadein = fadein
	game_text.kv.fadeout = fadeout
	game_text.kv.holdtime = holdtime
	game_text.kv.fxtime = "0.25"

	DispatchSpawn( game_text )

	return game_text
}

// pass the origin where the player's feet would be
// tests a player sized box for any collision and returns true only if it's clear
bool function PlayerCanTeleportHere( entity player, vector testOrg, entity ignoreEnt = null ) //TODO: This is a copy of SP's PlayerPosInSolid(). Not changing it to avoid patching SP. Merge into one function next game
{
	int solidMask = TRACE_MASK_PLAYERSOLID
	vector mins
	vector maxs
	int collisionGroup = TRACE_COLLISION_GROUP_PLAYER
	array<entity> ignoreEnts = [ player ]

	if ( IsValid( ignoreEnt ) )
		ignoreEnts.append( ignoreEnt )
	TraceResults result

	mins = player.GetPlayerMins()
	maxs = player.GetPlayerMaxs()
	result = TraceHull( testOrg, testOrg + < 0, 0, 1 >, mins, maxs, ignoreEnts, solidMask, collisionGroup )

	if ( result.startSolid )
		return false

	return true
}


enum eAttach
{
	No
	ViewAndTeleport
	View
	Teleport
	ThirdPersonView
}


void function LoadDiamond()
{
    printl( " " )
    printl( " " )
    printl( " " )

    // Draw a diamond of a random size and phase (of the moon) so it is easy to separate sections of logs.
    int random_spread = RandomIntRange( 4, 7 )
    float random_fullness = RandomFloat( 2.0 )
    bool functionref( int, int ) compare_func
    string msg

    if ( RandomFloat( 1.0 ) > 0.5 )
    {
	    compare_func = bool function( int a, int b )
	    {
		    return a <= b
	    }
    }
    else
    {
	    compare_func = bool function( int a, int b )
	    {
		    return a >= b
	    }
    }

    for ( int i = 0; i <= random_spread - 2; i++ )
    {
	    msg = ""

	    for ( int p = 0; p <= random_spread - i; p++ )
	    {
		    msg = msg + " "
	    }

	    for ( int p = 0; p <= i * 2; p++ )
	    {
		    if ( p == i * 2 || p == 0 )
		    {
			    msg = msg + "*"
		    }
		    else
		    {
			    int an_int = int( i * random_fullness )

			    if ( compare_func( p, an_int ) )
				    msg = msg + "*"
			    else
				    msg = msg + " "
		    }
	    }

	    printl( msg )
    }

    for ( int i = random_spread - 1; i >= 0; i-- )
    {
	    msg = ""

	    for ( int p = 0; p <= random_spread - i; p++ )
	    {
		    msg = msg + " "
	    }


	    for ( int p = 0; p <= i * 2; p++ )
	    {
		    if ( p == i * 2 || p == 0 )
		    {
			    msg = msg + "*"
		    }
		    else
		    {
			    if ( compare_func( p, int( i * random_fullness ) ) )
			    {
				    msg = msg + "*"
			    }
			    else
			    {
				    msg = msg + " "
			    }
		    }
	    }

	    printl( msg )
    }

    printl( " " )
    printl( " " )
    printl( " " )
}

// this will clear all dropped weapons in the map
void function ClearDroppedWeapons( float delayTime = 0.0 )
{
	if ( delayTime > 0 )
		wait delayTime

	bool onlyNotOwnedWeapons = true  // don't get the ones in guys' hands
	array<entity> weapons = GetWeaponArray( onlyNotOwnedWeapons )

	foreach ( weapon in weapons )
	{
		// don't clean up weapon pickups that were placed in leveled
		int spawnflags = expect string( weapon.kv.spawnflags ).tointeger()
		if ( spawnflags & SF_WEAPON_START_CONSTRAINED )
			continue

		weapon.Destroy()
	}
}

void function ClearActiveProjectilesForTeam( int team, vector searchOrigin = <0,0,0>, float searchDist = -1 )
{
	array<entity> projectiles = GetProjectileArrayEx( "any", team, TEAM_ANY, searchOrigin, searchDist )

	printt( "cleaning up", projectiles.len(), "weapon projectiles for team", team )

	foreach ( proj in projectiles )
	{
		if( !IsValid( proj ) )
			continue

		proj.Destroy()
	}
}

void function RestockPlayerAmmo_Silent( entity player = null )
{
	RestockPlayerAmmo( player, true )
}

void function RestockPlayerAmmo( entity player = null, bool isSilent = false )
{
	array<entity> players
	if ( IsAlive( player ) )
		players.append( player )
	else
		players = GetPlayerArray_Alive()

	foreach( player in players )
	{
		player.RefillAllAmmo()

		if ( !isSilent )
			EmitSoundOnEntityOnlyToPlayer( player, player, "Coop_AmmoBox_AmmoRefill" )
	}
}

entity function CreateLightSprite( vector origin, vector angles, string lightcolor = "255 0 0", float scale = 0.5 )
{
	// attach a light so we can see it
	entity env_sprite = CreateEntity( "env_sprite" )
	env_sprite.SetScriptName( UniqueString( "molotov_sprite" ) )
	env_sprite.kv.rendermode = 5
	env_sprite.kv.origin = origin
	env_sprite.kv.angles = angles
	env_sprite.kv.rendercolor = lightcolor
	env_sprite.kv.renderamt = 255
	env_sprite.kv.framerate = "10.0"
	env_sprite.SetValueForModelKey( $"sprites/glow_05.vmt" )
	env_sprite.kv.scale = string( scale )
	env_sprite.kv.spawnflags = 1
	env_sprite.kv.GlowProxySize = 16.0
	env_sprite.kv.HDRColorScale = 1.0
	DispatchSpawn( env_sprite )
	EntFireByHandle( env_sprite, "ShowSprite", "", 0, null, null )

	return env_sprite
}

// defaultWinner: if it's a tie, return this value
int function GetCurrentWinner( int defaultWinner = TEAM_MILITIA )
{
	int imcScore
	int militiaScore

	if ( IsRoundBased() )
	{
		imcScore = GameRules_GetTeamScore2( TEAM_IMC )
		militiaScore = GameRules_GetTeamScore2( TEAM_MILITIA )

		if ( IsRoundBasedUsingTeamScore() && ( imcScore == militiaScore ) )
		{
			imcScore = GameRules_GetTeamScore( TEAM_IMC )
			militiaScore = GameRules_GetTeamScore( TEAM_MILITIA )
		}
	}
	else
	{
		imcScore = GameRules_GetTeamScore( TEAM_IMC )
		militiaScore = GameRules_GetTeamScore( TEAM_MILITIA )
	}

	int currentWinner = defaultWinner

	if ( militiaScore > imcScore )
		currentWinner = TEAM_MILITIA
	else if ( imcScore > militiaScore )
		currentWinner = TEAM_IMC

	return currentWinner
}

void function SetNpcFollowsPlayerOverride( entity player, void functionref( entity, entity ) override )
{
	player.p.followPlayerOverride = override
}

void function ClearNpcFollowsPlayerOverride( entity player )
{
	player.p.followPlayerOverride = null
}

void function AddCallback_GameStateEnter( int gameState, void functionref() callbackFunc )
{
	Assert( gameState < svGlobal.gameStateEnterCallbacks.len() )

	Assert( !svGlobal.gameStateEnterCallbacks[ gameState ].contains( callbackFunc ), "Already added " + string( callbackFunc ) + " with AddCallback_GameStateEnter" )

	svGlobal.gameStateEnterCallbacks[ gameState ].append( callbackFunc )
}

void function GM_SetObserverFunc( void functionref( entity ) callbackFunc )
{
	svGlobal.observerFunc = callbackFunc
}

void function GM_AddPlayingThinkFunc( void functionref() callbackFunc )
{
	Assert( !svGlobal.playingThinkFuncTable.contains( callbackFunc ), "Already added " + string( callbackFunc ) + " with GM_AddPlayingThinkFunc" )

	svGlobal.playingThinkFuncTable.append( callbackFunc )
}

void function GM_AddThirtySecondsLeftFunc( void functionref() callbackFunc )
{
	Assert( !svGlobal.thirtySecondsLeftFuncTable.contains( callbackFunc ), "Already added " + string( callbackFunc ) + " with GM_AddThirtySecondsLeftFunc" )

	svGlobal.thirtySecondsLeftFuncTable.append( callbackFunc )
}

void function GM_SetMatchProgressAnnounceFunc( void functionref( int ) callbackFunc )
{
	svGlobal.matchProgressAnnounceFunc = callbackFunc
}

// Get an absolute offset poistion to an entity even if it's been rotated in world space
vector function GetEntPosPlusOffset( entity ent, float offsetX, float offsetY, float offsetZ )
{
	vector entAngles = ent.GetAngles()
	vector entOrg = ent.GetOrigin()

	vector right = AnglesToRight( entAngles )
	right = Normalize( right )
	vector pos = entOrg + ( right * offsetY )

	vector forward = AnglesToForward( entAngles )
	forward = Normalize( forward )
	pos = pos + ( forward * offsetX )

	vector up = AnglesToUp( entAngles )
	up = Normalize( up )
	pos = pos + ( up * offsetZ )

	return pos
}

void function EmitSoundToTeamPlayers( string alias, int team )
{
	array<entity> players = GetPlayerArrayOfTeam( team )

	foreach ( player in players )
		EmitSoundOnEntityOnlyToPlayer( player, player, alias )
}

void function EmitDifferentSoundsAtPositionForPlayerAndWorld( string soundForPlayer, string soundForWorld, vector position, entity player, int teamNum )
{
	if ( IsValid( player ) && player.IsPlayer() )
	{
		EmitSoundAtPositionExceptToPlayer( teamNum, position, player, soundForWorld )
		EmitSoundAtPositionOnlyToPlayer( teamNum, position, player, soundForPlayer)
	}
	else
	{
		EmitSoundAtPosition( teamNum, position, soundForWorld )
	}
}

void function EmitDifferentSoundsOnEntityForPlayerAndWorld( string soundForPlayer, string soundForWorld, entity soundEnt, entity player )
{
	if ( IsValid( player ) && player.IsPlayer() )
	{
		EmitSoundOnEntityExceptToPlayerNotPredicted( soundEnt, player, soundForWorld )
		EmitSoundOnEntityOnlyToPlayer(soundEnt, player, soundForPlayer)
	}
	else
	{
		EmitSoundOnEntity( soundEnt, soundForWorld )
	}
}

// Drop an entity to the ground by tracing straight down from its z-axis
void function DropToGround( entity ent )
{
	vector targetOrigin = OriginToGround( ent.GetOrigin() + <0,0,1> )
	ent.SetOrigin( targetOrigin )
}

void function DropTitanToGround( entity titan, array<entity> ignoreEnts )
{
	vector endOrigin = titan.GetOrigin() - < 0, 0, 20000 >
	vector mins = GetBoundsMin( HULL_TITAN )
	vector maxs = GetBoundsMax( HULL_TITAN )
	TraceResults traceResult = TraceHull( titan.GetOrigin(), endOrigin, mins, maxs, ignoreEnts, TRACE_MASK_TITANSOLID, TRACE_COLLISION_GROUP_NONE )

	titan.SetOrigin( traceResult.endPos )
}

vector function OriginToGround( vector origin )
{
	vector endOrigin = origin - < 0, 0, 20000 >
	TraceResults traceResult = TraceLine( origin, endOrigin, [], TRACE_MASK_NPCWORLDSTATIC, TRACE_COLLISION_GROUP_NONE )

	return traceResult.endPos
}

float function GetVerticalClearance( vector origin )
{
	vector endOrigin = origin + < 0, 0, 20000 >
	TraceResults traceResult = TraceLine( origin, endOrigin, [], TRACE_MASK_NPCWORLDSTATIC, TRACE_COLLISION_GROUP_NONE )
	vector endPos = traceResult.endPos
	float zDelta = ( endPos.z - origin.z )

	return zDelta
}

// ---------------------------------------------------------------------
// Determine if an entity is a valid player spawnpoint
// ---------------------------------------------------------------------
bool function PlayerSpawnpointIsValid( entity ent )
{
	if ( ent.GetClassName() != "prop_dynamic" )
		return false
	if ( ent.GetValueForModelKey() != $"models/humans/pete/mri_male.mdl" )
		return false

	return true
}

// ---------------------------------------------------------------------
// Make an NPC or the player invincible (true/false)
//	(_npc.nut intercepts incoming damage and negates it if the ent is tagged as invincible)
// ---------------------------------------------------------------------
void function MakeInvincible( entity ent )
{
	Assert( IsValid( ent ), "Tried to make invalid " + ent + " invincible" )
	Assert( ent.IsNPC() || ent.IsPlayer(), "MakeInvincible() can only be called on NPCs and the player" )
	Assert( IsAlive( ent ), "Tried to make dead ent " + ent + " invincible" )

	ent.SetInvulnerable()
}

void function ClearInvincible( entity ent )
{
	Assert( IsValid( ent ), "Tried to clear invalid " + ent + " invincible" )

	ent.ClearInvulnerable()
}

bool function IsInvincible( entity ent )
{
	return ent.IsInvulnerable()
}

//-------------------------------------
// Teleport an entity (teleporter) to an entity's org and angles (ent)
//--------------------------------------
void function TeleportToEnt( entity teleporter, entity ent )
{
	Assert( teleporter != null, "Unable to teleport null entity" )
	Assert( ent != null, "Unable to teleport to a null entity" )
	teleporter.SetOrigin( ent.GetOrigin() )
	teleporter.SetAngles( ent.GetAngles() )
}

//-----------------------------------------------------------
// CreateShake() - create and fire an env_shake at a specified origin
// - returns the shake in case you want to parent it
//------------------------------------------------------------

entity function CreateShake_internal( vector org, float amplitude, float frequency, float duration, float radius, int spawnFlags )
{
	entity env_shake = CreateEntity( "env_shake" )
	env_shake.kv.amplitude = amplitude
	env_shake.kv.radius = radius
	env_shake.kv.duration = duration
	env_shake.kv.frequency = frequency
	env_shake.kv.spawnflags = spawnFlags

	DispatchSpawn( env_shake )

	env_shake.SetOrigin( org )

	EntFireByHandle( env_shake, "StartShake", "", 0, null, null )
	EntFireByHandle( env_shake, "Kill", "", ( duration + 1 ), null, null )

	return env_shake
}

entity function CreateShake( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, 0 );
}

entity function CreateShakeRumbleOnly( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, SF_SHAKE_RUMBLE_ONLY );
}

entity function CreateShakeNoRumble( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, SF_SHAKE_NO_RUMBLE );
}

entity function CreateAirShake( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, SF_SHAKE_INAIR );
}

entity function CreateAirShakeRumbleOnly( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, (SF_SHAKE_INAIR | SF_SHAKE_RUMBLE_ONLY) );
}

entity function CreateAirShakeNoRumble( vector org, float amplitude = 16, float frequency = 150, float duration = 1.5, float radius = 2048 )
{
	return CreateShake_internal( org, amplitude, frequency, duration, radius, (SF_SHAKE_INAIR | SF_SHAKE_NO_RUMBLE) );
}

//-------------------------------------
// CreatePhysExplosion - physExplosion...small, medium or large
//--------------------------------------
entity function CreatePhysExplosion( vector org, float radius, int magnitude = 1, int flags = 1, bool dealsDamage = true )
{
	entity env_physexplosion = CreateEntity( "env_physexplosion" )
	env_physexplosion.kv.spawnflags = flags // default 1 = No Damage - Only Force
	env_physexplosion.kv.magnitude = magnitude
	env_physexplosion.kv.radius = string( radius )
	env_physexplosion.SetOrigin( org )
	env_physexplosion.kv.scriptDamageType = damageTypes.explosive
	DispatchSpawn( env_physexplosion )

	EntFireByHandle( env_physexplosion, "Explode", "", 0, null, null )
	EntFireByHandle( env_physexplosion, "Kill", "", 2, null, null )
}

//-----------------------------------------------------------
// CreatePropDynamic( model ) - create a generic prop_dynamic with default properties
//------------------------------------------------------------
entity function CreatePropDynamic( asset model, vector ornull origin = null, vector ornull angles = null, var solidType = 0, float fadeDist = -1 )
{
	entity prop_dynamic = CreateEntity( "prop_dynamic" )
	prop_dynamic.SetValueForModelKey( model )
	prop_dynamic.kv.fadedist = fadeDist
	prop_dynamic.kv.renderamt = 255
	prop_dynamic.kv.rendercolor = "255 255 255"
	prop_dynamic.kv.solid = solidType // 0 = no collision, 2 = bounding box, 6 = use vPhysics, 8 = hitboxes only
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen before DispatchSpawn, otherwise the prop may not touch triggers
		prop_dynamic.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_dynamic.SetAngles( expect vector( angles ) )
	}
	DispatchSpawn( prop_dynamic )
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen after DispatchSpawn, otherwise origin is snapped to nearest whole unit
		prop_dynamic.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_dynamic.SetAngles( expect vector( angles ) )
	}

	return prop_dynamic
}


//-----------------------------------------------------------
// CreatePropDynamicLightweight( model ) - create a generic prop_dynamic_lightweight with default properties
//------------------------------------------------------------
entity function CreatePropDynamicLightweight( asset model, vector ornull origin = null, vector ornull angles = null, var solidType = 0, float fadeDist = -1 )
{
	entity prop_dynamic = CreateEntity( "prop_dynamic_lightweight" )
	prop_dynamic.SetValueForModelKey( model )
	prop_dynamic.kv.fadedist = fadeDist
	prop_dynamic.kv.renderamt = 255
	prop_dynamic.kv.rendercolor = "255 255 255"
	prop_dynamic.kv.solid = solidType // 0 = no collision, 2 = bounding box, 6 = use vPhysics, 8 = hitboxes only
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen before DispatchSpawn, otherwise the prop may not touch triggers
		prop_dynamic.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_dynamic.SetAngles( expect vector( angles ) )
	}
	DispatchSpawn( prop_dynamic )
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen after DispatchSpawn, otherwise origin is snapped to nearest whole unit
		prop_dynamic.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_dynamic.SetAngles( expect vector( angles ) )
	}

	return prop_dynamic
}


//-----------------------------------------------------------
// CreatePropScript( model ) - create a generic prop_script with default properties
//------------------------------------------------------------
entity function CreatePropScript( asset model, vector ornull origin = null, vector ornull angles = null, int solidType = 0, float fadeDist = -1 )
{
	entity prop_script = CreateEntity( "prop_script" )
	prop_script.SetValueForModelKey( model )
	prop_script.kv.fadedist = fadeDist
	prop_script.kv.renderamt = 255
	prop_script.kv.rendercolor = "255 255 255"
	prop_script.kv.solid = solidType // 0 = no collision, 2 = bounding box, 6 = use vPhysics, 8 = hitboxes only
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen before DispatchSpawn, otherwise the prop may not touch triggers
		prop_script.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_script.SetAngles( expect vector( angles ) )
	}
	DispatchSpawn( prop_script )
	if ( origin )
	{
		// hack: Setting origin twice. SetOrigin needs to happen after DispatchSpawn, otherwise origin is snapped to nearest whole unit
		prop_script.SetOrigin( expect vector( origin ) )
		if ( angles )
			prop_script.SetAngles( expect vector( angles ) )
	}

	return prop_script
}



//-----------------------------------------------------------
// CreatePropPhysics( model ) - create a generic prop_physics with default properties
//------------------------------------------------------------
entity function CreatePropPhysics( asset model, vector origin, vector angles )
{
	entity prop_physics = CreateEntity( "prop_physics" )
	prop_physics.SetValueForModelKey( model )
	prop_physics.kv.spawnflags = 0
	prop_physics.kv.fadedist = -1
	prop_physics.kv.physdamagescale = 0.1
	prop_physics.kv.inertiaScale = 1.0
	prop_physics.kv.renderamt = 255
	prop_physics.kv.rendercolor = "255 255 255"
	SetTeam( prop_physics, TEAM_BOTH )	// need to have a team other then 0 or it won't take impact damage

	prop_physics.SetOrigin( origin )
	prop_physics.SetAngles( angles )
	DispatchSpawn( prop_physics )

	return prop_physics
}

//-----------------------------------------------------------
// SpawnBullseye() - creates a npc_bullseye and attaches it to an entity
//------------------------------------------------------------
entity function SpawnBullseye( int team, entity ent = null )
{
	entity bullseye = CreateEntity( "npc_bullseye" )
	bullseye.SetScriptName( UniqueString( "bullseye" ) )
	bullseye.kv.rendercolor = "255 255 255"
	bullseye.kv.renderamt = 0
	bullseye.kv.health = 9999
	bullseye.kv.max_health = -1
	bullseye.kv.spawnflags = 516
	bullseye.kv.FieldOfView = 0.5
	bullseye.kv.FieldOfViewAlert = 0.2
	bullseye.kv.AccuracyMultiplier = 1.0
	bullseye.kv.physdamagescale = 1.0
	bullseye.kv.WeaponProficiency = eWeaponProficiency.VERYGOOD
	bullseye.kv.minangle = "360"
	DispatchSpawn( bullseye )

	SetTeam( bullseye, team )

	if ( ent )
	{
		vector bounds = ent.GetBoundingMaxs()
		bullseye.SetOrigin( ent.GetOrigin() + < 0, 0, bounds.z * 0.5 > )
		bullseye.SetParent( ent )
	}

	return bullseye
}

void function CenterPrint( ... )
{
	string msg = ""
	for ( int i = 0; i < vargc; i++ )
		msg = ( msg + " " + string( vargv[ i ] ) )

	int words = expect int( vargc )
	if ( words < 1 )
		words = 1

	float delay = GraphCapped( float( words ), 2.0, 8.0, 2.1, 3.5 )

	entity ent = CreateGameText( msg, -1, 0.5, 10, "255 255 255", 0.25, 0.25, delay )
	EntFireByHandle( ent, "Display", "", 0, null, null )

	thread DestroyCenterPrint( ent, delay )
}

void function DestroyCenterPrint( entity ent, float delay )
{
	wait( delay )
	ent.Destroy()
}

bool function IsValidPlayer( entity player )
{
	if ( !IsValid( player ) )
		return false

	if ( !player.IsPlayer() )
		return false

	if ( IsDisconnected( player ) )
		return false

	return true
}

bool function IsDisconnected( entity player )
{
	return player.p.isDisconnected
}

/****************************************************************************************************\
/*
|*											PLAY FX
\*
\****************************************************************************************************/

entity function PlayFX( asset effectName, vector org, vector ornull optionalAng = null, vector ornull overrideAngle = null )
{
	return __CreateFxInternal( effectName, null, "", org, optionalAng, C_PLAYFX_SINGLE, null, -1, null, overrideAngle )
}

entity function PlayFXWithControlPoint( asset effectName, vector org, entity cpoint1, int visibilityFlagOverride = -1, entity visibilityFlagEntOverride = null, vector ornull overrideAngle = null, int _type = C_PLAYFX_SINGLE )
{
	return __CreateFxInternal( effectName, null, "", org, null, _type, cpoint1, visibilityFlagOverride, visibilityFlagEntOverride, overrideAngle)
}

entity function PlayFXOnEntityWithControlPoint( asset effectName, entity ent, entity cpoint1, int visibilityFlagOverride = -1, entity visibilityFlagEntOverride = null, vector ornull overrideAngle = null, int _type = C_PLAYFX_SINGLE )
{
	return __CreateFxInternal( effectName, ent, "", null, null, _type, cpoint1, visibilityFlagOverride, visibilityFlagEntOverride, overrideAngle)
}

entity function PlayFXOnEntity( asset effectName, entity ent, string optionalTag = "", vector ornull optionalTranslation = null, vector ornull optionalRotation = null, int visibilityFlagOverride = -1, entity visibilityFlagEntOverride = null, vector ornull overrideAngle = null )
{
	return __CreateFxInternal( effectName, ent, optionalTag, optionalTranslation, optionalRotation, C_PLAYFX_SINGLE, null,  visibilityFlagOverride, visibilityFlagEntOverride, overrideAngle )
}

entity function PlayFXForPlayer( asset effectName, entity player, vector ornull org, vector ornull optionalAng = null )
{
	return __CreateFxInternal( effectName, null, "", org, optionalAng, C_PLAYFX_SINGLE, null, ENTITY_VISIBLE_TO_OWNER, player )
}

entity function PlayFXOnEntityForEveryoneExceptPlayer( asset effectName, entity ent, entity player, string optionalTag = "", vector ornull optionalTranslation = null, vector ornull optionalRotation = null )
{
	return __CreateFxInternal( effectName, ent, optionalTag, optionalTranslation, optionalRotation, C_PLAYFX_SINGLE, null, (ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY), player )
}

entity function PlayFXForEveryoneExceptPlayer( asset effectName, entity player, vector ornull org, vector ornull optionalAng = null )
{
	return __CreateFxInternal( effectName, null, "", org, optionalAng, C_PLAYFX_SINGLE, null, (ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY), player )
}

void function PlayFXOnTitanPlayerForTime( asset effectName, entity titan, string attachment, float duration )
{
	titan.EndSignal( "OnDeath" )
	titan.EndSignal( "DisembarkingTitan" )
	titan.EndSignal( "TitanEjectionStarted" )

	entity fx = PlayFXOnEntityForEveryoneExceptPlayer( effectName, titan, titan, attachment )

	OnThreadEnd(
	function() : ( fx )
		{
			if ( IsValid(fx) )
			{
				fx.Destroy()
			}
		}
	)

	wait duration
}

entity function ClientStylePlayFXOnEntity( asset effectName, entity ent, string tag, float duration = 2.0 )
{
	string name = ent.GetScriptName()
	ent.SetScriptName( UniqueString() ) // hack because you can only specify control points by name
	// hack this is also not quite right because we can't specify the attachment type on the server... should be trivial to add in code:
	// change DEFINE_FIELD( m_parentAttachmentType, FIELD_INTEGER ), to DEFINE_KEYFIELD( m_parentAttachmentType, FIELD_INTEGER, "attachmentType" ),
	entity result = __CreateFxInternal( effectName, ent, tag, null, null, C_PLAYFX_SINGLE, ent, (ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY), ent )
	EntFireByHandle( result, "Kill", "", duration, null, null )
	ent.SetScriptName( name )

	return result
}

entity function PlayLoopFX( asset effectName, vector ornull org, vector ornull optionalAng = null )
{
	return __CreateFxInternal( effectName, null, "", org, optionalAng, C_PLAYFX_LOOP )
}

entity function PlayLoopFXOnEntity( asset effectName, entity ent, string optionalTag = "", vector ornull optionalTranslation = null, vector ornull optionalRotation = null, int visibilityFlagOverride = -1, entity visibilityFlagEntOverride = null )
{
	return __CreateFxInternal( effectName, ent, optionalTag, optionalTranslation, optionalRotation, C_PLAYFX_LOOP, null, visibilityFlagOverride, visibilityFlagEntOverride )
}

entity function __CreateFxInternal( asset effectName, entity ent, string optionalTag = "", vector ornull optionalTranslation = <0,0,0>, vector ornull optionalRotation = <0,0,0>,
									int _type = C_PLAYFX_SINGLE, entity cpointEnt1 = null, int visibilityFlagOverride = -1, entity visibilityFlagEntOverride = null, vector ornull overrideAngle = null )
{
	entity fx = CreateEntity( "info_particle_system" )
	fx.SetValueForEffectNameKey( effectName )
	if( visibilityFlagOverride != -1 )
		fx.kv.VisibilityFlags = visibilityFlagOverride
	else
		fx.kv.VisibilityFlags = ENTITY_VISIBLE_TO_EVERYONE
	fx.kv.start_active = 1
	fx.e.fxType = _type

	if ( _type == C_PLAYFX_SINGLE )
		fx.DoNotCreateFXOnRestore();

	vector coreOrg
	vector coreAng

	//are we attaching to an ent?
	if ( ent )
	{
		//are we attaching to a tag on an ent
		if ( optionalTag != "" )
		{
			int attachID = ent.LookupAttachment( optionalTag )
			coreOrg = ent.GetAttachmentOrigin( attachID )
			coreAng = ent.GetAttachmentAngles( attachID )
		}
		else
		{
			coreOrg = ent.GetOrigin()
			coreAng = ent.GetAngles()
		}

		fx.Code_SetTeam( ent.GetTeam() );
	}
	else //if not we're just playing in space
	{
		optionalTag = ""
		coreOrg = < 0, 0, 0 >
		coreAng = < 0, 0, 0 >
	}

	if ( optionalTranslation )
	{
		expect vector( optionalTranslation )
		if ( ent )
			coreOrg = PositionOffsetFromEnt( ent, optionalTranslation.x, optionalTranslation.y, optionalTranslation.z )
		else
			coreOrg = coreOrg + optionalTranslation
	}

	coreOrg = ClampToWorldspace( coreOrg )
	fx.SetOrigin( coreOrg )

	if ( overrideAngle )
	{
		expect vector( overrideAngle )
		fx.SetAngles( overrideAngle )
	}
	else if ( optionalRotation )
	{
		expect vector( optionalRotation )
		fx.SetAngles( coreAng + optionalRotation )
	}
	else
	{
		fx.SetAngles( coreAng )
	}

	if ( ent )
	{
		if ( !ent.IsMarkedForDeletion() ) // TODO: This is a hack for shipping. The real solution is to spawn the FX before deleting the parent entity.
		{
			fx.SetParent( ent, optionalTag, true )
		}
	}

	if ( visibilityFlagEntOverride != null )
		fx.SetOwner( visibilityFlagEntOverride )

	if ( cpointEnt1 )
		fx.kv.cpoint1 = cpointEnt1.GetTargetName()

	DispatchSpawn( fx )
	thread __DeleteFxInternal( fx )

	//SetTargetName( fx, "FX_" + effectName )
	return fx
}

void function __DeleteFxInternal( entity fx )
{
	//if it loops or is multiple then don't delete internally
	if ( fx.e.fxType == C_PLAYFX_MULTIPLE )
		return

	if ( fx.e.fxType == C_PLAYFX_LOOP )
		return

	wait 30 //no way to know when an effect is over
	if ( !IsValid( fx ) )
		return

	fx.ClearParent()
	fx.Destroy()
}

void function StartFX( entity fx )
{
	Assert( fx.e.fxType == C_PLAYFX_LOOP, "Tried to use StartFX() on effect that is not LOOPING" )
	EntFireByHandle( fx, "Start", "", 0, null, null )
}

void function StopFX( entity fx )
{
	Assert( fx.e.fxType == C_PLAYFX_LOOP, "Tried to use StopFX() on effect that is not LOOPING" )
	EntFireByHandle( fx, "Stop", "", 0, null, null )
}

void function ReplayFX( entity fx )
{
	Assert( fx.e.fxType == C_PLAYFX_MULTIPLE, "Tried to use ReplayFX() on effect that is not MULTIPLE" )
	//thread it because there is a WaitFrame() inside the function
	thread __ReplayFXInternal( fx )
}

void function __ReplayFXInternal( entity fx )
{
	//for non-looping fx, we must stop first before we can fire again
	EntFireByHandle( fx, "Stop", "", 0, null, null )
	//we can't start in the same frame, WaitFrame() skips 1 false
	//it should be noted that "WaitFrame()" doesn't work with a timescale above 1
	WaitFrame()
	//may have died since the last frame
	if ( IsValid( fx ) )
		EntFireByHandle( fx, "Start", "", 0, null, null )
}

void function Entity_StopFXArray( entity ent )
{
	foreach( fx in ent.e.fxArray )
	{
		if ( IsValid( fx ) )
		{
			StopFX( fx )
			fx.Destroy()
		}
	}
}

/****************************************************************************************************\
|*											end play fx
\****************************************************************************************************/


table function GetDamageTableFromInfo( var damageInfo )
{
	table Table = {}
	Table.damageSourceId <- DamageInfo_GetDamageSourceIdentifier( damageInfo )
	Table.origin <- DamageInfo_GetDamagePosition( damageInfo )
	Table.force <- DamageInfo_GetDamageForce( damageInfo )
	Table.scriptType <- DamageInfo_GetCustomDamageType( damageInfo )

	return Table
}

bool function EntityInSolid( entity ent, entity ignoreEnt = null, int buffer = 0 ) //TODO:  This function returns true for a player standing inside a friendly grunt. It also returns true if you are right up against a ceiling.Needs fixing for next game
{
	Assert( IsValid( ent ) )
	int solidMask
	vector mins
	vector maxs
	int collisionGroup
	array<entity> ignoreEnts = []

	ignoreEnts.append( ent )

	if ( IsValid( ignoreEnt ) )
	{
		ignoreEnts.append( ignoreEnt )
	}

	if ( ent.IsTitan() )
		solidMask = TRACE_MASK_TITANSOLID
	else if ( ent.IsPlayer() )
		solidMask = TRACE_MASK_PLAYERSOLID
	else
		solidMask = TRACE_MASK_NPCSOLID

	if ( ent.IsPlayer() )
	{
		mins = ent.GetPlayerMins()
		maxs = ent.GetPlayerMaxs()
		collisionGroup = TRACE_COLLISION_GROUP_PLAYER
	}
	else
	{
		Assert( ent.IsNPC() )
		mins = ent.GetBoundingMins()
		maxs = ent.GetBoundingMaxs()
		collisionGroup = TRACE_COLLISION_GROUP_NONE
	}

	if ( buffer > 0 )
	{
		mins.x -= float( buffer )
		mins.y -= float( buffer )
		maxs.x += float( buffer )
		maxs.y += float( buffer )
	}

	// if we got into solid, teleport back to safe place
	vector currentOrigin = ent.GetOrigin()
	TraceResults result = TraceHull( currentOrigin, currentOrigin + < 0, 0, 1 >, mins, maxs, ignoreEnts, solidMask, collisionGroup )
	//PrintTable( result )
	//DrawArrow( result.endPos, Vector(0,0,0), 5, 150 )
	if ( result.startSolid )
		return true

	return result.fraction < 1.0 // TODO: Probably not needed according to Jiesang. Fix after ship.
}

bool function EntityInSpecifiedEnt( entity ent, entity specifiedEnt, int buffer = 0 )
{
	Assert( IsValid( ent ) )
	Assert( IsValid( specifiedEnt ) )

	int solidMask
	vector mins
	vector maxs
	int collisionGroup

	if ( ent.IsTitan() )
		solidMask = TRACE_MASK_TITANSOLID
	else if ( ent.IsPlayer() )
		solidMask = TRACE_MASK_PLAYERSOLID
	else
		solidMask = TRACE_MASK_NPCSOLID

	if ( ent.IsPlayer() )
	{
		mins = ent.GetPlayerMins()
		maxs = ent.GetPlayerMaxs()
		collisionGroup = TRACE_COLLISION_GROUP_PLAYER
	}
	else
	{
		Assert( ent.IsNPC() )
		mins = ent.GetBoundingMins()
		maxs = ent.GetBoundingMaxs()
		collisionGroup = TRACE_COLLISION_GROUP_NONE
	}

	if ( buffer > 0 )
	{
		mins.x -= float( buffer )
		mins.y -= float( buffer )
		maxs.x += float( buffer )
		maxs.y += float( buffer )
	}

	// if we got into solid, teleport back to safe place
	vector currentOrigin = ent.GetOrigin()
	TraceResults result = TraceHull( currentOrigin, currentOrigin + < 0, 0, 1 >, mins, maxs, null, solidMask, collisionGroup )
	//PrintTable( result )
	//DrawArrow( result.endPos, Vector(0,0,0), 5, 150 )
	if ( result.startSolid == false )
		return false

	return result.hitEnt == specifiedEnt
}

void function KillFromInfo( entity ent, var damageInfo )
{
	entity attacker = DamageInfo_GetAttacker( damageInfo )
	entity weapon = DamageInfo_GetWeapon( damageInfo )
	//float amount = DamageInfo_GetDamage( damageInfo )

	// JFS: if the player became invalid, the attacker becomes the projectile which is bad
	if ( attacker.IsProjectile() )
		attacker = svGlobal.worldspawn

	if ( !weapon )
		weapon = attacker

	table Table = GetDamageTableFromInfo( damageInfo )
	Table.forceKill <- true

	ent.TakeDamage( 9999, attacker, weapon, Table )
}


entity function GetPlayerTitanInMap( entity player )
{
	// temporarily flipped
	entity petTitan = player.GetPetTitan()
	if ( IsValid( petTitan ) && IsAlive( petTitan ) )
		return petTitan

	// first try to return the player's actual titan
	if ( player.IsTitan() )
		return player

	return null
}


entity function GetPlayerTitanFromSouls( entity player )
{
	// returns the first owned titan found
	array<entity> souls = GetTitanSoulArray()
	foreach ( soul in souls )
	{
		if ( !IsValid( soul ) )
			continue

		if ( soul.GetBossPlayer() != player )
			continue

		if ( !IsAlive( soul.GetTitan() ) )
			continue

		return soul.GetTitan()
	}

	return null
}

void function DisableTitanShield( entity titan )
{
	entity soul = titan.GetTitanSoul()

	soul.SetShieldHealth( 0 )
	soul.SetShieldHealthMax( 0 )
}

void function DisableShield( entity ent )
{
	entity soul = ent.GetTitanSoul()

	if ( soul )
	{
		DisableTitanShield( ent )
		return
	}

	ent.SetShieldHealth( 0 )
	ent.SetShieldHealthMax( 0 )
}

void function SetVelocityTowardsEntity( entity entToMove, entity targetEnt, float speed )
{
	Assert( speed > 0 )
	Assert( IsValid( entToMove ) )
	Assert( IsValid( targetEnt ) )

	vector direction = ( targetEnt.GetWorldSpaceCenter() - entToMove.GetOrigin() )
	direction = Normalize( direction ) * speed
	entToMove.SetVelocity( direction )
}

void function SetVelocityTowardsEntityTag( entity entToMove, entity targetEnt, string targetTag, float speed )
{
	Assert( speed > 0 )
	Assert( IsValid( entToMove ) )
	Assert( IsValid( targetEnt ) )

	int attachID = targetEnt.LookupAttachment( targetTag )
	vector attachOrigin = targetEnt.GetAttachmentOrigin( attachID )

	vector direction = ( attachOrigin - entToMove.GetOrigin() )
	direction = Normalize( direction ) * speed
	entToMove.SetVelocity( direction )
}

void function EntityDemigod_TryAdjustDamageInfo( entity ent, var damageInfo )
{
	float dmg = DamageInfo_GetDamage( damageInfo )
	if ( dmg <= 0 )
		return

	if ( ent.IsTitan() && !GetDoomedState( ent ) ) //Allow demigod titans to go into doomed
		return

	int bottomLimit = 5
	// Set it up so that you at least take 1 damage, for hit indicators etc to trigger
	if ( ent.GetHealth() <= bottomLimit )
	{
		// Prevent going over max health to avoid a server crash.
		int newHealth = bottomLimit + 1
		ent.SetHealth( ent.GetMaxHealth() < newHealth ? ent.GetMaxHealth() : newHealth )
	}

	int health = ent.GetHealth()

	if ( health - dmg <= bottomLimit )
	{
		int newdmg = health - bottomLimit
		DamageInfo_SetDamage( damageInfo, newdmg )
		//printt( "setting damage to ", newdmg )
	}
}

void function DebugDamageInfo( entity ent, var damageInfo )
{
	printt( "damage to " + ent + ": " + DamageInfo_GetDamage( damageInfo ) )
	int damageType = DamageInfo_GetCustomDamageType( damageInfo )
	printt( "explosive: " + ( damageType & DF_EXPLOSION ) )
	printt( "bullet: " + ( damageType & DF_BULLET ) )
	printt( "gib: " + ( damageType & DF_GIB ) )

	vector dampos = DamageInfo_GetDamagePosition( damageInfo )
	vector org = DamageInfo_GetInflictor( damageInfo ).GetOrigin()
	DebugDrawLine( dampos, org, 255, 0, 0, true, 10.0 )
	DebugDrawLine( org, ent.GetOrigin(), 255, 255, 0, true, 10.0 )
}

vector function RandomVecInDome( vector dir )
{
	vector angles = VectorToAngles( dir )
	vector forward = AnglesToForward( angles )
	vector right = AnglesToRight( angles )
	vector up = AnglesToUp( angles )

	float offsetRight = RandomFloatRange( -1, 1 )
	float offsetUp = RandomFloatRange( -1, 1 )
	float offsetForward = RandomFloat( 1.0 )

	vector endPos = < 0, 0, 0 >
	endPos += forward * offsetForward
	endPos += up * offsetUp
	endPos += right * offsetRight
	endPos.Norm()

	return endPos
}

float function GetAnimEventTime( asset modelname, string anim, string event )
{
	entity dummy = CreatePropDynamic( modelname )
	dummy.Hide()

	float duration 	= dummy.GetSequenceDuration( anim )
	float frac 		= dummy.GetScriptedAnimEventCycleFrac( anim, event )

	dummy.Destroy()

	//this might cause some issues in R2 - but we'll fix them as we go - it's important this doesn't silently fail
	Assert( frac > 0.0, "event: " + event + " doesn't exist in animation: " + anim )
	Assert( frac < 1.0, "event: " + event + " doesn't exist in animation: " + anim )

	return duration * frac
}

void function SetDeathFuncName( entity npc, string functionNameString )
{
	Assert( npc.kv.deathScriptFuncName == "", "deathScriptFuncName was already set" )
	npc.kv.deathScriptFuncName = functionNameString
}

void function ClearDeathFuncName( entity npc )
{
	npc.kv.deathScriptFuncName = ""
}

/*function PushSunLightAngles( x, y, z )
{
	entity clight = GetEnt( "env_cascade_light" )
	Assert( clight )

	clight.PushAngles( x, y, z )
}

function PopSunLightAngles()
{
	entity clight = GetEnt( "env_cascade_light" )
	Assert( clight )

	clight.PopAngles()
}*/

entity function GetPilotAntiPersonnelWeapon( entity player )
{
	array<entity> weaponsArray = player.GetMainWeapons()
	foreach( weapon in weaponsArray )
	{
			int weaponType = weapon.GetWeaponType()
			if ( weaponType == WT_SIDEARM || weaponType == WT_ANTITITAN )
				continue;

			return weapon
	}

	return null
}

entity function GetPilotSideArmWeapon( entity player )
{
	array<entity> weaponsArray = player.GetMainWeapons()
	foreach( weapon in weaponsArray )
	{
		if ( weapon.GetWeaponType() == WT_SIDEARM )
			return weapon
	}

	return null
}

entity function GetPilotAntiTitanWeapon( entity player )
{
	array<entity> weaponsArray = player.GetMainWeapons()
	foreach( weapon in weaponsArray )
	{
		if ( weapon.GetWeaponType() == WT_ANTITITAN )
			return weapon
	}

	return null
}

bool function PilotHasSniperWeapon( entity player )
{
	array<entity> weaponsArray = player.GetMainWeapons()
	foreach ( weapon in weaponsArray )
	{
		if ( IsValid( weapon ) && weapon.GetWeaponInfoFileKeyField( "is_sniper" ) == 1 )
			return true
	}

	return false
}

bool function PilotActiveWeaponIsSniper( entity player )
{
	entity weapon = player.GetActiveWeapon()

	if ( IsValid( weapon ) && weapon.GetWeaponInfoFileKeyField( "is_sniper" ) == 1 )
		return true

	return false
}

void function ScreenFadeToColor( entity player, float r, float g, float b, float a, float fadeTime = 1.7, float holdTime = 0.0 )
{
	Assert( IsValid( player ) )

	ScreenFade( player, r, g, b, a, fadeTime, holdTime, FFADE_OUT | FFADE_PURGE )
}


void function ScreenFadeFromColor( entity player, float r, float g, float b, float a, float fadeTime = 2.0, float holdTime = 2.0 )
{
	Assert( IsValid( player ) )

	ScreenFade( player, r, g, b, a, fadeTime, holdTime, FFADE_IN | FFADE_PURGE )
}

void function ScreenFadeToBlack( entity player, float fadeTime, float holdTime )
{
	Assert( IsValid( player ) )

	ScreenFade( player, 0, 0, 1, 255, fadeTime, holdTime, FFADE_OUT | FFADE_PURGE )
}

void function ScreenFadeFromBlack( entity player, float fadeTime = 2.0, float holdTime = 2.0 )
{
	Assert( IsValid( player ) )

	ScreenFade( player, 0, 1, 0, 255, fadeTime, holdTime, FFADE_IN | FFADE_PURGE )
}

void function ScreenFadeToBlackForever( entity player, float fadeTime = 1.7 )
{
	Assert( IsValid( player ) )

	ScreenFade( player, 0, 0, 1, 255, fadeTime, 0, FFADE_OUT | FFADE_STAYOUT )
}

/*******************************************************
/ Server Effects
/
/	CreateServerEffect_Friendly( effectName, team )
/	CreateServerEffect_Enemy( effectName, team )
/	CreateServerEffect_Owner( effectName, owner )
/	SetServerEffectControlPoint( effectEnt, controlPoint, vecValue )
/	StartServerEffect( effectEnt )
/	StartServerEffectInWorld( effectEnt, origin, angles )
/	StartServerEffectOnEntity( effectEnt, ent, tag = null )
/
*******************************************************/

// NOTE: this does not play the effect, use StartEffectOnEntity
entity function CreateServerEffect_Friendly( asset effectName, int team )
{
	entity friendlyEffect = _CreateServerEffect( effectName, 2 ) // ENTITY_VISIBLE_TO_FRIENDLY
	friendlyEffect.kv.TeamNum = team
	friendlyEffect.kv.teamnumber = team

	return friendlyEffect
}

// NOTE: this does not play the effect, use StartEffectOnEntity
entity function CreateServerEffect_Enemy( asset effectName, int team )
{
	entity enemyEffect = _CreateServerEffect( effectName, 4 ) // ENTITY_VISIBLE_TO_ENEMY
	enemyEffect.kv.TeamNum = team
	enemyEffect.kv.teamnumber = team

	return enemyEffect
}

// NOTE: this does not play the effect, use StartEffectOnEntity
entity function CreateServerEffect_Owner( asset effectName, entity owner )
{
	Assert( IsValid( owner ) )

	entity ownerEffect = _CreateServerEffect( effectName, 1 ) // ENTITY_VISIBLE_TO_OWNER
	ownerEffect.kv.TeamNum = owner.GetTeam()
	ownerEffect.SetOwner( owner )

	return ownerEffect
}

entity function _CreateServerEffect( asset effectName, int visFlags )
{
	entity serverEffect = CreateEntity( "info_particle_system" )
	serverEffect.SetOrigin( <0, 0, 0> )
	serverEffect.SetAngles( <0, 0, 0> )
	serverEffect.SetValueForEffectNameKey( effectName )
	serverEffect.kv.start_active = 1
	serverEffect.kv.VisibilityFlags = visFlags

	thread _ServerEffectCleanup( serverEffect )
	return serverEffect
}

entity function SetServerEffectControlPoint( entity effectEnt, int controlPoint, vector vecValue ) // for now, only support static
{
	entity helper = CreateEntity( "info_placement_helper" )
	helper.SetOrigin( vecValue )
	effectEnt.SetControlPointEnt( controlPoint, helper )
	effectEnt.e.fxControlPoints.append( helper )

	return helper
}

void function StartServerEffect( entity effectEnt )
{
	DispatchSpawn( effectEnt )
}

void function StartServerEffectInWorld( entity effectEnt, vector origin, vector angles )
{
	effectEnt.SetOrigin( origin )
	effectEnt.SetAngles( angles )
	DispatchSpawn( effectEnt )
}

void function StartServerEffectOnEntity( entity effectEnt, entity ent, string tag = "" )
{
	Assert( IsValid( effectEnt ) )
	Assert( IsValid( ent ) )

	if ( tag != "" )
	{
		int attachID = ent.LookupAttachment( tag )
		vector origin = ent.GetAttachmentOrigin( attachID )
		vector angles = ent.GetAttachmentAngles( attachID )

		origin = ClampToWorldspace( origin )
		effectEnt.SetOrigin( origin )
		effectEnt.SetAngles( angles )
		effectEnt.SetParent( ent, tag, true )
	}
	else
	{
		effectEnt.SetParent( ent )
	}

	DispatchSpawn( effectEnt )
}

void function _ServerEffectCleanup( entity effectEnt )
{
	effectEnt.WaitSignal( "OnDestroy" )

	foreach ( entity controlPoint in effectEnt.e.fxControlPoints )
	{
		controlPoint.Destroy()
	}
}

float function GetYaw( vector org1, vector org2 )
{
	vector vec = org2 - org1
	vector angles = VectorToAngles( vec )
	return angles.y
}

void function HideName( entity ent )
{
	ent.SetNameVisibleToFriendly( false )
	ent.SetNameVisibleToEnemy( false )
	ent.SetNameVisibleToNeutral( false )
	ent.SetNameVisibleToOwner( false )
}

void function ShowName( entity ent )
{
	ent.SetNameVisibleToFriendly( true )
	ent.SetNameVisibleToEnemy( true )
	ent.SetNameVisibleToNeutral( true )
	ent.SetNameVisibleToOwner( true )
}

void function ShowNameToAllExceptOwner( entity ent )
{
	ent.SetNameVisibleToFriendly( true )
	ent.SetNameVisibleToEnemy( true )
	ent.SetNameVisibleToNeutral( true )
	ent.SetNameVisibleToOwner( false )
}

void function EmitSoundOnEntityToTeamExceptPlayer( entity ent, string sound, int team, entity excludePlayer )
{
	array<entity> players = GetPlayerArrayOfTeam( team )

	foreach ( player in players )
	{
		if ( player == excludePlayer )
			continue

		EmitSoundOnEntityOnlyToPlayer( ent, player, sound )
	}
}

#if DEV
// DEV function to toggle player view between the skybox and the real world.
void function ToggleSkyboxView( float scale = 0.001 )
{
	entity player = GetEntByIndex( 1 )

	entity skyboxCamLevel = GetEnt( "skybox_cam_level" )

	Assert( IsValid( skyboxCamLevel ), "Could not find a sky_camera entity named \"skybox_cam_level\" in this map." )

	vector skyOrigin = skyboxCamLevel.GetOrigin()

	if ( !file.isSkyboxView )
	{
		if ( !player.IsNoclipping() )
		{
			ClientCommand( player, "noclip" )
			wait( 0.25 )
		}

		ClientCommand( player, "sv_noclipspeed 0.1" )
		file.isSkyboxView = true
		vector offset = player.GetOrigin()
		offset *= scale

		player.SetOrigin( skyOrigin + offset - < 0.0, 0.0, 60.0 - (60.0 * scale) > )
	}
	else
	{
		ClientCommand( player, "sv_noclipspeed 5" )
		file.isSkyboxView = false
		vector offset = player.GetOrigin() - skyOrigin + < 0.0, 0.0, 60.0 - (60.0 * scale) >
		offset *= 1.0 / scale

		offset = ClampToWorldspace( offset )

		player.SetOrigin( offset )
	}
}

void function DamageRange( float value, float headShotMultiplier, int playerHealth = 200 )
{
	printt( "Damage Range: ", value, headShotMultiplier )

	float bodyShot = value
	float headShot = value * headShotMultiplier

	int maxHeadshots = 0

	int simHealth = playerHealth
	while ( simHealth > 0 )
	{
		simHealth = (simHealth.tofloat() - headShot).tointeger()
		maxHeadshots++
	}

	printt( "HeadShots:    BodyShots:     Total:" )

	simHealth = playerHealth
	int numHeadshots = 0
	while ( numHeadshots < maxHeadshots )
	{
		simHealth = playerHealth
		for ( int hsIdx = 0; hsIdx < numHeadshots; hsIdx++ )
		{
			simHealth = (simHealth.tofloat() - headShot).tointeger()
		}

		int numBodyShots = 0
		while ( simHealth > 0 )
		{
			simHealth = (simHealth.tofloat() - bodyShot).tointeger()
			numBodyShots++
		}
		printt( format( "%i             %i              %i", numHeadshots, numBodyShots, numHeadshots + numBodyShots ) )
		numHeadshots++
	}

	printt( format( "%i             %i              %i", numHeadshots, 0, numHeadshots ) )
}

#endif // DEV

void function MuteAll( entity player, int fadeOutTime = 2 )
{
	//DumpStack(2)
	Assert( player.IsPlayer() )

	Assert( fadeOutTime >= 1 && fadeOutTime <= 4 , "Only have 4 kinds of fadeout to play, time must be in the range [1,4]" )

	string fadeoutSoundString

	switch( fadeOutTime )
	{
		case 1:
			fadeoutSoundString = "1_second_fadeout"
			break

		case 2:
			fadeoutSoundString = "2_second_fadeout"
			break

		case 3:
			fadeoutSoundString = "3_second_fadeout"
			break

		case 4:
			fadeoutSoundString = "4_second_fadeout"
			break

		default:
			unreachable

	}

	printt( "Apply " +  fadeoutSoundString + " to player: " + player )

	EmitSoundOnEntityOnlyToPlayer( player, player, fadeoutSoundString )
}

//Mutes all except halftime sounds and dialogue
void function MuteHalfTime( entity player )
{
	Assert( player.IsPlayer() )
	printt( "Apply HalfTime_fadeout to player: " + player )
	EmitSoundOnEntityOnlyToPlayer( player, player, "HalfTime_fadeout" )
}

void function UnMuteAll( entity player )
{
	//DumpStack(2)
	Assert( player.IsPlayer() )

	//Just stop all the possible fadeout sounds.
	printt( "Stopping all fadeout for player: " + player )
	StopSoundOnEntity( player, "1_second_fadeout" )
	StopSoundOnEntity( player, "2_second_fadeout" )
	StopSoundOnEntity( player, "3_second_fadeout" )
	StopSoundOnEntity( player, "4_second_fadeout" )
	StopSoundOnEntity( player, "HalfTime_fadeout" )
}

void function AllPlayersMuteAll( int time = MUTEALLFADEIN )
{
	array<entity> players = GetPlayerArray()

	foreach ( player in players )
		MuteAll( player, time )
}

void function AllPlayersUnMuteAll()
{
	array<entity> players = GetPlayerArray()

	foreach ( player in players )
		UnMuteAll( player )
}

void function TakeAmmoFromPlayer( entity player )
{
	array<entity> mainWeapons = player.GetMainWeapons()
	array<entity> offhandWeapons = player.GetOffhandWeapons()

	foreach ( weapon in mainWeapons )
	{
		weapon.SetWeaponPrimaryAmmoCount( 0 )

		if ( weapon.GetWeaponPrimaryClipCountMax() > 0 )
			weapon.SetWeaponPrimaryClipCount( 0 )
	}

	foreach ( weapon in offhandWeapons )
	{
		weapon.SetWeaponPrimaryAmmoCount( 0 )

		if ( weapon.GetWeaponPrimaryClipCountMax() > 0 )
			weapon.SetWeaponPrimaryClipCount( 0 )
	}
}


bool function NearFlagSpawnPoint( vector dropPoint )
{
	if ( "flagSpawnPoint" in level && IsValid( level.flagSpawnPoint ) )
	{
		vector fspOrigin = expect entity( level.flagSpawnPoint ).GetOrigin()
		if ( Distance( fspOrigin, dropPoint ) < SAFE_TITANFALL_DISTANCE_CTF )
			return true
	}

	if ( "flagReturnPoint" in level && IsValid( level.flagReturnPoint ) )
	{
		vector fspOrigin = expect entity( level.flagReturnPoint ).GetOrigin()
		if ( Distance( fspOrigin, dropPoint ) < SAFE_TITANFALL_DISTANCE_CTF )
			return true
	}

	if ( "flagSpawnPoints" in level )
	{
		foreach ( flagSpawnPoint in svGlobal.flagSpawnPoints )
		{
			vector fspOrigin = flagSpawnPoint.GetOrigin()
			if ( Distance( fspOrigin, dropPoint ) < SAFE_TITANFALL_DISTANCE_CTF )
				return true
		}
	}

	return false
}

bool function HasCinematicFlag( entity player, int flag )
{
	Assert( player.IsPlayer() )
	Assert( IsValid( player ) )
	return ( player.GetCinematicEventFlags() & flag ) != 0
}

void function AddCinematicFlag( entity player, int flag )
{
	Assert( player.IsPlayer() )
	Assert( IsValid( player ) )
	player.SetCinematicEventFlags( player.GetCinematicEventFlags() | flag )
	player.Signal( "CE_FLAGS_CHANGED" )
}

void function RemoveCinematicFlag( entity player, int flag )
{
	Assert( player.IsPlayer() )
	Assert( IsValid( player ) )
	player.SetCinematicEventFlags( player.GetCinematicEventFlags() & ( ~flag ) )
	player.Signal( "CE_FLAGS_CHANGED" )
}

void function SkyScaleDefault( entity ent, float time = 1.0 )
{
	if ( IsValid( ent ) )
		ent.LerpSkyScale( SKYSCALE_DEFAULT, time )
}

void function MoveSpawn( string targetName, vector origin, vector angles )
{
	entity ent = GetEnt( targetName )
	ent.SetOrigin( origin )
	ent.SetAngles( angles )
}

/*
function CheckDailyChallengeAchievement( entity player )
{
	if ( player.GetPersistentVar( "cu8achievement.ach_allDailyChallengesForDay" ) == true )
		return

	int maxRefs = PersistenceGetArrayCount( "activeDailyChallenges" )
	int todaysDailiesComplete = 0
	int today = Daily_GetDayForCurrentTime()
	for ( int i = 0; i < maxRefs; i++ )
	{
		int day = player.GetPersistentVarAsInt( "activeDailyChallenges[" + i + "].day" )
		if ( day != today )
			continue

		local ref = player.GetPersistentVar( "activeDailyChallenges[" + i + "].ref" )
		if ( !IsChallengeComplete( ref, player ) )
			continue

		todaysDailiesComplete++
	}

	if ( todaysDailiesComplete >= 3 )
		player.SetPersistentVar( "cu8achievement.ach_allDailyChallengesForDay", true )
}
*/

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get an array of all linked entities targeted to one after the other down the chain
array<entity> function GetEntityTargetChain_Deprecated( entity ent )
{
	array<entity> entityChain = []
	entity currentEnt = ent
	entity nextEnt

	while ( true )
	{
		nextEnt = GetEnt( currentEnt.GetTarget_Deprecated() )
		if ( IsValid( nextEnt ) )
			entityChain.append( nextEnt )
		else
			return entityChain
		currentEnt = nextEnt
	}

	unreachable
}

void function PlayImpactFXTable( vector origin, entity owner, string impactFX, int flags = 0 )
{
	Explosion(
		origin,										//center,
		owner,										//attacker,
		owner,										//inflictor,flags
		0,											//damage,
		0,											//damageHeavyArmor,
		1,											//innerRadius,
		1,											//outerRadius,
		flags,										//flags,
		origin,										//projectileLaunchOrigin,
		0,											//explosionForce,
		damageTypes.explosive,						//scriptDamageFlags,
		-1,											//scriptDamageSourceIdentifier,
		impactFX )									//impactEffectTableName
}

void function SetSignalDelayed( entity ent, string signal, float delay )
{
	thread __SetSignalDelayedThread( ent, signal, delay )
}

void function __SetSignalDelayedThread( entity ent, string signal, float delay )
{
	EndSignal( ent, signal )	// so that if we call this again with the same signal on the same ent we won't get multiple signal events.

	wait delay
	if ( IsValid( ent ) )
		Signal( ent, signal )
}

#if DEV
table function GetPlayerPos( entity player = null )
{
	if ( !player )
		player = gp()[0]

	vector org = player.GetOrigin()
	vector vec = player.GetViewVector()
	vector ang = VectorToAngles( vec )

	return { origin = org, angles = ang }
}

string function GetScriptPos( entity player = null )
{
	table playerPos = GetPlayerPos( player )
	vector origin = expect vector( playerPos.origin )
	vector angles = expect vector( playerPos.angles )

	string returnStr = CreateOriginAnglesString( origin, <0, angles.y, 0> )
	return returnStr
}

string function CreateOriginAnglesString( vector origin, vector angles )
{
	string returnStr = "< " + origin.x + ", " + origin.y + ", " + origin.z + " >, < " + angles.x + ", " + angles.y + ", " + angles.z + " >"
	return returnStr
}

void function DistCheck_SetTestPoint()
{
	svGlobal.distCheckTestPoint = expect vector( GetPlayerPos().origin )
	printt( "DistCheck test point set to:", svGlobal.distCheckTestPoint )
}

void function DistCheck()
{
	vector here = expect vector( GetPlayerPos().origin )
	float dist = Distance( here, svGlobal.distCheckTestPoint )
	printt( "Distance:", dist, "units from", svGlobal.distCheckTestPoint )
}
#endif // DEV

void function ClearChildren( entity parentEnt ) //Probably should have code give us a GetChildren() function that returns a list instead of having to iterate through NextMovePeer
{
	entity childEnt = parentEnt.FirstMoveChild()
	entity nextChildEnt

	while ( childEnt != null )
	{
		nextChildEnt = childEnt.NextMovePeer()
		childEnt.ClearParent()

		childEnt = nextChildEnt
	}
}

void function ForceTimeLimitDone()
{
	level.devForcedWin = true
	level.devForcedTimeLimit = true
	svGlobal.levelEnt.Signal( "devForcedWin" )
	ServerCommand( "mp_enabletimelimit 1" )
	ServerCommand( "mp_enablematchending 1" )
}


void function UpdateBadRepPresent()
{
	array<entity> players = GetPlayerArray()
	bool found = false
/*	always set to false for now
	foreach ( player in players )
	{
		if ( player.HasBadReputation() )
		{
			found = true
			break
		}
	}
*/
	level.nv.badRepPresent = found
	level.ui.badRepPresent = found
}

void function Dev_PrintMessage( entity player, string text, string subText = "", float duration = 7.0, string soundAlias = "" )
{
	#if DEV
	// Build the message on the client
	string sendMessage
	for ( int textType = 0 ; textType < 2 ; textType++ )
	{
		sendMessage = textType == 0 ? text : subText

		for ( int i = 0; i < sendMessage.len(); i++ )
		{
			Remote_CallFunction_NonReplay( player, "Dev_BuildClientMessage", textType, sendMessage[i] )
		}
	}
	Remote_CallFunction_NonReplay( player, "Dev_PrintClientMessage", duration )
	if ( soundAlias != "" )
		EmitSoundOnEntity( player, soundAlias )
	#endif
}

bool function IsAttackDefendBased() //If needed to, we can make this a .nv and then move this function into utility_shared
{
	return expect bool( level.attackDefendBased )
}

bool function IsRoundBasedUsingTeamScore()  //If needed to, we can make this a .nv and then move this function into utility_shared
{
	return IsRoundBased() && expect bool( level.roundBasedUsingTeamScore )
}

bool function ShouldResetRoundBasedTeamScore()
{
	return IsRoundBased() && svGlobal.roundBasedTeamScore_RoundReset
}

void function CreateZipline( vector startPos, vector endPos )
{
	string startpointName = UniqueString( "rope_startpoint" )
	string endpointName = UniqueString( "rope_endpoint" )

	entity rope_start = CreateEntity( "move_rope" )
	SetTargetName( rope_start, startpointName )
	rope_start.kv.NextKey = endpointName
	rope_start.kv.MoveSpeed = 64
	rope_start.kv.Slack = 25
	rope_start.kv.Subdiv = "2"
	rope_start.kv.Width = "2"
	rope_start.kv.Type = "0"
	rope_start.kv.TextureScale = "1"
	rope_start.kv.RopeMaterial = "cable/zipline.vmt"
	rope_start.kv.PositionInterpolator = 2
	rope_start.kv.Zipline = "1"
	rope_start.kv.ZiplineAutoDetachDistance = "150"
	rope_start.kv.ZiplineSagEnable = "0"
	rope_start.kv.ZiplineSagHeight = "50"
	rope_start.SetOrigin( startPos )

	entity rope_end = CreateEntity( "keyframe_rope" )
	SetTargetName( rope_end, endpointName )
	rope_end.kv.MoveSpeed = 64
	rope_end.kv.Slack = 25
	rope_end.kv.Subdiv = "2"
	rope_end.kv.Width = "2"
	rope_end.kv.Type = "0"
	rope_end.kv.TextureScale = "1"
	rope_end.kv.RopeMaterial = "cable/zipline.vmt"
	rope_end.kv.PositionInterpolator = 2
	rope_end.kv.Zipline = "1"
	rope_end.kv.ZiplineAutoDetachDistance = "150"
	rope_end.kv.ZiplineSagEnable = "0"
	rope_end.kv.ZiplineSagHeight = "50"
	rope_end.SetOrigin( endPos )

	DispatchSpawn( rope_start )
	DispatchSpawn( rope_end )
}

string function GetNPCTitanSettingFile( entity titan )
{
	Assert( titan.IsTitan(), titan + " is not a titan" )
	return titan.ai.titanSettings.titanSetFile
}

void function DecodeBitField( int bitField )
{
	for ( int bitIndex = 0; bitIndex < 32; bitIndex++ )
	{
		if ( bitField & (1 << bitIndex) )
		{
			printt( "Comparison: ", bitField, "& ( 1 <<", bitIndex, ") = ", bitField & (1 << bitIndex) )
			printt( "BIT SET: ", bitIndex, bitField, 1 << bitIndex )
		}
	}
}

void function DropWeapon( entity npc )
{
	entity weapon = npc.GetActiveWeapon()
	if ( !weapon )
		return

	string name = weapon.GetWeaponClassName()

	// giving the weapon you have drops a new one in its place
	npc.GiveWeapon( name )
	npc.TakeActiveWeapon()
}

void function TestGiveGunTo( int index, string weaponName )
{
	entity ent = GetEntByIndex( index )
	if ( !ent )
	{
		printt( "No entity for index:", index )
		return;
	}

	TakePrimaryWeapon( ent )
	ent.GiveWeapon( weaponName )
	ent.SetActiveWeaponByName( weaponName )
}

string function GetEditorClass( entity self )
{
	if ( self.HasKey( "editorclass" ) )
		return expect string( self.kv.editorclass )

	return ""
}

bool function TitanHasRegenningShield( entity soul )
{
	if ( !TitanShieldRegenEnabled() )
		return false

	if ( !TitanShieldDecayEnabled() )
		return true

	if ( SoulHasPassive( soul, ePassives.PAS_SHIELD_BOOST ) )
		return true

	return false
}

void function DelayShieldDecayTime( entity soul, float delay )
{
	soul.e.nextShieldDecayTime = Time() + delay
}

void function HighlightWeapon( entity weapon )
{
#if HAS_WEAPON_PICKUP_HIGHLIGHT
	if ( weapon.IsLoadoutPickup() )
	{
		Highlight_SetOwnedHighlight( weapon, "sp_loadout_pickup" )
		Highlight_SetNeutralHighlight( weapon, "sp_loadout_pickup" )
	}
	else
	{
		Highlight_SetOwnedHighlight( weapon, "weapon_drop_active" )
		Highlight_SetNeutralHighlight( weapon, "weapon_drop_normal" )
	}
#endif // #if HAS_WEAPON_PICKUP_HIGHLIGHT
}

void function WaitTillLookingAt( entity player, entity ent, bool doTrace, float degrees, float minDist = 0, float timeOut = 0, entity trigger = null, string failsafeFlag = "" )
{
	EndSignal( ent, "OnDestroy" )
	EndSignal( player, "OnDeath" )

	//trigger = the trigger ther player must be touching while doing the check
	//failsafeFlag = bypass everything if this flag gets set

	if ( failsafeFlag != "" )
		EndSignal( level, failsafeFlag )

	float minDistSqr = minDist * minDist
	Assert( minDistSqr >= 0 )
	float timeoutTime = Time() + timeOut

	while( true )
	{

		if ( timeOut > 0 && Time() > timeoutTime )
			break

		if ( failsafeFlag != "" && Flag( failsafeFlag ) )
			break

		// Within range?
		if ( minDistSqr > 0 && DistanceSqr( player.GetOrigin(), ent.GetOrigin() ) > minDistSqr )
		{
			WaitFrame()
			continue
		}

		// Touching trigger?
		if ( ( trigger != null ) && ( !trigger.IsTouching( player ) ) )
		{
			WaitFrame()
			continue
		}

		if ( PlayerCanSee( player, ent, doTrace, degrees ) )
			break

		WaitFrame()
	}
}

void function SetTargetName( entity ent, string name )
{
	ent.SetValueForKey( "targetname", name )
}

ZipLine function CreateZipLine( vector start, vector end, int autoDetachDistance = 150, float ziplineMoveSpeedScale = 1.0 )
{
	string midpointName = UniqueString( "rope_midpoint" )
	string endpointName = UniqueString( "rope_endpoint" )

	entity rope_start = CreateEntity( "move_rope" )
	rope_start.kv.NextKey = midpointName
	rope_start.kv.MoveSpeed = 0
	rope_start.kv.ZiplineMoveSpeedScale = ziplineMoveSpeedScale
	rope_start.kv.Slack = 0
	rope_start.kv.Subdiv = 0
	rope_start.kv.Width = "2"
	rope_start.kv.TextureScale = "1"
	rope_start.kv.RopeMaterial = "cable/zipline.vmt"
	rope_start.kv.PositionInterpolator = 2
	rope_start.kv.Zipline = "1"
	rope_start.kv.ZiplineAutoDetachDistance = string( autoDetachDistance )
	rope_start.kv.ZiplineSagEnable = "0"
	rope_start.kv.ZiplineSagHeight = "0"
	rope_start.SetOrigin( start )

	entity rope_mid = CreateEntity( "keyframe_rope" )
	SetTargetName( rope_mid, midpointName )
	rope_start.kv.NextKey = endpointName
	rope_mid.SetOrigin( ( start + end ) * 0.5 )
	//rope_mid.SetOrigin( start )

	entity rope_end = CreateEntity( "keyframe_rope" )
	SetTargetName( rope_end, endpointName )
	rope_end.SetOrigin( end )

	// Dispatch spawn entities
	DispatchSpawn( rope_start )
	DispatchSpawn( rope_mid )
	DispatchSpawn( rope_end )

	ZipLine zipLine
	zipLine.start = rope_start
	zipLine.mid = rope_mid
	zipLine.end = rope_end

	return zipLine
}

entity function GetPlayerFromEntity( entity ent )
{
	entity player = null

	if ( ent.IsPlayer() )
	{
		player = ent
	}
	else if ( ent.IsNPC() )
	{
		player = ent.GetBossPlayer()
	}
	else
	{
		player = ent.GetOwner()
		if ( !player || !player.IsPlayer() )
			return null
	}

	if ( IsValid_ThisFrame( player ) )
		return player

	return null
}

void function SetHumanRagdollImpactTable( entity ent )
{
	ent.SetRagdollImpactFX( HUMAN_RAGDOLL_IMPACT_TABLE_IDX )
}

bool function ScriptManagedEntArrayContains( int handle, entity ent )
{
	array< entity > ents = GetScriptManagedEntArray( handle )
	foreach ( ent in ents )
	{
		if ( ent == ent )
			return true
	}

	return false
}

void function HideCrit( entity ent )
{
	int bodyGroupIndex = ent.FindBodyGroup( "hitpoints" )

	if ( bodyGroupIndex == -1 )
	{
		return
	}

	ent.SetBodygroup( bodyGroupIndex, 1 )
}

void function ShowCrit( entity ent )
{
	int bodyGroupIndex = ent.FindBodyGroup( "hitpoints" )

	if ( bodyGroupIndex == -1 )
	{
		return
	}

	ent.SetBodygroup( bodyGroupIndex, 0 )
}


#if DEV
void function TeleportEnemyBotToView()
{
	entity player = gp()[0]

	TraceResults traceResults = PlayerViewTrace( player )

	if ( traceResults.fraction >= 1.0 )
		return

	array<entity> players = GetPlayerArrayOfEnemies_Alive( player.GetTeam() )
	foreach ( enemy in players )
	{
		if ( !enemy.IsBot() )
			continue

		enemy.SetOrigin( traceResults.endPos )
		return
	}
}

void function TeleportEntityToView( entity ent )
{
	entity player = gp()[0]

	TraceResults traceResults = PlayerViewTrace( player )

	if ( traceResults.fraction >= 1.0 )
		return

	ent.SetOrigin( traceResults.endPos )
	//traceResults.surfaceNormal
}

void function TeleportFriendlyBotToView()
{
	entity player = gp()[0]

	TraceResults traceResults = PlayerViewTrace( player )

	if ( traceResults.fraction >= 1.0 )
		return

	array<entity> players = GetPlayerArrayOfTeam_Alive( player.GetTeam() )
	foreach ( enemy in players )
	{
		if ( !enemy.IsBot() )
			continue

		enemy.SetOrigin( traceResults.endPos )
		return
	}
}

void function TeleportBotToAbove()
{
	entity player = gp()[0]

	array<entity> players = GetPlayerArray_AlivePilots()
	foreach ( enemy in players )
	{
		if ( !enemy.IsBot() )
			continue

		enemy.SetOrigin( player.GetOrigin() + < 0, 0, 512 > )
		return
	}
}

TraceResults function PlayerViewTrace( entity player, float distance = 10000 )
{
	vector eyePosition = player.EyePosition()
	vector viewVector = player.GetViewVector()

	TraceResults traceResults = TraceLine( eyePosition, eyePosition + viewVector * distance, player, TRACE_MASK_SHOT_BRUSHONLY, TRACE_COLLISION_GROUP_NONE )

	return traceResults
}
#endif

void function ClearPlayerAnimViewEntity( entity player, float time = 0.3 )
{
	entity viewEnt = player.GetFirstPersonProxy()
	viewEnt.HideFirstPersonProxy()
	viewEnt.Anim_Stop()

	player.AnimViewEntity_SetLerpOutTime( time )
	player.AnimViewEntity_Clear()
	player.p.currViewConeFunction = null
}


void function BrushMoves( entity brush )
{
	float moveTime = float( brush.kv.move_time )
	int movedir = int( brush.kv.movedirection )

	BrushMovesInDirection( brush, movedir, moveTime )
}


void function BrushMovesInDirection( entity ent, int dir, float moveTime = 0, float blendIn = 0, float blendOut = 0, float lip = 8 )
{
	entity mover = CreateOwnedScriptMover( ent )
	OnThreadEnd(
		function() : ( ent, mover )
		{
			if ( IsValid( ent ) )
				ent.ClearParent()
			if ( IsValid( mover ) )
				mover.Destroy()
		}
	)

	dir %= 360
	if ( dir > 180 )
		dir -= 360
	else if ( dir < -180 )
		dir += 360

	string moveAxis = GetMoveAxisFromDir( dir )

	ent.SetParent( mover )
	vector origin = ent.GetOrigin()
	float moveAmount
	if ( ent.HasKey( "move_amount" ) )
	{
		moveAmount = float( ent.kv.move_amount ) - lip
		switch ( moveAxis )
		{
			case "x":
			case "y":
				if ( dir < 0 )
					moveAmount *= -1
				break

			case "z":
				if ( dir == -1 )
					moveAmount *= -1
				break
		}
	}
	else
	{
		switch ( moveAxis )
		{
			case "x":
				moveAmount = GetEntWidth( ent ) - lip
				if ( dir < 0 )
					moveAmount *= -1
				break

			case "y":
				moveAmount = GetEntDepth( ent ) - lip
				if ( dir < 0 )
					moveAmount *= -1
				break

			case "z":
				moveAmount = GetEntHeight( ent ) - lip
				if ( dir == -1 )
					moveAmount *= -1
				break
		}
	}

	switch ( moveAxis )
	{
		case "x":
			origin.x += moveAmount
			break
		case "y":
			origin.y += moveAmount
			break
		case "z":
			origin.z += moveAmount
			break
	}

	if ( moveTime > 0 )
	{
		mover.NonPhysicsMoveTo( origin, moveTime, blendIn, blendOut )
		wait moveTime
	}
	else
	{
		mover.SetOrigin( origin )
	}
}

string function GetMoveAxisFromDir( int dir )
{
	if ( dir == 1 || dir == -1 )
		return "z"

	if ( dir % 180 == 0 )
		return "x"

	return "y"
}


float function GetEntHeight( entity ent )
{
	return ent.GetBoundingMaxs().z - ent.GetBoundingMins().z
}

float function GetEntWidth( entity ent )
{
	return ent.GetBoundingMaxs().x - ent.GetBoundingMins().x
}

float function GetEntDepth( entity ent )
{
	return ent.GetBoundingMaxs().y - ent.GetBoundingMins().y
}

void function PushEntWithVelocity( entity ent, vector velocity )
{
	if ( !ent.IsPlayer() && !ent.IsNPC() )
		return

	if ( !IsAlive( ent ) )
		return

	float scale = 1.0
	float pushbackScale = 1.0
	if ( ent.IsTitan() )
	{
		entity soul = ent.GetTitanSoul()
		if ( soul != null ) // defensive fix
		{
			string settings = GetSoulPlayerSettings( soul )
			var scale = Dev_GetPlayerSettingByKeyField_Global( settings, "pushbackScale" )
			if ( scale != null )
			{
				pushbackScale = expect float( scale )
			}
		}
	}

	scale = 1.0 - StatusEffect_Get( ent, eStatusEffect.pushback_dampen )
	scale = scale * pushbackScale

	velocity *= scale

	ent.SetVelocity( velocity )
}



bool function IsPlayerMalePilot( entity player )
{
	Assert( player.IsPlayer() )

	if ( !IsPilot( player ) )
		return false

	return !IsPlayerFemale( player )
}

bool function IsPlayerFemalePilot( entity player )
{
	Assert( player.IsPlayer() )

	if ( !IsPilot( player ) )
		return false

	return IsPlayerFemale( player )
}

bool function IsFacingEnemy( entity guy, entity enemy, int viewAngle = 75 )
{
	vector dir = enemy.GetOrigin() - guy.GetOrigin()
	dir = Normalize( dir )
	float dot = DotProduct( guy.GetPlayerOrNPCViewVector(), dir )
	float yaw = DotToAngle( dot )

	return ( yaw < viewAngle )
}

void function SetSquad( entity guy, string squadName )
{
	Assert( IsValid( guy ) )

	if ( guy.kv.squadname == squadName )
		return

	// we only want squads containing NPCs of the same class
	#if HAS_AI_SQUAD_LIMITS
	Assert( SquadValidForClass( squadName, guy.GetClassName() ), "Can't put AI " + guy + " in squad " + squadName + ", because it contains one or more AI with a different class." )
	Assert( SquadCanAcceptNewMembers( guy, squadName ), "Can't add AI " + guy + " to squad " + squadName + ", because that squad already has " + SQUAD_SIZE + " slots filled or reserved." )
	#endif

	guy.SetSquad( squadName )
}

void function PushPlayersApart( entity target, entity attacker, float speed )
{
	vector dif = Normalize( target.GetOrigin() - attacker.GetOrigin() )
	dif *= speed
	PushPlayerAway( target, dif )
	PushPlayerAway( attacker, -dif )
}

void function PushPlayerAway( entity target, vector velocity )
{
	#if MP
	if ( !target.IsPlayer() && !target.IsNPC() )
		return
	#endif

	vector result = velocity // + target.GetVelocity()
	result.z = max( 200, fabs( velocity.z ) )
	target.SetVelocity( result )
	//DebugDrawLine( target.GetOrigin(), target.GetOrigin() + result * 5, 255, 0, 0, true, 5.0 )
}


int function SortBySpawnTime( entity ent1, entity ent2 )
{
	if ( ent1.e.spawnTime > ent2.e.spawnTime )
		return 1

	if ( ent2.e.spawnTime > ent1.e.spawnTime )
		return -1

	return 0
}

void function HolsterAndDisableWeapons( entity player )
{
	player.HolsterWeapon()
	DisableOffhandWeapons( player )
}

void function HolsterViewModelAndDisableWeapons( entity player ) //Note that this skips the first person holster animation, and it appears to 3p observers you still have a gun out
{
	player.DisableWeaponViewModel()
	DisableOffhandWeapons( player )
}


void function DeployAndEnableWeapons( entity player )
{
	player.DeployWeapon()
	EnableOffhandWeapons( player )
}

void function DeployViewModelAndEnableWeapons( entity player )
{
	if ( IsAlive( player ) )
		player.EnableWeaponViewModel()
	EnableOffhandWeapons( player )
}

//Investigate: This might be getting called without enableoffhandweapons being called. If so,  Server_TurnOffhandWeaponsDisabledOn() should be used instead of this stack system.
void function DisableOffhandWeapons( entity player )
{
	player.Server_TurnOffhandWeaponsDisabledOn()
	player.p.disableOffhandWeaponsStackCount++
}

void function EnableOffhandWeapons( entity player )
{
	player.p.disableOffhandWeaponsStackCount--
	if ( player.p.disableOffhandWeaponsStackCount <= 0 )
		player.Server_TurnOffhandWeaponsDisabledOff()

	Assert( player.p.disableOffhandWeaponsStackCount >= 0, "Warning! Called EnableOffhandWeapons() but the weapons aren't disabled!" )
}

void function PushEntWithDamageInfoAndDistanceScale( entity ent, var damageInfo, float nearRange, float farRange, float nearScale, float farScale, float forceMultiplier_dotBase = 0.5 )
{
	float scale = GraphCapped( DamageInfo_GetDistFromAttackOrigin( damageInfo ), nearRange, farRange, nearScale, farScale )

	if ( scale > 0 )
		PushEntWithDamageInfo( ent, damageInfo, forceMultiplier_dotBase, scale )
}

void function PushEntWithDamageInfo( entity ent, var damageInfo, float forceMultiplier_dotBase = 0.5, float forceMultiplier_dotScale = 0.5 )
{
	int source = DamageInfo_GetDamageSourceIdentifier( damageInfo )
	switch ( source )
	{
 		case eDamageSourceId.mp_titanweapon_vortex_shield:
  		case eDamageSourceId.mp_titanweapon_vortex_shield_ion:
			return
	}

	entity projectile = DamageInfo_GetInflictor( damageInfo )
	if ( !IsValid( projectile ) )
		return

	vector attackDirection = Normalize( projectile.GetVelocity() )
	float damage = DamageInfo_GetDamage( damageInfo )

	PushEntWithDamageFromDirection( ent, damage, attackDirection, forceMultiplier_dotBase, forceMultiplier_dotScale )
}

void function PushEntWithDamageFromDirection( entity ent, float damage, vector attackDirection, float forceMultiplier_dotBase = 0.5, float forceMultiplier_dotScale = 0.5 )
{

	float speed
	if ( damage < 900 )
		speed = GraphCapped( damage, 0, 900, 0, 650 )
	else
		speed = GraphCapped( damage, 900, 1400, 650, 1400 )

	vector direction = attackDirection + <0,0,0>
	direction.z *= 0.25
	vector force = direction * speed

	force += < 0, 0, fabs( direction.z ) * 0.25 >

	vector velocity = ent.GetVelocity()
	vector baseVel = Normalize( velocity + <0,0,0> )

	float dot = DotProduct( baseVel, attackDirection ) * -1
	float dotMultiplier
	if ( dot > 0 )
	{
		dot *= forceMultiplier_dotScale
	}
	else
	{
		dot = 0
	}

	force *= ( forceMultiplier_dotBase + dot )
	//printt( "force " + Length( force ) )
	velocity += force
	PushEntWithVelocity( ent, velocity )
}


void function SetPlayerAnimViewEntity( entity player, entity model )
{
	// clear any attempts to hide the view anim entity
	player.Signal( "NewViewAnimEntity" )
	player.AnimViewEntity_SetEntity( model )
}


void function RandomizeHead( entity model ) //Randomize head across all available heads
{
	int headIndex = model.FindBodyGroup( "head" )
	if ( headIndex == -1 )
	{
		//printt( "HeadIndex == -1, returning" )
		return
	}
	int numOfHeads = model.GetBodyGroupModelCount( headIndex ) - 1 // last one is no head
	//printt( "Num of Heads: " + numOfHeads )

	if ( HasTeamSkin( model ) )
	{
		RandomizeHeadByTeam( model, headIndex, numOfHeads )
		return
	}
	else
	{
		int randomHeadIndex = RandomInt( numOfHeads )
		//printt( "Set head to: : " + randomHeadIndex )
		model.SetBodygroup( headIndex, randomHeadIndex )
	}
}

bool function HasTeamSkin( entity model )
{
	return  "teamSkin" in model.CreateTableFromModelKeyValues()
}

void function RandomizeHeadByTeam( entity model, int headIndex, int numOfHeads ) //Randomize head across heads available to a particular team. Assumes for a model all imc heads are first, then all militia heads are later.
{
	float midPoint = float( numOfHeads / 2 )

	int randomHeadIndex = 0
	if ( model.GetTeam() == TEAM_IMC )
	{
		randomHeadIndex = RandomInt( midPoint )
	}
	else if ( model.GetTeam() == TEAM_MILITIA )
	{
		randomHeadIndex = RandomIntRange( midPoint, numOfHeads )
	}
	//printt( "Model ", model.GetModelName(), " is using ", numOfHeads, " randomHeadIndex")

	//printt( "Set head to: : " + randomHeadIndex )
	model.SetBodygroup( headIndex, randomHeadIndex )
}

void function TakeWeaponsForArray( entity ent, array<entity> weapons )
{
	foreach ( weapon in weapons )
	{
		ent.TakeWeaponNow( weapon.GetWeaponClassName() )
	}
}

void function ScaleHealth( entity ent, float scale )
{
	Assert( IsAlive( ent ) )

	int maxHealth = ent.GetMaxHealth()
	float healthRatio = float( ent.GetHealth() ) / maxHealth
	maxHealth = int( maxHealth * scale )
	ent.SetHealth( maxHealth * healthRatio )
	ent.SetMaxHealth( maxHealth )
}

void function TeleportPlayerToEnt( entity player, entity org )
{
	if ( !IsValid( player ) )
		return
	Assert( player.IsPlayer() )
	player.SetOrigin( org.GetOrigin() )
	player.SetAngles( org.GetAngles() )
}

float function ShieldModifyDamage( entity ent, var damageInfo )
{
	entity victim
	if ( ent.IsTitan() )
		victim = ent.GetTitanSoul()
	else
		victim = ent

	int shieldHealth = victim.GetShieldHealth()

	float damage = DamageInfo_GetDamage( damageInfo )

	int damageSourceIdentifier = DamageInfo_GetDamageSourceIdentifier( damageInfo )
	ShieldDamageModifier damageModifier = GetShieldDamageModifier( damageInfo )
	damage *= damageModifier.damageScale

	float healthFrac = GetHealthFrac( victim )

	float permanentDamage = (damage * damageModifier.permanentDamageFrac * healthFrac)

	float shieldDamage

	if ( damageSourceIdentifier == eDamageSourceId.titanEmpField )
	{
		shieldDamage = min( 1000.0, float( shieldHealth ) )
	}
	else
	{
		if ( damageModifier.normalizeShieldDamage )
			shieldDamage = damage * 0.5
		else
			shieldDamage = damage - permanentDamage

		// if ( IsSoul( victim ) && SoulHasPassive( victim, ePassives.PAS_SHIELD_BOOST ) )
		// 	shieldDamage *= SHIELD_BOOST_DAMAGE_DAMPEN

		if ( IsSoul( victim ) && SoulHasPassive( victim, ePassives.PAS_BERSERKER ) )
			shieldDamage *= BERSERKER_INCOMING_DAMAGE_DAMPEN
	}

	float newShieldHealth = shieldHealth - shieldDamage

	victim.SetShieldHealth( max( 0, newShieldHealth ) )

	if ( shieldHealth > 0 && newShieldHealth <= 0 )
	{
		if ( ent.IsPlayer() )
		{
			EmitSoundOnEntityExceptToPlayer( ent, ent, "titan_energyshield_down_3P" )
			EmitSoundOnEntityOnlyToPlayer( ent, ent, "titan_energyshield_down_1P" )
		}
		else if ( ent.GetScriptName() == "fw_team_tower" )
		{
			EmitSoundOnEntity( ent, "TitanWar_Harvester_ShieldDown" )

			#if FACTION_DIALOGUE_ENABLED
				PlayFactionDialogueToTeam( "fortwar_baseShieldDownFriendly", ent.GetTeam() )
				PlayFactionDialogueToTeam( "fortwar_baseShieldDownEnemy", GetOtherTeam( ent.GetTeam() ) )
			#endif
		}
		else
		{
			EmitSoundOnEntity( ent, "titan_energyshield_down_3P" )
		}
	}

	DamageInfo_AddCustomDamageType( damageInfo, DF_SHIELD_DAMAGE )

	if ( newShieldHealth < 0 )
	{
		DamageInfo_SetDamage( damageInfo, fabs( newShieldHealth ) + permanentDamage )
	}
	else
	{
		if ( permanentDamage == 0 )
		{
			entity attacker = DamageInfo_GetAttacker( damageInfo )
			vector damageOrigin = GetDamageOrigin( damageInfo, ent )
			int damageType = DamageInfo_GetCustomDamageType( damageInfo )
			int attackerEHandle = attacker.GetEncodedEHandle()
			int damageSourceId = DamageInfo_GetDamageSourceIdentifier( damageInfo )

			if ( attacker.IsPlayer() )
				attacker.NotifyDidDamage( ent, DamageInfo_GetHitBox( damageInfo ), DamageInfo_GetDamagePosition( damageInfo ), damageType, shieldDamage, DamageInfo_GetDamageFlags( damageInfo ), DamageInfo_GetHitGroup( damageInfo ), DamageInfo_GetWeapon( damageInfo ), DamageInfo_GetDistFromAttackOrigin( damageInfo ) )
			if ( ent.IsPlayer() )
				Remote_CallFunction_Replay( ent, "ServerCallback_TitanTookDamage", shieldDamage, damageOrigin.x, damageOrigin.y, damageOrigin.z, damageType, damageSourceId, attackerEHandle, null, false, 0 )
		}
		DamageInfo_SetDamage( damageInfo, permanentDamage )
	}

	float actualShieldDamage = min( shieldHealth, shieldDamage )

	if ( actualShieldDamage > 0 )
	{
		foreach ( func in ent.e.entPostShieldDamageCallbacks )
		{
			func( ent, damageInfo, actualShieldDamage )
		}
	}

	return actualShieldDamage
}

ShieldDamageModifier function GetShieldDamageModifier( var damageInfo )
{
	ShieldDamageModifier damageModifier

	// Disabling Shield Damage Modifiers and rebalancing the weapons. The below mechanics seem cool in an R1 style system though so leaving them commented out.
	// NOTE: Changing Damage Scale has a buggy interaction with permanent damage that must be fixed if we re-enable this.
	/*
	int damageSourceIdentifier = DamageInfo_GetDamageSourceIdentifier( damageInfo )

	switch ( damageSourceIdentifier )
	{
		case eDamageSourceId.mp_weapon_thermite_grenade:
			damageModifier.permanentDamageFrac = 0.9
			break
	}

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_ELECTRICAL )
	{
		// amped version
		if ( damageSourceIdentifier == eDamageSourceId.mp_titanweapon_xo16 )
			damageModifier.damageScale *= 1.5

		// amped version
		if ( damageSourceIdentifier == eDamageSourceId.mp_titanweapon_triple_threat )
			damageModifier.damageScale *= 1.5

		if ( damageSourceIdentifier == eDamageSourceId.mp_titanweapon_arc_cannon )
			damageModifier.damageScale *= 1.5
	}
	*/

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_ELECTRICAL )
	{
		int damageSourceIdentifier = DamageInfo_GetDamageSourceIdentifier( damageInfo )
		// Vanguard Arc Rounds
		if ( damageSourceIdentifier == eDamageSourceId.mp_titanweapon_xo16_vanguard )
			damageModifier.damageScale *= 1.5
	}


	return damageModifier
}



void function AddCallback_NPCLeeched( void functionref( entity, entity ) callbackFunc )
{
	Assert( !( svGlobal.onLeechedCustomCallbackFunc.contains( callbackFunc ) ) )
	svGlobal.onLeechedCustomCallbackFunc.append( callbackFunc )
}

void function MessageToPlayer( entity player, int eventID, entity ent = null, var eventVal = null )
{
	var eHandle = null
	if ( ent )
		eHandle = ent.GetEncodedEHandle()

	Remote_CallFunction_NonReplay( player, "ServerCallback_EventNotification", eventID, eHandle, eventVal )
	//SendHudMessage( player, message, 0.33, 0.28, 255, 255, 255, 255, 0.15, 3.0, 0.5 )
}


void function MessageToTeam( int team, int eventID, entity excludePlayer = null, entity ent = null, var eventVal = null )
{
	array<entity> players = GetPlayerArray()

	foreach ( player in players )
	{
		if ( player.GetTeam() != team )
			continue

		if ( player == excludePlayer )
			continue

		MessageToPlayer( player, eventID, ent, eventVal )
	}
}

void function MessageToAll( int eventID, entity excludePlayer = null, entity ent = null, var eventVal = null )
{
	array<entity> players = GetPlayerArray()

	foreach ( player in players )
	{
		if ( player == excludePlayer )
			continue

		MessageToPlayer( player, eventID, ent, eventVal )
	}
}



string function ReloadScriptsInternal()
{
	reloadingScripts = true
	reloadedScripts = true
	ReloadingScriptsBegin()

	if ( IsMenuLevel() )
	{
		reloadingScripts = false
		ReloadingScriptsEnd()
		return ""
	}

	TitanEmbark_Init()

	ReloadScriptCallbacks()

	reloadingScripts = false
	ReloadingScriptsEnd()

	return ( "reloaded server scripts" )
}

string function ReloadScripts()
{
	ServerCommand( "fs_report_sync_opens 0" ) // makes reload scripts slow
	delaythread ( 0 ) ReloadScriptsInternal()

	return ( "reloaded server scripts" )
}

void function SetGameEndTime(float seconds)
{
	SetServerVar( "gameEndTime", Time() + seconds )
}

void function SetRoundEndTime(float seconds)
{
	SetServerVar( "roundEndTime", Time() + seconds )
}

void function SetScoreLimit(int newLimit)
{
	SetPlaylistVarOverride( "scorelimit", string(newLimit) )
}

int function GameTime_TimeLimitSeconds()
{
	if ( IsRoundBased() )
	{
		return ( GetRoundTimeLimit_ForGameMode() * 60.0 ).tointeger()
	}
	else
	{
		if ( IsSuddenDeathGameMode() && GetGameState() == eGameState.SuddenDeath )
			return ( GetTimeLimit_ForGameMode() * 60.0 ).tointeger() + ( GetSuddenDeathTimeLimit_ForGameMode() * 60.0 ).tointeger()
		else
			return ( GetTimeLimit_ForGameMode() * 60.0 ).tointeger()
	}
	unreachable
}

int function GetSuddenDeathTimeLimit_ForGameMode()
{
	string mode = GameRules_GetGameMode()
	string playlistString = "suddendeath_timelimit"

	return GetCurrentPlaylistVarInt( playlistString, 4 )
}

int function GameTime_TimeLimitMinutes()
{
	if ( IsRoundBased() )
		return floor( GetRoundTimeLimit_ForGameMode() ).tointeger()
	else
		return floor( GetTimeLimit_ForGameMode() ).tointeger()
	unreachable
}

int function GameTime_TimeLeftMinutes()
{
	if ( GetGameState() == eGameState.WaitingForPlayers )
		return 0
	if ( GetGameState() == eGameState.Prematch )
		return int( ( expect float( GetServerVar( "gameStartTime" ) ) - Time()) / 60.0 )

	return floor( GameTime_TimeLimitMinutes() - GameTime_PlayingTime() / 60 ).tointeger()
}

int function GameTime_TimeLeftSeconds()
{
	if ( GetGameState() == eGameState.Prematch )
		return int( expect float( GetServerVar( "gameStartTime" ) ) - Time() )

	return floor( GameTime_TimeLimitSeconds() - GameTime_PlayingTime() ).tointeger()
}

int function GameTime_Seconds()
{
	return floor( Time() ).tointeger()
}

int function GameTime_Minutes()
{
	return int( floor( GameTime_Seconds() / 60 ) )
}

float function GameTime_PlayingTime()
{
	return GameTime_PlayingTimeSince( Time() )
}

float function GameTime_PlayingTimeSince( float sinceTime )
{
	int gameState = GetGameState()
	
	// temp fix because i have no fucking clue why this crashes

	if ( gameState < eGameState.Playing )
		return 0

	if ( IsRoundBased() )
	{
		if ( gameState > eGameState.SuddenDeath )
			return (expect float( GetServerVar( "roundEndTime" ) ) - expect float( GetServerVar( "roundStartTime" ) ) )
		else
			return sinceTime - expect float( GetServerVar( "roundStartTime" ) )
	
	}
	else
	{
		if ( gameState > eGameState.SuddenDeath )
			return (expect float( GetServerVar( "gameEndTime" ) ) - expect float( GetServerVar( "gameStartTime" ) ) )
		else
			return sinceTime - expect float( GetServerVar( "gameStartTime" ) )
	}
	
	unreachable
}

float function GameTime_TimeSpentInCurrentState()
{
	return Time() - expect float( GetServerVar( "gameStateChangeTime" ) )
}

int function GameScore_GetFirstToScoreLimit()
{
	return expect int( level.firstToScoreLimit )
}

bool function GameScore_AllowPointsOverLimit()
{
	return svGlobal.allowPointsOverLimit
}

int function GameScore_GetWinningTeam()
{
	if ( GameScore_GetFirstToScoreLimit() )
		return GameScore_GetFirstToScoreLimit()

	if ( IsRoundBased() )
	{
		if ( GameRules_GetTeamScore2( TEAM_IMC ) > GameRules_GetTeamScore2( TEAM_MILITIA ) )
			return TEAM_IMC
		else if ( GameRules_GetTeamScore2( TEAM_MILITIA ) > GameRules_GetTeamScore2( TEAM_IMC ) )
			return TEAM_MILITIA
	}
	else
	{
		if ( GameRules_GetTeamScore( TEAM_IMC ) > GameRules_GetTeamScore( TEAM_MILITIA ) )
			return TEAM_IMC
		else if ( GameRules_GetTeamScore( TEAM_MILITIA ) > GameRules_GetTeamScore( TEAM_IMC ) )
			return TEAM_MILITIA
	}

	return TEAM_UNASSIGNED
}

int function GameScore_GetWinningTeam_ThisRound()
{
	if ( GameScore_GetFirstToScoreLimit() )
		return GameScore_GetFirstToScoreLimit()

	Assert ( IsRoundBased() )

	if ( GameRules_GetTeamScore( TEAM_IMC ) > GameRules_GetTeamScore( TEAM_MILITIA ) )
		return TEAM_IMC
	else if ( GameRules_GetTeamScore( TEAM_MILITIA ) > GameRules_GetTeamScore( TEAM_IMC ) )
		return TEAM_MILITIA

	return TEAM_UNASSIGNED
}

#if DEV
void function KillIMC()
{
	array<entity> enemies = GetNPCArrayOfTeam( TEAM_IMC )
	foreach ( enemy in enemies )
	{
		enemy.Die()
	}
}

void function killtitans()
{
	printt( "Script command: Kill all titans" )
	array<entity> titans = GetTitanArray()
	foreach ( titan in titans )
		titan.Die()
}

void function killminions()
{
	printt( "Script command: Kill all minions" )
	array<entity> minions = GetAllMinions()
	foreach ( minion in minions )
	{
		minion.Die()
	}
}
#endif


array<entity> function GetTeamMinions( int team )
{
	array<entity> ai = GetNPCArrayByClass( "npc_soldier" )
	ai.extend( GetNPCArrayByClass( "npc_spectre" ) )

	for ( int i = 0; i < ai.len(); i++ )
	{
		if ( ai[i].GetTeam() != team )
		{
			ai.remove(i)
			i--
		}
	}

	return ai
}

array<entity> function GetAllMinions()
{
	array<entity> ai = GetNPCArrayByClass( "npc_soldier" )
	ai.extend( GetNPCArrayByClass( "npc_spectre" ) )
	ai.extend( GetNPCArrayByClass( "npc_drone" ) )

	return ai
}


bool function GameScore_IsLowScoreDifference()
{
	int winningTeam = GameScore_GetWinningTeam()

	if ( !winningTeam )
		return true

	int losingTeam = GetOtherTeam( winningTeam )

	int winningTeamScore
	int losingTeamScore

	if ( IsRoundBased() )
	{
		winningTeamScore = GameRules_GetTeamScore2( winningTeam )
		losingTeamScore =  GameRules_GetTeamScore2( losingTeam )
	}
	else
	{
		winningTeamScore =  GameRules_GetTeamScore( winningTeam )
		losingTeamScore =   GameRules_GetTeamScore( losingTeam )
	}

	return ( winningTeamScore - losingTeamScore < 2 )
}

bool function IsFastPilot( entity player )
{
	Assert( IsPilot( player ), "Pilot only check" )

	if ( player.IsWallHanging() )
		return false

	if ( player.IsWallRunning() )
		return true

	if ( !player.IsOnGround() )
		return true

	if ( LengthSqr( player.GetSmoothedVelocity() ) > 180*180 || LengthSqr( player.GetVelocity() ) > 180*180 )
		return true

	return false
}

void function KillPlayer( entity player, int damageSource )
{
	#if DEV
	printt( "Played Killed from script: " )
	DumpStack()
	#endif

	Assert( IsAlive( player ) )
	Assert( player.IsPlayer() )
	player.Die( svGlobal.worldspawn, svGlobal.worldspawn, { damageSourceId = damageSource, scriptType=DF_SKIP_DAMAGE_PROT | DF_SKIPS_DOOMED_STATE } )
}


//////////////////////////////////////////////////////////
void function TurretChangeTeam( entity turret, int team )
{
	if ( team != TEAM_UNASSIGNED )
	{
		// If a turret is on some player's team it should never be invulnerable
		MakeTurretVulnerable( turret )
	}

	SetTeam( turret, team )

	// refresh the turret client side particle effects
	UpdateTurretClientSideParticleEffects( turret )
}

void function MakeTurretInvulnerable( entity turret )
{
	Assert( IsValid( turret ) )
	turret.SetInvulnerable()
	turret.SetNoTarget(true)
	turret.SetNoTargetSmartAmmo(true)
}

void function MakeTurretVulnerable( entity turret )
{
	Assert( IsValid( turret ) )
	turret.ClearInvulnerable()
	turret.SetNoTarget(false)
	turret.SetNoTargetSmartAmmo(false)
}


void function UpdateTurretClientSideParticleEffects( entity turret )
{
	if ( !IsValid( turret ) )
		return

	int turretEHandle = turret.GetEncodedEHandle()
	array<entity> players = GetPlayerArray()
	foreach( player in players )
	{
		Remote_CallFunction_Replay( player, "ServerCallback_TurretRefresh", turretEHandle )
	}
}



bool function TakePrimaryWeapon( entity player )
{
	array<entity> weapons = player.GetMainWeapons()
	foreach ( index, weaponEnt in weapons )
	{
		int weaponType = weaponEnt.GetWeaponType()
		if ( weaponType == WT_SIDEARM || weaponType == WT_ANTITITAN )
			continue;

		string weapon = weaponEnt.GetWeaponClassName()
		player.TakeWeaponNow( weapon )
		return true
	}
	return false
}

bool function TakeSecondaryWeapon( entity player )
{
	array<entity> weapons = player.GetMainWeapons()
	foreach ( index, weaponEnt in weapons )
	{
		if ( weaponEnt.GetWeaponType() != WT_ANTITITAN )
			continue

		string weapon = weaponEnt.GetWeaponClassName()
		player.TakeWeaponNow( weapon )
		return true
	}
	return false
}

bool function TakeSidearmWeapon( entity player )
{
	array<entity> weapons = player.GetMainWeapons()
	foreach ( index, weaponEnt in weapons )
	{
		if ( weaponEnt.GetWeaponType() != WT_SIDEARM )
			continue

		string weapon = weaponEnt.GetWeaponClassName()
		player.TakeWeaponNow( weapon )
		return true
	}
	return false
}

void function TakeAllWeapons( entity ent )
{
	if ( ent.IsPlayer() )
	{
		ent.RemoveAllItems()
		array<entity> weapons = ent.GetMainWeapons()
		foreach ( weapon in weapons )
		{
			Assert( 0, ent + " still has weapon " + weapon.GetWeaponClassName() + " after doing takeallweapons" )
		}
	}
	else
	{
		array<entity> weapons = ent.GetMainWeapons()
		TakeWeaponsForArray( ent, weapons )

		weapons = ent.GetOffhandWeapons()
		foreach ( index, weapon in clone weapons )
		{
			ent.TakeOffhandWeapon( index )
		}
		TakeWeaponsForArray( ent, weapons )
	}
}


void function SetSpawnflags( entity ent, int spawnFlags )
{
	ent.kv.spawnflags = spawnFlags
}


void function DestroyAfterDelay( entity ent, float delay )
{
	Assert( IsNewThread(), "Must be threaded off" )

	ent.EndSignal( "OnDestroy" )

	wait( delay )

	ent.Destroy()
}

void function UnlockAchievement( entity player, int achievementID )
{
	Assert( IsValid( player ), "Can't unlock achievement on invalid player entity" )
	Assert( player.IsPlayer(), "Can't unlock achivement on non-player entity" )
	Assert( achievementID > 0 && achievementID < achievements.MAX_ACHIVEMENTS, "Tried to unlock achievement with invalid enum value" )

	Remote_CallFunction_UI( player, "ScriptCallback_UnlockAchievement", achievementID )
}

void function UpdateHeroStatsForPlayer( entity player )
{
	if ( !IsValid( player ) )
		return
	Remote_CallFunction_NonReplay( player, "ServerCallback_UpdateHeroStats" )
}

void function TestDeathFall()
{
	entity trigger = GetEntByScriptName( "DeathFallTrigger" )
	table results = WaitSignal( trigger, "OnTrigger" )
	printt( "DEATH FALL TRIGGERED" )
	PrintTable( results )
}

bool function PlayerHasTitan( entity player )
{
	entity titan
	if ( player.IsTitan() )
		titan = player
	else
		titan = player.GetPetTitan()

	if ( IsAlive( titan ) )
		return true

	return false
}