aboutsummaryrefslogtreecommitdiff
path: root/Northstar.CustomServers/mod/scripts/vscripts/weapons/_weapon_utility.nut
blob: b3e5f5a39b745d688aaba963adc6786e2392e59f (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
untyped

//TODO: Should split this up into server, client and shared versions and just globalize_all_functions
global function WeaponUtility_Init

global function ApplyVectorSpread
global function DebugDrawMissilePath
global function DegreesToTarget
global function DetonateAllPlantedExplosives
global function EntityCanHaveStickyEnts
global function EntityShouldStick
global function FireExpandContractMissiles
global function FireExpandContractMissiles_S2S
global function GetVectorFromPositionToCrosshair
global function GetVelocityForDestOverTime
global function GetPlayerVelocityForDestOverTime
global function GetWeaponBurnMods
global function InitMissileForRandomDriftForVortexLow
global function IsPilotShotgunWeapon
global function PlantStickyEntity
global function PlantStickyEntityThatBouncesOffWalls
global function PlantStickyEntityOnWorldThatBouncesOffWalls
global function PlantStickyGrenade
global function PlantSuperStickyGrenade
global function Player_DetonateSatchels
global function PROTO_CanPlayerDeployWeapon
global function ProximityCharge_PostFired_Init
global function RegenerateOffhandAmmoOverTime
global function ShotgunBlast
global function FireGenericBoltWithDrop
global function OnWeaponPrimaryAttack_GenericBoltWithDrop_Player
global function OnWeaponPrimaryAttack_GenericMissile_Player
global function OnWeaponActivate_updateViewmodelAmmo
global function TEMP_GetDamageFlagsFromProjectile
global function WeaponCanCrit
global function GiveEMPStunStatusEffects
global function GetPrimaryWeapons
global function GetSidearmWeapons
global function GetATWeapons
global function GetPlayerFromTitanWeapon
global function ChargeBall_Precache
global function ChargeBall_FireProjectile
global function ChargeBall_ChargeBegin
global function ChargeBall_ChargeEnd
global function ChargeBall_StopChargeEffects
global function ChargeBall_GetChargeTime

global function PlayerUsedOffhand
#if SERVER
global function SetPlayerCooldowns
global function ResetPlayerCooldowns
global function StoreOffhandData
#endif

global function GetRadiusDamageDataFromProjectile

#if DEV
global function DevPrintAllStatusEffectsOnEnt
#endif // #if DEV

#if SERVER
	global function ClusterRocket_Detonate
	global function PassThroughDamage
	global function PROTO_CleanupTrackedProjectiles
	global function PROTO_InitTrackedProjectile
	global function PROTO_PlayTrapLightEffect
	global function Satchel_PostFired_Init
	global function StartClusterExplosions
	global function TrapDestroyOnRoundEnd
	global function TrapExplodeOnDamage
	global function PROTO_DelayCooldown
	global function PROTO_FlakCannonMissiles
	global function GetBulletPassThroughTargets
	global function IsValidPassThroughTarget
	global function GivePlayerAmpedWeapon
	global function GivePlayerAmpedWeaponAndSetAsActive
	global function ReplacePlayerOffhand
	global function ReplacePlayerOrdnance
	global function DisableWeapons
	global function EnableWeapons
	global function WeaponAttackWave
	global function AddActiveThermiteBurn
	global function GetActiveThermiteBurnsWithinRadius
	global function OnWeaponPrimaryAttack_GenericBoltWithDrop_NPC
	global function OnWeaponPrimaryAttack_GenericMissile_NPC
	global function EMP_DamagedPlayerOrNPC
	global function EMP_FX
	global function GetWeaponDPS
	global function GetTTK
	global function GetWeaponModsFromDamageInfo
	global function Thermite_DamagePlayerOrNPCSounds
	global function AddThreatScopeColorStatusEffect
	global function RemoveThreatScopeColorStatusEffect
#endif //SERVER
#if CLIENT
	global function GlobalClientEventHandler
	global function UpdateViewmodelAmmo
	global function ServerCallback_AirburstIconUpdate
	global function ServerCallback_GuidedMissileDestroyed
	global function IsOwnerViewPlayerFullyADSed
#endif //CLIENT

global const PROJECTILE_PREDICTED = true
global const PROJECTILE_NOT_PREDICTED = false

global const PROJECTILE_LAG_COMPENSATED = true
global const PROJECTILE_NOT_LAG_COMPENSATED = false

const float EMP_SEVERITY_SLOWTURN = 0.35
const float EMP_SEVERITY_SLOWMOVE = 0.50
const float LASER_STUN_SEVERITY_SLOWTURN = 0.20
const float LASER_STUN_SEVERITY_SLOWMOVE = 0.30

const asset FX_EMP_BODY_HUMAN			= $"P_emp_body_human"
const asset FX_EMP_BODY_TITAN			= $"P_emp_body_titan"
const asset FX_VANGUARD_ENERGY_BODY_HUMAN		= $"P_monarchBeam_body_human"
const asset FX_VANGUARD_ENERGY_BODY_TITAN		= $"P_monarchBeam_body_titan"
const SOUND_EMP_REBOOT_SPARKS = "marvin_weld"
const FX_EMP_REBOOT_SPARKS = $"weld_spark_01_sparksfly"
const EMP_GRENADE_BEAM_EFFECT	= $"wpn_arc_cannon_beam"
const DRONE_REBOOT_TIME = 5.0
const GUNSHIP_REBOOT_TIME = 5.0

global struct RadiusDamageData
{
	int explosionDamage
	int explosionDamageHeavyArmor
	float explosionRadius
	float explosionInnerRadius
}

#if SERVER

global struct PopcornInfo
{
	string weaponName
	array weaponMods // could be array< string >
	int damageSourceId
	int count
	float delay
	float offset
	float range
	vector normal
	float duration
	int groupSize
	bool hasBase
}

struct ColorSwapStruct
{
	int statusEffectId
	entity weaponOwner
}

struct
{
	float titanRocketLauncherTitanDamageRadius
	float titanRocketLauncherOtherDamageRadius

	int activeThermiteBurnsManagedEnts
	array<ColorSwapStruct> colorSwapStatusEffects
} file

global int HOLO_PILOT_TRAIL_FX

global struct HoverSounds
{
	string liftoff_1p
	string liftoff_3p
	string hover_1p
	string hover_3p
	string descent_1p
	string descent_3p
	string landing_1p
	string landing_3p
}

#endif

function WeaponUtility_Init()
{
	level.weaponsPrecached <- {}

	// what classes can sticky thrown entities stick to?
	level.stickyClasses <- {}
	level.stickyClasses[ "worldspawn" ]			<- true
	level.stickyClasses[ "player" ]				<- true
	level.stickyClasses[ "prop_dynamic" ]		<- true
	level.stickyClasses[ "prop_script" ]		<- true
	level.stickyClasses[ "func_brush" ]			<- true
	level.stickyClasses[ "func_brush_lightweight" ]	<- true
	level.stickyClasses[ "phys_bone_follower" ]	<- true

	level.trapChainReactClasses <- {}
	level.trapChainReactClasses[ "mp_weapon_frag_grenade" ]			<- true
	level.trapChainReactClasses[ "mp_weapon_satchel" ]				<- true
	level.trapChainReactClasses[ "mp_weapon_proximity_mine" ] 		<- true
	level.trapChainReactClasses[ "mp_weapon_laser_mine" ]			<- true

	RegisterSignal( "Planted" )
	RegisterSignal( "EMP_FX" )
	RegisterSignal( "ArcStunned" )

	PrecacheParticleSystem( EMP_GRENADE_BEAM_EFFECT )
	PrecacheParticleSystem( FX_EMP_BODY_TITAN )
	PrecacheParticleSystem( FX_EMP_BODY_HUMAN )
	PrecacheParticleSystem( FX_VANGUARD_ENERGY_BODY_HUMAN )
	PrecacheParticleSystem( FX_VANGUARD_ENERGY_BODY_TITAN )
	PrecacheParticleSystem( FX_EMP_REBOOT_SPARKS )

	PrecacheImpactEffectTable( CLUSTER_ROCKET_FX_TABLE )

	#if SERVER
		AddDamageCallbackSourceID( eDamageSourceId.mp_titanweapon_triple_threat, TripleThreatGrenade_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_weapon_defender, Defender_DamagedPlayerOrNPC )
		//AddDamageCallbackSourceID( eDamageSourceId.mp_titanweapon_rocketeer_rocketstream, TitanRocketLauncher_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_weapon_smr, SMR_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_weapon_flak_rifle, PROTO_Flak_Rifle_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_titanweapon_stun_laser, VanguardEnergySiphon_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_weapon_grenade_emp, EMP_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId.mp_weapon_proximity_mine, EMP_DamagedPlayerOrNPC )
		AddDamageCallbackSourceID( eDamageSourceId[ CHARGE_TOOL ], EMP_DamagedPlayerOrNPC )
		if ( IsMultiplayer() )
			AddCallback_OnPlayerRespawned( PROTO_TrackedProjectile_OnPlayerRespawned )
		AddCallback_OnPlayerKilled( PAS_CooldownReduction_OnKill )
		AddCallback_OnPlayerGetsNewPilotLoadout( OnPlayerGetsNewPilotLoadout )
		AddCallback_OnPlayerKilled( OnPlayerKilled )

		file.activeThermiteBurnsManagedEnts = CreateScriptManagedEntArray()

		AddCallback_EntitiesDidLoad( EntitiesDidLoad )

		HOLO_PILOT_TRAIL_FX = PrecacheParticleSystem( $"P_ar_holopilot_trail" )

		PrecacheParticleSystem( $"wpn_laser_blink" )
		PrecacheParticleSystem( $"wpn_laser_blink_fast" )
		PrecacheParticleSystem( $"P_ordinance_icon_owner" )
	#endif
}

#if SERVER
void function EntitiesDidLoad()
{
#if SP
	// if we are going to do this, it should happen in the weapon, not globally
	//float titanRocketLauncherInnerRadius = expect float( GetWeaponInfoFileKeyField_Global( "mp_titanweapon_rocketeer_rocketstream", "explosion_inner_radius" ) )
	//float titanRocketLauncherOuterRadius = expect float( GetWeaponInfoFileKeyField_Global( "mp_titanweapon_rocketeer_rocketstream", "explosionradius" ) )
	//file.titanRocketLauncherTitanDamageRadius = titanRocketLauncherInnerRadius + ( ( titanRocketLauncherOuterRadius - titanRocketLauncherInnerRadius ) * 0.4 )
	//file.titanRocketLauncherOtherDamageRadius = titanRocketLauncherInnerRadius + ( ( titanRocketLauncherOuterRadius - titanRocketLauncherInnerRadius ) * 0.1 )
#endif
}
#endif

////////////////////////////////////////////////////////////////////

#if CLIENT
void function GlobalClientEventHandler( entity weapon, string name )
{
	if ( name == "ammo_update" )
		UpdateViewmodelAmmo( false, weapon )

	if ( name == "ammo_full" )
		UpdateViewmodelAmmo( true, weapon )
}

function UpdateViewmodelAmmo( bool forceFull, entity weapon )
{
	Assert( weapon != null ) // used to be: if ( weapon == null ) weapon = this.self

	if ( !IsValid( weapon ) )
		return
	if ( !IsLocalViewPlayer( weapon.GetWeaponOwner() ) )
		return

	int bodyGroupCount = weapon.GetWeaponSettingInt( eWeaponVar.bodygroup_ammo_index_count )
	if ( bodyGroupCount <= 0 )
		return

	int rounds = weapon.GetWeaponPrimaryClipCount()
	int maxRoundsForClipSize = weapon.GetWeaponPrimaryClipCountMax()
	int maxRoundsForBodyGroup = (bodyGroupCount - 1)
	int maxRounds = minint( maxRoundsForClipSize, maxRoundsForBodyGroup )

	if ( forceFull || (rounds > maxRounds) )
		rounds = maxRounds

	//printt( "ROUNDS:", rounds, "/", maxRounds )
	weapon.SetViewmodelAmmoModelIndex( rounds )
}
#endif // #if CLIENT

void function OnWeaponActivate_updateViewmodelAmmo( entity weapon )
{
#if CLIENT
	UpdateViewmodelAmmo( false, weapon )
#endif // #if CLIENT
}

#if SERVER
//////////////////WEAPON DAMAGE CALLBACKS/////////////////////////////////////////
void function TripleThreatGrenade_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	if ( !IsValid( ent ) )
		return

	if ( ent.GetClassName() == "grenade_frag" )
		return

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_DOOMED_HEALTH_LOSS )
		return

	vector damagePosition = DamageInfo_GetDamagePosition( damageInfo )

	vector entOrigin = ent.GetOrigin()
	vector entCenter = ent.GetWorldSpaceCenter()
	float distanceToOrigin = Distance( entOrigin, damagePosition )
	float distanceToCenter = Distance( entCenter, damagePosition )

	vector normal = Vector( 0, 0, 1 )
	entity inflictor = DamageInfo_GetInflictor( damageInfo )
	if ( IsValid( inflictor.s ) )
	{
		if ( "collisionNormal" in inflictor.s )
			normal = expect vector( inflictor.s.collisionNormal )
	}

	local zDifferenceOrigin = deg_cos( DegreesToTarget( entOrigin, normal, damagePosition ) ) * distanceToOrigin
	local zDifferenceTop = deg_cos( DegreesToTarget( entCenter, normal, damagePosition ) ) * distanceToCenter - (entCenter.z - entOrigin.z)

	float zDamageDiff
	//Full damage if explosion is between Origin or Center.
	if ( zDifferenceOrigin > 0 && zDifferenceTop < 0 )
		zDamageDiff = 1.0
	else if ( zDifferenceTop > 0 )
		zDamageDiff = GraphCapped( zDifferenceTop, 0.0, 32.0, 1.0, 0.0 )
	else
		zDamageDiff = GraphCapped( zDifferenceOrigin, 0.0, -32.0, 1.0, 0.0 )

	DamageInfo_ScaleDamage( damageInfo, zDamageDiff )
}

void function Defender_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	if ( !IsValid( ent ) )
		return

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_DOOMED_HEALTH_LOSS )
		return

	local damage = Vortex_HandleElectricDamage( ent, DamageInfo_GetAttacker( damageInfo ), DamageInfo_GetDamage( damageInfo ), DamageInfo_GetWeapon( damageInfo ) )
	DamageInfo_SetDamage( damageInfo, damage )
}

/*
void function TitanRocketLauncher_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	Assert( IsSingleplayer() )

	if ( !IsValid( ent ) )
		return

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_DOOMED_HEALTH_LOSS )
		return

	vector damagePosition = DamageInfo_GetDamagePosition( damageInfo )

	if ( ent == DamageInfo_GetAttacker( damageInfo ) )
		return

	if ( ent.IsTitan() )
	{
		vector entOrigin = ent.GetOrigin()
		if ( Distance( damagePosition, entOrigin ) > file.titanRocketLauncherTitanDamageRadius )
			DamageInfo_SetDamage( damageInfo, 0 )
	}
	else if ( IsHumanSized( ent ) )
	{
		if ( Distance( damagePosition, ent.GetOrigin() ) > file.titanRocketLauncherOtherDamageRadius )
			DamageInfo_SetDamage( damageInfo, 0 )
	}
}
*/

void function SMR_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	//Hack - JFS ( The explosion radius is too small on the SMR to deal splash damage to pilots on a Titan. )
	if ( !IsValid( ent ) )
		return

	if ( !ent.IsTitan() )
		return

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_DOOMED_HEALTH_LOSS )
		return

	entity attacker = DamageInfo_GetAttacker( damageInfo )

	if ( IsValid( attacker ) && attacker.IsPlayer() && attacker.GetTitanSoulBeingRodeoed() == ent.GetTitanSoul() )
		attacker.TakeDamage( 30, attacker, attacker, { scriptType = DF_GIB | DF_EXPLOSION, damageSourceId = eDamageSourceId.mp_weapon_smr, weapon = DamageInfo_GetWeapon( damageInfo ) } )
}


void function PROTO_Flak_Rifle_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	entity attacker = DamageInfo_GetAttacker( damageInfo )

	if ( !IsValid( ent ) || !IsValid( attacker ) )
		return

	if ( attacker == ent )
		DamageInfo_ScaleDamage( damageInfo, 0.5 )
}

function EngineerRocket_DamagedPlayerOrNPC( ent, damageInfo )
{
	expect entity( ent )

	entity attacker = DamageInfo_GetAttacker( damageInfo )

	if ( !IsValid( ent ) || !IsValid( attacker ) )
		return

	if ( attacker == ent )
		DamageInfo_SetDamage( damageInfo, 10 )
}
///////////////////////////////////////////////////////////////////////

#endif // SERVER

vector function ApplyVectorSpread( vector vecShotDirection, float spreadDegrees, float bias = 1.0 )
{
	vector angles = VectorToAngles( vecShotDirection )
	vector vecUp = AnglesToUp( angles )
	vector vecRight = AnglesToRight( angles )

	float sinDeg = deg_sin( spreadDegrees / 2.0 )

	// get circular gaussian spread
	float x
	float y
	float z

	if ( bias > 1.0 )
		bias = 1.0
	else if ( bias < 0.0 )
		bias = 0.0

	// code gets these values from cvars ai_shot_bias_min & ai_shot_bias_max
	float shotBiasMin = -1.0
	float shotBiasMax = 1.0

	// 1.0 gaussian, 0.0 is flat, -1.0 is inverse gaussian
	float shotBias = ( ( shotBiasMax - shotBiasMin ) * bias ) + shotBiasMin
	float flatness = ( fabs(shotBias) * 0.5 )

	while ( true )
	{
		x = RandomFloatRange( -1.0, 1.0 ) * flatness + RandomFloatRange( -1.0, 1.0 ) * (1 - flatness)
		y = RandomFloatRange( -1.0, 1.0 ) * flatness + RandomFloatRange( -1.0, 1.0 ) * (1 - flatness)
		if ( shotBias < 0 )
		{
			x = ( x >= 0 ) ? 1.0 - x : -1.0 - x
			y = ( y >= 0 ) ? 1.0 - y : -1.0 - y
		}
		z = x * x + y * y

		if ( z <= 1 )
			break
	}

	vector addX = vecRight * ( x * sinDeg )
	vector addY = vecUp * ( y * sinDeg )
	vector m_vecResult = vecShotDirection + addX + addY

	return m_vecResult
}


float function DegreesToTarget( vector origin, vector forward, vector targetPos )
{
	vector dirToTarget = targetPos - origin
	dirToTarget = Normalize( dirToTarget )
	float dot = DotProduct( forward, dirToTarget )
	float degToTarget = (acos( dot ) * 180 / PI)

	return degToTarget
}

function ShotgunBlast( entity weapon, vector pos, vector dir, int numBlasts, int damageType, float damageScaler = 1.0, float ornull maxAngle = null, float ornull maxDistance = null )
{
	Assert( numBlasts > 0 )
	int numBlastsOriginal = numBlasts
	entity owner = weapon.GetWeaponOwner()

	/*
	Debug ConVars:
		visible_ent_cone_debug_duration_client - Set to non-zero to see debug output
		visible_ent_cone_debug_duration_server - Set to non-zero to see debug output
		visible_ent_cone_debug_draw_radius - Size of trace endpoint debug draw
	*/

	if ( maxDistance == null )
		maxDistance	= weapon.GetMaxDamageFarDist()
	expect float( maxDistance )

	if ( maxAngle == null )
		maxAngle = owner.GetAttackSpreadAngle() * 0.5
	expect float( maxAngle )

	array<entity> ignoredEntities 	= [ owner ]
	int traceMask 					= TRACE_MASK_SHOT
	int visConeFlags				= VIS_CONE_ENTS_TEST_HITBOXES | VIS_CONE_ENTS_CHECK_SOLID_BODY_HIT | VIS_CONE_ENTS_APPOX_CLOSEST_HITBOX | VIS_CONE_RETURN_HIT_VORTEX

	entity antilagPlayer
	if ( owner.IsPlayer() )
	{
		if ( owner.IsPhaseShifted() )
			return;

		antilagPlayer = owner
	}

	//JFS - Bug 198500
	Assert( maxAngle > 0.0, "JFS returning out at this instance. We need to investigate when a valid mp_titanweapon_laser_lite weapon returns 0 spread")
	if ( maxAngle == 0.0 )
		return

	array<VisibleEntityInCone> results = FindVisibleEntitiesInCone( pos, dir, maxDistance, (maxAngle * 1.1), ignoredEntities, traceMask, visConeFlags, antilagPlayer, weapon )
	foreach ( result in results )
	{
		float angleToHitbox = 0.0
		if ( !result.solidBodyHit )
			angleToHitbox = DegreesToTarget( pos, dir, result.approxClosestHitboxPos )

		numBlasts -= ShotgunBlastDamageEntity( weapon, pos, dir, result, angleToHitbox, maxAngle, numBlasts, damageType, damageScaler )
		if ( numBlasts <= 0 )
			break
	}

	//Something in the TakeDamage above is triggering the weapon owner to become invalid.
	owner = weapon.GetWeaponOwner()
	if ( !IsValid( owner ) )
		return

	// maxTracer limit set in /r1dev/src/game/client/c_player.h
	const int MAX_TRACERS = 16
	bool didHitAnything = ((numBlastsOriginal - numBlasts) != 0)
	bool doTraceBrushOnly = (!didHitAnything)
	if ( numBlasts > 0 )
		weapon.FireWeaponBullet_Special( pos, dir, minint( numBlasts, MAX_TRACERS ), damageType, false, false, true, false, false, false, doTraceBrushOnly )
}


const SHOTGUN_ANGLE_MIN_FRACTION = 0.1;
const SHOTGUN_ANGLE_MAX_FRACTION = 1.0;
const SHOTGUN_DAMAGE_SCALE_AT_MIN_ANGLE = 0.8;
const SHOTGUN_DAMAGE_SCALE_AT_MAX_ANGLE = 0.1;

int function ShotgunBlastDamageEntity( entity weapon, vector barrelPos, vector barrelVec, VisibleEntityInCone result, float angle, float maxAngle, int numPellets, int damageType, float damageScaler )
{
	entity target = result.ent

	//The damage scaler is currently only > 1 for the Titan Shotgun alt fire.
	if ( !target.IsTitan() && damageScaler > 1 )
		damageScaler = max( damageScaler * 0.4, 1.5 )

	entity owner = weapon.GetWeaponOwner()
	// Ent in cone not valid
	if ( !IsValid( target ) || !IsValid( owner ) )
		return 0

	// Fire fake bullet towards entity for visual purposes only
	vector hitLocation = result.visiblePosition
	vector vecToEnt = ( hitLocation - barrelPos )
	vecToEnt.Norm()
	if ( Length( vecToEnt ) == 0 )
		vecToEnt = barrelVec

	// This fires a fake bullet that doesn't do any damage. Currently it triggeres a damage callback with 0 damage which is bad.
	weapon.FireWeaponBullet_Special( barrelPos, vecToEnt, 1, damageType, true, true, true, false, false, false, false ) // fires perfect bullet with no antilag and no spread

#if SERVER
	// Determine how much damage to do based on distance
	float distanceToTarget = Distance( barrelPos, hitLocation )

	if ( !result.solidBodyHit ) // non solid hits take 1 blast more
		distanceToTarget += 130

	int extraMods = result.extraMods
	float damageAmount = CalcWeaponDamage( owner, target, weapon, distanceToTarget, extraMods )

	// vortex needs to scale damage based on number of rounds absorbed
	string className = weapon.GetWeaponClassName()
	if ( (className == "mp_titanweapon_vortex_shield") || (className == "mp_titanweapon_vortex_shield_ion") || (className == "mp_titanweapon_heat_shield") )
	{
		damageAmount *= numPellets
		//printt( "scaling vortex hitscan output damage by", numPellets, "pellets for", weaponNearDamageTitan, "damage vs titans" )
	}

	float coneScaler = 1.0
	//if ( angle > 0 )
	//	coneScaler = GraphCapped( angle, (maxAngle * SHOTGUN_ANGLE_MIN_FRACTION), (maxAngle * SHOTGUN_ANGLE_MAX_FRACTION), SHOTGUN_DAMAGE_SCALE_AT_MIN_ANGLE, SHOTGUN_DAMAGE_SCALE_AT_MAX_ANGLE )

	// Calculate the final damage abount to inflict on the target. Also scale it by damageScaler which may have been passed in by script ( used by alt fire mode on titan shotgun to fire multiple shells )
	float finalDamageAmount = damageAmount * coneScaler * damageScaler
	//printt( "angle:", angle, "- coneScaler:", coneScaler, "- damageAmount:", damageAmount, "- damageScaler:", damageScaler, "  = finalDamageAmount:", finalDamageAmount )

	// Calculate impulse force to apply based on damage
	int maxImpulseForce = expect int( weapon.GetWeaponInfoFileKeyField( "impulse_force" ) )
	float impulseForce = float( maxImpulseForce ) * coneScaler * damageScaler
	vector impulseVec = barrelVec * impulseForce

	int damageSourceID = weapon.GetDamageSourceID()

	//
	float critScale = weapon.GetWeaponSettingFloat( eWeaponVar.critical_hit_damage_scale )
	target.TakeDamage( finalDamageAmount, owner, weapon, { origin = hitLocation, force = impulseVec, scriptType = damageType, damageSourceId = damageSourceID, weapon = weapon, hitbox = result.visibleHitbox, criticalHitScale = critScale } )

	//printt( "-----------" )
	//printt( "    distanceToTarget:", distanceToTarget )
	//printt( "    damageAmount:", damageAmount )
	//printt( "    coneScaler:", coneScaler )
	//printt( "    impulseForce:", impulseForce )
	//printt( "    impulseVec:", impulseVec.x + ", " + impulseVec.y + ", " + impulseVec.z )
	//printt( "        finalDamageAmount:", finalDamageAmount )
	//PrintTable( result )
#endif // #if SERVER

	return 1
}

int function FireGenericBoltWithDrop( entity weapon, WeaponPrimaryAttackParams attackParams, bool isPlayerFired )
{
#if CLIENT
	if ( !weapon.ShouldPredictProjectiles() )
		return 1
#endif // #if CLIENT

	weapon.EmitWeaponNpcSound( LOUD_WEAPON_AI_SOUND_RADIUS_MP, 0.2 )

	const float PROJ_SPEED_SCALE = 1
	const float PROJ_GRAVITY = 1
	int damageFlags = weapon.GetWeaponDamageFlags()
	entity bolt = weapon.FireWeaponBolt( attackParams.pos, attackParams.dir, PROJ_SPEED_SCALE, damageFlags, damageFlags, isPlayerFired, 0 )
	if ( bolt != null )
	{
		bolt.kv.gravity = PROJ_GRAVITY
		bolt.kv.rendercolor = "0 0 0"
		bolt.kv.renderamt = 0
		bolt.kv.fadedist = 1
	}

	return 1
}
var function OnWeaponPrimaryAttack_GenericBoltWithDrop_Player( entity weapon, WeaponPrimaryAttackParams attackParams )
{
	return FireGenericBoltWithDrop( weapon, attackParams, true )
}

var function OnWeaponPrimaryAttack_EPG( entity weapon, WeaponPrimaryAttackParams attackParams )
{
	entity missile = weapon.FireWeaponMissile( attackParams.pos, attackParams.dir, 1, damageTypes.largeCaliberExp, damageTypes.largeCaliberExp, false, PROJECTILE_NOT_PREDICTED )
	if ( missile )
	{
		EmitSoundOnEntity( missile, "Weapon_Sidwinder_Projectile" )
		missile.InitMissileForRandomDriftFromWeaponSettings( attackParams.pos, attackParams.dir )
	}

	return missile
}

#if SERVER
var function OnWeaponPrimaryAttack_GenericBoltWithDrop_NPC( entity weapon, WeaponPrimaryAttackParams attackParams )
{
	return FireGenericBoltWithDrop( weapon, attackParams, false )
}
#endif // #if SERVER


var function OnWeaponPrimaryAttack_GenericMissile_Player( entity weapon, WeaponPrimaryAttackParams attackParams )
{
	weapon.EmitWeaponNpcSound( LOUD_WEAPON_AI_SOUND_RADIUS_MP, 0.2 )

	entity weaponOwner = weapon.GetWeaponOwner()
	vector bulletVec = ApplyVectorSpread( attackParams.dir, weaponOwner.GetAttackSpreadAngle() - 1.0 )
	attackParams.dir = bulletVec

	if ( IsServer() || weapon.ShouldPredictProjectiles() )
	{
		entity missile = weapon.FireWeaponMissile( attackParams.pos, attackParams.dir, 1.0, weapon.GetWeaponDamageFlags(), weapon.GetWeaponDamageFlags(), false, PROJECTILE_PREDICTED )
		if ( missile )
		{
			missile.InitMissileForRandomDriftFromWeaponSettings( attackParams.pos, attackParams.dir )
		}
	}
}

#if SERVER
var function OnWeaponPrimaryAttack_GenericMissile_NPC( entity weapon, WeaponPrimaryAttackParams attackParams )
{
	weapon.EmitWeaponNpcSound( LOUD_WEAPON_AI_SOUND_RADIUS_MP, 0.2 )

	entity missile = weapon.FireWeaponMissile( attackParams.pos, attackParams.dir, 1.0, weapon.GetWeaponDamageFlags(), weapon.GetWeaponDamageFlags(), true, PROJECTILE_NOT_PREDICTED )
	if ( missile )
	{
		missile.InitMissileForRandomDriftFromWeaponSettings( attackParams.pos, attackParams.dir )
	}
}
#endif // #if SERVER

bool function PlantStickyEntityOnWorldThatBouncesOffWalls( entity ent, table collisionParams, float bounceDot )
{
	entity hitEnt = expect entity( collisionParams.hitEnt )
	if ( hitEnt && ( hitEnt.IsWorld() || hitEnt.HasPusherRootParent() ) )
	{
		float dot = expect vector( collisionParams.normal ).Dot( Vector( 0, 0, 1 ) )

		if ( dot < bounceDot )
			return false

		return PlantStickyEntity( ent, collisionParams )
	}

	return false
}

bool function PlantStickyEntityThatBouncesOffWalls( entity ent, table collisionParams, float bounceDot )
{
	if ( expect entity( collisionParams.hitEnt ) == GetEntByIndex( 0 ) )
	{
		// Satchel hit the world
		float dot = expect vector( collisionParams.normal ).Dot( Vector( 0, 0, 1 ) )

		if ( dot < bounceDot )
			return false
	}

	return PlantStickyEntity( ent, collisionParams )
}


bool function PlantStickyEntity( entity ent, table collisionParams, vector angleOffset = <0.0, 0.0, 0.0> )
{
	if ( !EntityShouldStick( ent, expect entity( collisionParams.hitEnt ) ) )
		return false

	// Don't allow parenting to another "sticky" entity to prevent them parenting onto each other
	if ( collisionParams.hitEnt.IsProjectile() )
		return false

	// Update normal from last bouce so when it explodes it can orient the effect properly

	vector plantAngles = AnglesCompose( VectorToAngles( collisionParams.normal ), angleOffset )
	vector plantPosition = expect vector( collisionParams.pos )

	if ( !LegalOrigin( plantPosition ) )
		return false

	#if SERVER
		ent.SetAbsOrigin( plantPosition )
		ent.SetAbsAngles( plantAngles )
		ent.proj.isPlanted = true
	#else
		ent.SetOrigin( plantPosition )
		ent.SetAngles( plantAngles )
	#endif
	ent.SetVelocity( Vector( 0, 0, 0 ) )

	//printt( " - Hitbox is:", collisionParams.hitbox, " IsWorld:", collisionParams.hitEnt )
	if ( !collisionParams.hitEnt.IsWorld() )
	{
		if ( !ent.IsMarkedForDeletion() && !collisionParams.hitEnt.IsMarkedForDeletion() )
		{
			if ( collisionParams.hitbox > 0 )
				ent.SetParentWithHitbox( collisionParams.hitEnt, collisionParams.hitbox, true )

			// Hit a func_brush
			else
				ent.SetParent( collisionParams.hitEnt )

			if ( collisionParams.hitEnt.IsPlayer() )
			{
				thread HandleDisappearingParent( ent, expect entity( collisionParams.hitEnt ) )
			}
		}
	}
	else
	{
		ent.SetVelocity( Vector( 0, 0, 0 ) )
		ent.StopPhysics()
	}
	#if CLIENT
	if ( ent instanceof C_BaseGrenade )
	#else
	if ( ent instanceof CBaseGrenade )
	#endif
		ent.MarkAsAttached()

	ent.Signal( "Planted" )

	return true
}

bool function PlantStickyGrenade( entity ent, vector pos, vector normal, entity hitEnt, int hitbox, float depth = 0.0, bool allowBounce = true, bool allowEntityStick = true )
{
	if ( ent.GetTeam() == hitEnt.GetTeam() )
		return false

	if ( ent.IsMarkedForDeletion() || hitEnt.IsMarkedForDeletion() )
		return false

	vector plantAngles = VectorToAngles( normal )
	vector plantPosition = pos + normal * -depth

	if ( !allowBounce )
		ent.SetVelocity( Vector( 0, 0, 0 ) )

	if ( !LegalOrigin( plantPosition ) )
		return false

	#if SERVER
		ent.SetAbsOrigin( plantPosition )
		ent.SetAbsAngles( plantAngles )
		ent.proj.isPlanted = true
	#else
		ent.SetOrigin( plantPosition )
		ent.SetAngles( plantAngles )
	#endif

	if ( !hitEnt.IsWorld() && (!hitEnt.IsTitan() || !allowEntityStick) )
		return false

	// SetOrigin might be causing the ent to get markedForDeletion.
	if ( ent.IsMarkedForDeletion() )
		return false

	ent.SetVelocity( Vector( 0, 0, 0 ) )

	if ( hitEnt.IsWorld() )
	{
		ent.SetParent( hitEnt, "", true )
		ent.StopPhysics()
	}
	else
	{
		if ( hitbox > 0 )
			ent.SetParentWithHitbox( hitEnt, hitbox, true )
		else // Hit a func_brush
			ent.SetParent( hitEnt )

		if ( hitEnt.IsPlayer() )
		{
			thread HandleDisappearingParent( ent, hitEnt )
		}
	}

	#if CLIENT
		if ( ent instanceof C_BaseGrenade )
			ent.MarkAsAttached()
	#else
		if ( ent instanceof CBaseGrenade )
			ent.MarkAsAttached()
	#endif

	return true
}


bool function PlantSuperStickyGrenade( entity ent, vector pos, vector normal, entity hitEnt, int hitbox )
{
	if ( ent.GetTeam() == hitEnt.GetTeam() )
		return false

	vector plantAngles = VectorToAngles( normal )
	vector plantPosition = pos

	if ( !LegalOrigin( plantPosition ) )
		return false

	#if SERVER
		ent.SetAbsOrigin( plantPosition )
		ent.SetAbsAngles( plantAngles )
		ent.proj.isPlanted = true
	#else
		ent.SetOrigin( plantPosition )
		ent.SetAngles( plantAngles )
	#endif

	if ( !hitEnt.IsWorld() && !hitEnt.IsPlayer() && !hitEnt.IsNPC() )
		return false

	ent.SetVelocity( Vector( 0, 0, 0 ) )

	if ( hitEnt.IsWorld() )
	{
		ent.StopPhysics()
	}
	else
	{
		if ( !ent.IsMarkedForDeletion() && !hitEnt.IsMarkedForDeletion() )
		{
			if ( hitbox > 0 )
				ent.SetParentWithHitbox( hitEnt, hitbox, true )
			else // Hit a func_brush
				ent.SetParent( hitEnt )

			if ( hitEnt.IsPlayer() )
			{
				thread HandleDisappearingParent( ent, hitEnt )
			}
		}
	}

	#if CLIENT
		if ( ent instanceof C_BaseGrenade )
			ent.MarkAsAttached()
	#else
		if ( ent instanceof CBaseGrenade )
			ent.MarkAsAttached()
	#endif

	return true
}

#if SERVER
void function HandleDisappearingParent( entity ent, entity parentEnt )
{
	parentEnt.EndSignal( "OnDeath" )
	ent.EndSignal( "OnDestroy" )

	OnThreadEnd(
	function() : ( ent )
		{
			ent.ClearParent()
		}
	)

	parentEnt.WaitSignal( "StartPhaseShift" )
}
#else
void function HandleDisappearingParent( entity ent, entity parentEnt )
{
	parentEnt.EndSignal( "OnDeath" )
	ent.EndSignal( "OnDestroy" )

	parentEnt.WaitSignal( "StartPhaseShift" )

	ent.ClearParent()
}
#endif

bool function EntityShouldStick( entity stickyEnt, entity hitent )
{
	if ( !EntityCanHaveStickyEnts( stickyEnt, hitent ) )
		return false

	if ( hitent == stickyEnt )
		return false

	return true
}

bool function EntityCanHaveStickyEnts( entity stickyEnt, entity ent )
{
	if ( !IsValid( ent ) )
		return false

	if ( ent.GetModelName() == $"" ) // valid case, other projectiles bullets, etc.. sometimes have no model
		return false;

	local entClassname
	if ( IsServer() )
		entClassname = ent.GetClassName()
	else
		entClassname = ent.GetSignifierName() // Can return null

	if ( !( entClassname in level.stickyClasses ) && !ent.IsNPC() )
		return false

	#if CLIENT
	if ( stickyEnt instanceof C_Projectile )
	#else
	if ( stickyEnt instanceof CProjectile )
	#endif
	{
	string weaponClassName = stickyEnt.ProjectileGetWeaponClassName()
	local stickPlayer = GetWeaponInfoFileKeyField_Global( weaponClassName, "stick_pilot" )
	local stickTitan = GetWeaponInfoFileKeyField_Global( weaponClassName, "stick_titan" )
	local stickNPC = GetWeaponInfoFileKeyField_Global( weaponClassName, "stick_npc" )

	if ( ent.IsTitan() && stickTitan )
		return true
	else if ( ent.IsPlayer() && stickPlayer )
		return true
	else if ( ent.IsNPC() && stickNPC )
		return true

	// not pilots
	if ( ent.IsPlayer() && !ent.IsTitan() )
		return false
	}

	return true
}

#if SERVER
// shared with the vortex script which also needs to create satchels
function Satchel_PostFired_Init( entity satchel, entity player )
{
	satchel.proj.onlyAllowSmartPistolDamage = false
	thread SatchelThink( satchel, player )
}

function SatchelThink( entity satchel, entity player )
{
	player.EndSignal("OnDestroy")
	satchel.EndSignal("OnDestroy")

	int satchelHealth = 15
	thread TrapExplodeOnDamage( satchel, satchelHealth )

	#if DEV
		// temp HACK for FX to use to figure out the size of the particle to play
		if ( Flag( "ShowExplosionRadius" ) )
			thread ShowExplosionRadiusOnExplode( satchel )
	#endif

	player.EndSignal( "OnDeath" )

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

	WaitForever()
}

#endif // SERVER

function ProximityCharge_PostFired_Init( entity proximityMine, entity player )
{
	#if SERVER
	proximityMine.proj.onlyAllowSmartPistolDamage = false
	#endif
}

function DetonateAllPlantedExplosives( entity player )
{
	// ToDo: Could use Player_DetonateSatchels but it only tracks satchels, not laser mines.

	// Detonate all explosives - satchels and laser mines are also frag grenades in disguise
	array<entity> grenades = GetProjectileArrayEx( "grenade_frag", TEAM_ANY, TEAM_ANY, Vector( 0, 0, 0 ), -1 )
	foreach( grenade in grenades )
	{
		if ( grenade.GetOwner() != player )
			continue

		if ( grenade.ProjectileGetDamageSourceID() != eDamageSourceId.mp_weapon_satchel && grenade.ProjectileGetDamageSourceID() != eDamageSourceId.mp_weapon_proximity_mine )
			continue

		thread ExplodePlantedGrenadeAfterDelay( grenade, RandomFloatRange( 0.75, 0.95 ) )
	}
}

function ExplodePlantedGrenadeAfterDelay( entity grenade, float delay )
{
	grenade.EndSignal( "OnDeath" )
	grenade.EndSignal( "OnDestroy" )

	float endTime = Time() + delay

	while ( Time() < endTime )
	{
		EmitSoundOnEntity( grenade, DEFAULT_WARNING_SFX	)
		wait 0.1
	}

	grenade.GrenadeExplode( grenade.GetForwardVector() )
}

function Player_DetonateSatchels( entity player )
{
	#if SERVER
	Assert( IsServer() )

	array<entity> traps = GetScriptManagedEntArray( player.s.activeTrapArrayId )
	traps.sort( CompareCreationReverse )
	foreach ( index, satchel in traps )
	{
		if ( IsValidSatchel( satchel ) )
		{

			thread PROTO_ExplodeAfterDelay( satchel, index * 0.25 )
		}
	}
	#endif
}

function IsValidSatchel( entity satchel )
{
	#if SERVER
	if ( satchel.ProjectileGetWeaponClassName() != "mp_weapon_satchel" )
		return false

	if ( satchel.e.isDisabled == true )
		return false

	return true
	#endif
}

#if SERVER
function PROTO_ExplodeAfterDelay( entity satchel, float delay )
{
	satchel.EndSignal( "OnDestroy" )

	#if MP
	while ( !satchel.proj.isPlanted )
	{
		WaitFrame()
	}
	#endif

	wait delay

	satchel.GrenadeExplode( satchel.GetForwardVector() )
}
#endif


#if DEV
function ShowExplosionRadiusOnExplode( entity ent )
{
	ent.WaitSignal( "OnDestroy" )

	float innerRadius = expect float( ent.GetWeaponInfoFileKeyField( "explosion_inner_radius" ) )
	float outerRadius = expect float( ent.GetWeaponInfoFileKeyField( "explosionradius" ) )

	vector org = ent.GetOrigin()
	vector angles = Vector( 0, 0, 0 )
	thread DebugDrawCircle( org, angles, innerRadius, 255, 255, 51, true, 3.0 )
	thread DebugDrawCircle( org, angles, outerRadius, 255, 255, 255, true, 3.0 )
}
#endif // DEV

#if SERVER
// shared between nades, satchels and laser mines
void function TrapExplodeOnDamage( entity trapEnt, int trapEntHealth = 50, float waitMin = 0.0, float waitMax = 0.0 )
{
	Assert( IsValid( trapEnt ), "Given trapEnt entity is not valid, fired from: " + trapEnt.ProjectileGetWeaponClassName() )
	EndSignal( trapEnt, "OnDestroy" )

	trapEnt.SetDamageNotifications( true )
	var results //Really should be a struct
	entity attacker
	entity inflictor

	while ( true )
	{
		if ( !IsValid( trapEnt ) )
			return

		results = WaitSignal( trapEnt, "OnDamaged" )
		attacker = expect entity( results.activator )
		inflictor = expect entity( results.inflictor )

		if ( IsValid( inflictor ) && inflictor == trapEnt )
			continue

		bool shouldDamageTrap = false
		if ( IsValid( attacker ) )
		{
			if ( trapEnt.proj.onlyAllowSmartPistolDamage )
			{
				if ( attacker.IsNPC() || attacker.IsPlayer() )
				{
					entity attackerWeapon = attacker.GetActiveWeapon()
					if ( IsValid( attackerWeapon ) && WeaponIsSmartPistolVariant( attackerWeapon ) )
						shouldDamageTrap = true
				}
			}
			else
			{
				if ( trapEnt.GetTeam() == attacker.GetTeam() )
				{
					if ( trapEnt.GetOwner() != attacker )
						shouldDamageTrap = false
					else
						shouldDamageTrap = !ProjectileIgnoresOwnerDamage( trapEnt )
				}
				else
				{
					shouldDamageTrap = true
				}
			}
		}

		if ( shouldDamageTrap )
			trapEntHealth -= int ( results.value ) //TODO: This returns float even though it feels like it should return int

		if ( trapEntHealth <= 0 )
			break
	}

	if ( !IsValid( trapEnt ) )
		return

	inflictor = expect entity( results.inflictor ) // waiting on code feature to pass inflictor with OnDamaged signal results table

	if ( waitMin >= 0 && waitMax > 0 )
	{
		float waitTime = RandomFloatRange( waitMin, waitMax )

		if ( waitTime > 0 )
			wait waitTime
	}
	else if ( IsValid( inflictor ) && (inflictor.IsProjectile() || (inflictor instanceof CWeaponX)) )
	{
		int dmgSourceID
		if ( inflictor.IsProjectile() )
			dmgSourceID = inflictor.ProjectileGetDamageSourceID()
		else
			dmgSourceID = inflictor.GetDamageSourceID()

		string inflictorClass = GetObitFromDamageSourceID( dmgSourceID )

		if ( inflictorClass in level.trapChainReactClasses )
		{
			// chain reaction delay
			Wait( RandomFloatRange( 0.2, 0.275 ) )
		}
	}

	if ( !IsValid( trapEnt ) )
		return

	if ( IsValid( attacker ) )
	{
		if ( attacker.IsPlayer() )
		{
			AddPlayerScoreForTrapDestruction( attacker, trapEnt )
			trapEnt.SetOwner( attacker )
		}
		else
		{
			entity lastAttacker = GetLastAttacker( attacker )
			if ( IsValid( lastAttacker ) )
			{
				// for chain explosions, figure out the attacking player that started the chain
				trapEnt.SetOwner( lastAttacker )
			}
		}
	}

	trapEnt.GrenadeExplode( trapEnt.GetForwardVector() )
}

bool function ProjectileIgnoresOwnerDamage( entity projectile )
{
	var ignoreOwnerDamage = projectile.ProjectileGetWeaponInfoFileKeyField( "projectile_ignore_owner_damage" )

	if ( ignoreOwnerDamage == null )
		return false

	return ignoreOwnerDamage == 1
}

bool function WeaponIsSmartPistolVariant( entity weapon )
{
	var isSP = weapon.GetWeaponInfoFileKeyField( "is_smart_pistol" )

	//printt( isSP )

	if ( isSP == null )
		return false

	return ( isSP == 1 )
}

// NOTE: we should stop using this
function TrapDestroyOnRoundEnd( entity player, entity trapEnt )
{
	trapEnt.EndSignal( "OnDestroy" )

	svGlobal.levelEnt.WaitSignal( "ClearedPlayers" )

	if ( IsValid( trapEnt ) )
		trapEnt.Destroy()
}

function AddPlayerScoreForTrapDestruction( entity player, entity trapEnt )
{
	// don't get score for killing your own trap
	if ( "originalOwner" in trapEnt.s && trapEnt.s.originalOwner == player )
		return

	string trapClass = trapEnt.ProjectileGetWeaponClassName()
	if ( trapClass == "" )
		return

	string scoreEvent
	if ( trapClass == "mp_weapon_satchel" )
		scoreEvent = "Destroyed_Satchel"
	else if ( trapClass == "mp_weapon_proximity_mine" )
		scoreEvent = "Destored_Proximity_Mine"

	if ( scoreEvent == "" )
		return

	AddPlayerScore( player, scoreEvent, trapEnt )
}

table function GetBulletPassThroughTargets( entity attacker, WeaponBulletHitParams hitParams )
{
	//HACK requires code later
	table passThroughInfo = {
		endPos = null
		targetArray = []
	}

	TraceResults result
	array<entity> ignoreEnts = [ attacker, hitParams.hitEnt ]

	while ( true )
	{
		vector vec = ( hitParams.hitPos - hitParams.startPos ) * 1000
		ArrayRemoveInvalid( ignoreEnts )
		result = TraceLine( hitParams.startPos, vec, ignoreEnts, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_NONE )

		if ( result.hitEnt == svGlobal.worldspawn )
			break

		ignoreEnts.append( result.hitEnt )

		if ( IsValidPassThroughTarget( result.hitEnt, attacker ) )
			passThroughInfo.targetArray.append( result.hitEnt )
	}
	passThroughInfo.endPos = result.endPos

	return passThroughInfo
}
#endif // SERVER

bool function WeaponCanCrit( entity weapon )
{
	// player sometimes has no weapon during titan exit, mantle, etc...
	if ( !weapon )
		return false

	return weapon.GetWeaponSettingBool( eWeaponVar.critical_hit )
}


#if SERVER
bool function IsValidPassThroughTarget( entity target, entity attacker )
{
	//Tied to PassThroughHack function remove when supported by code.
	if ( target == svGlobal.worldspawn )
		return false

	if ( !IsValid( target ) )
		return false

	if ( target.GetTeam() == attacker.GetTeam() )
		return false

	if ( target.GetTeam() != TEAM_IMC && target.GetTeam() != TEAM_MILITIA )
		return false

	return true
}

function PassThroughDamage( entity weapon, targetArray )
{
	//Tied to PassThroughHack function remove when supported by code.

	int damageSourceID = weapon.GetDamageSourceID()
	entity owner = weapon.GetWeaponOwner()

	foreach ( ent in targetArray )
	{
		expect entity( ent )

		float distanceToTarget = Distance( weapon.GetOrigin(), ent.GetOrigin() )
		float damageToDeal = CalcWeaponDamage( owner, ent, weapon, distanceToTarget, 0 )

		ent.TakeDamage( damageToDeal, owner, weapon.GetWeaponOwner(), { damageSourceId = damageSourceID } )
	}
}
#endif // SERVER

vector function GetVectorFromPositionToCrosshair( entity player, vector startPos )
{
	Assert( IsValid( player ) )

	// See where we're looking
	vector traceStart = player.EyePosition()
	vector traceEnd = traceStart + ( player.GetViewVector() * 20000 )
	local ignoreEnts = [ player ]
	TraceResults traceResult = TraceLine( traceStart, traceEnd, ignoreEnts, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_NONE )

	// Return vec from startPos to where we are looking
	vector vec = traceResult.endPos - startPos
	vec = Normalize( vec )
	return vec
}

/*
function InitMissileForRandomDriftBasic( missile, startPos, startDir )
{
	missile.s.RandomFloatRange <- RandomFloat( 1.0 )
	missile.s.startPos <- startPos
	missile.s.startDir <- startDir
}
*/

function InitMissileForRandomDriftForVortexHigh( entity missile, vector startPos, vector startDir )
{
	missile.InitMissileForRandomDrift( startPos, startDir, 8, 2.5, 0, 0, 100, 100 )
}

function InitMissileForRandomDriftForVortexLow( entity missile, vector startPos, vector startDir )
{
	missile.InitMissileForRandomDrift( startPos, startDir, 0.3, 0.085, 0, 0, 0.5, 0.5 )
}

/*
function InitMissileForRandomDrift( missile, startPos, startDir )
{
	InitMissileForRandomDriftBasic( missile, startPos, startDir )

	missile.s.drift_windiness <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_drift_windiness" )
	missile.s.drift_intensity <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_drift_intensity" )

	missile.s.straight_time_min <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_straight_time_min" )
	missile.s.straight_time_max <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_straight_time_max" )

	missile.s.straight_radius_min <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_straight_radius_min" )
	if ( missile.s.straight_radius_min < 1 )
		missile.s.straight_radius_min = 1
	missile.s.straight_radius_max <- missile.ProjectileGetWeaponInfoFileKeyField( "projectile_straight_radius_max" )
	if ( missile.s.straight_radius_max < 1 )
		missile.s.straight_radius_max = 1
}

function SmoothRandom( x )
{
	return 0.25 * (sin(x) + sin(x * 0.762) + sin(x * 0.363) + sin(x * 0.084))
}

function MissileRandomDrift( timeElapsed, timeStep, windiness, intensity )
{
	// This function makes the missile go in a random direction.
	// Windiness is how frequently the missile changes direction.
	// Intensity is how strongly the missile steers in the direction it has chosen.

	local sampleTime = timeElapsed - timeStep * 0.5

	intensity *= timeStep

	local offset = self.s.RandomFloatRange * 1000

	local offsetx = intensity * SmoothRandom( offset     +       sampleTime * windiness )
	local offsety = intensity * SmoothRandom( offset * 2 + 100 + sampleTime * windiness )

	local right = self.GetRightVector()
	local up = self.GetUpVector()

	//DebugDrawLine( self.GetOrigin(), self.GetOrigin() + right * 100, 255,255,255, true, 0 )
	//DebugDrawLine( self.GetOrigin(), self.GetOrigin() + up * 100, 255,128,255, true, 0 )

	local dir = self.GetVelocity()
	local speed = Length( dir )
	dir = Normalize( dir )
	dir += right * offsetx
	dir += up * offsety
	dir = Normalize( dir )
	dir *= speed

	return dir
}

// designed to be called every frame (GetProjectileVelocity callback) on projectiles that are flying through the air
function ApplyMissileControlledDrift( missile, timeElapsed, timeStep )
{
	// If we have a target, don't do anything fancy; just let code do the homing behavior
	if ( missile.GetMissileTarget() )
		return missile.GetVelocity()

	local s = missile.s
	return MissileControlledDrift( timeElapsed, timeStep, s.drift_windiness, s.drift_intensity, s.straight_time_min, s.straight_time_max, s.straight_radius_min, s.straight_radius_max )
}

function MissileControlledDrift( timeElapsed, timeStep, windiness, intensity, pathTimeMin, pathTimeMax, pathRadiusMin, pathRadiusMax )
{
	// Start with random drift.
	local vel = MissileRandomDrift( timeElapsed, timeStep, windiness, intensity )

	// Straighten our velocity back along our original path if we're below pathTimeMax.
	// Path time is how long it tries to stay on a straight path.
	// Path radius is how far it can get from its straight path.
	if ( timeElapsed < pathTimeMax )
	{
		local org = self.GetOrigin()
		local alongPathLen = self.s.startDir.Dot( org - self.s.startPos )
		local alongPathPos = self.s.startPos + self.s.startDir * alongPathLen
		local offPathOffset = org - alongPathPos
		local pathDist = Length( offPathOffset )

		local speed = Length( vel )

		local lerp = 1
		if ( timeElapsed > pathTimeMin )
			lerp = 1.0 - (timeElapsed - pathTimeMin) / (pathTimeMax - pathTimeMin)

		local pathRadius = pathRadiusMax + (pathRadiusMin - pathRadiusMax) * lerp

		// This circle shows the radius the missile is allowed to be in.
		//if ( IsServer() )
		//	DebugDrawCircle( alongPathPos, VectorToAngles( AnglesToUp( VectorToAngles( self.s.startDir ) ) ), pathRadius, 255,255,255, true, 0.0 )

		local backToPathVel = offPathOffset * -1
		// Cap backToPathVel at speed
		if ( pathDist > pathRadius )
			backToPathVel *= speed / pathDist
		else
			backToPathVel *= speed / pathRadius

		if ( pathDist < pathRadius )
		{
			backToPathVel += self.s.startDir * (speed * (1.0 - pathDist / pathRadius))
		}

		//DebugDrawLine( org, org + vel * 0.1, 255,255,255, true, 0 )
		//DebugDrawLine( org, org + backToPathVel * intensity * lerp * 0.1, 128,255,128, true, 0 )

		vel += backToPathVel * (intensity * timeStep)
		vel = Normalize( vel )
		vel *= speed
	}

	return vel
}
*/

#if SERVER
function ClusterRocket_Detonate( entity rocket, vector normal )
{
	entity owner = rocket.GetOwner()
	if ( !IsValid( owner ) )
		return

	int count
	float duration
	float range

	array mods = rocket.ProjectileGetMods()
	if ( mods.contains( "pas_northstar_cluster" ) )
	{
		count = CLUSTER_ROCKET_BURST_COUNT_BURN
		duration = PAS_NORTHSTAR_CLUSTER_ROCKET_DURATION
		range = CLUSTER_ROCKET_BURST_RANGE * 1.5
	}
	else
	{
		count = CLUSTER_ROCKET_BURST_COUNT
		duration = CLUSTER_ROCKET_DURATION
		range = CLUSTER_ROCKET_BURST_RANGE
	}

	if ( mods.contains( "fd_twin_cluster" ) )
	{
		count = int( count * 0.7 )
		duration *= 0.7
	}
	PopcornInfo popcornInfo

	popcornInfo.weaponName = "mp_titanweapon_dumbfire_rockets"
	popcornInfo.weaponMods = mods
	popcornInfo.damageSourceId = eDamageSourceId.mp_titanweapon_dumbfire_rockets
	popcornInfo.count = count
	popcornInfo.delay = CLUSTER_ROCKET_BURST_DELAY
	popcornInfo.offset = CLUSTER_ROCKET_BURST_OFFSET
	popcornInfo.range = range
	popcornInfo.normal = normal
	popcornInfo.duration = duration
	popcornInfo.groupSize = CLUSTER_ROCKET_BURST_GROUP_SIZE
	popcornInfo.hasBase = true

	thread StartClusterExplosions( rocket, owner, popcornInfo, CLUSTER_ROCKET_FX_TABLE )
}


function StartClusterExplosions( entity projectile, entity owner, PopcornInfo popcornInfo, customFxTable = null )
{
	Assert( IsValid( owner ) )
	owner.EndSignal( "OnDestroy" )

	string weaponName = popcornInfo.weaponName
	float innerRadius
	float outerRadius
	int explosionDamage
	int explosionDamageHeavyArmor

	innerRadius = projectile.GetProjectileWeaponSettingFloat( eWeaponVar.explosion_inner_radius )
	outerRadius = projectile.GetProjectileWeaponSettingFloat( eWeaponVar.explosionradius )
	if ( owner.IsPlayer() )
	{
		explosionDamage = projectile.GetProjectileWeaponSettingInt( eWeaponVar.explosion_damage )
		explosionDamageHeavyArmor = projectile.GetProjectileWeaponSettingInt( eWeaponVar.explosion_damage_heavy_armor )
	}
	else
	{
		explosionDamage = projectile.GetProjectileWeaponSettingInt( eWeaponVar.npc_explosion_damage )
		explosionDamageHeavyArmor = projectile.GetProjectileWeaponSettingInt( eWeaponVar.npc_explosion_damage_heavy_armor )
	}

	local explosionDelay = projectile.ProjectileGetWeaponInfoFileKeyField( "projectile_explosion_delay" )

	if ( owner.IsPlayer() )
		owner.EndSignal( "OnDestroy" )

	vector origin = projectile.GetOrigin()

	vector rotateFX = Vector( 90,0,0 )
	entity placementHelper = CreateScriptMover()
	placementHelper.SetOrigin( origin )
	placementHelper.SetAngles( VectorToAngles( popcornInfo.normal ) )
	SetTeam( placementHelper, owner.GetTeam() )

	array<entity> players = GetPlayerArray()
	foreach ( player in players )
	{
		Remote_CallFunction_NonReplay( player, "SCB_AddGrenadeIndicatorForEntity", owner.GetTeam(), owner.GetEncodedEHandle(), placementHelper.GetEncodedEHandle(), outerRadius )
	}

	int particleSystemIndex = GetParticleSystemIndex( CLUSTER_BASE_FX )
	int attachId = placementHelper.LookupAttachment( "REF" )
	entity fx

	if ( popcornInfo.hasBase )
	{
		fx = StartParticleEffectOnEntity_ReturnEntity( placementHelper, particleSystemIndex, FX_PATTACH_POINT_FOLLOW, attachId )
		EmitSoundOnEntity( placementHelper, "Explo_ThermiteGrenade_Impact_3P" ) // TODO: wants a custom sound
	}

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

	if ( explosionDelay )
		wait explosionDelay

	waitthread ClusterRocketBursts( origin, explosionDamage, explosionDamageHeavyArmor, innerRadius, outerRadius, owner, popcornInfo, customFxTable )

	if ( IsValid( projectile ) )
		projectile.Destroy()
}


//------------------------------------------------------------
// ClusterRocketBurst() - does a "popcorn airburst" explosion effect over time around the origin. Total distance is based on popRangeBase
// - returns the entity in case you want to parent it
//------------------------------------------------------------
function ClusterRocketBursts( vector origin, int damage, int damageHeavyArmor, float innerRadius, float outerRadius, entity owner, PopcornInfo popcornInfo, customFxTable = null )
{
	owner.EndSignal( "OnDestroy" )

	// this ent remembers the weapon mods
	entity clusterExplosionEnt = CreateEntity( "info_target" )
	DispatchSpawn( clusterExplosionEnt )

	if ( popcornInfo.weaponMods.len() > 0 )
		clusterExplosionEnt.s.weaponMods <- popcornInfo.weaponMods

	clusterExplosionEnt.SetOwner( owner )
	clusterExplosionEnt.SetOrigin( origin )

	AI_CreateDangerousArea_Static( clusterExplosionEnt, null, outerRadius, TEAM_INVALID, true, true, origin )

	OnThreadEnd(
		function() : ( clusterExplosionEnt )
		{
			clusterExplosionEnt.Destroy()
		}
	)

	// No Damage - Only Force
	// Push players
	// Test LOS before pushing
	int flags = 11
	// create a blast that knocks pilots out of the way
	CreatePhysExplosion( origin, outerRadius, PHYS_EXPLOSION_LARGE, flags )

	int count = popcornInfo.groupSize
	for ( int index = 0; index < count; index++ )
	{
		thread ClusterRocketBurst( clusterExplosionEnt, origin, damage, damageHeavyArmor, innerRadius, outerRadius, owner, popcornInfo, customFxTable )
		WaitFrame()
	}

	wait CLUSTER_ROCKET_DURATION
}

function ClusterRocketBurst( entity clusterExplosionEnt, vector origin, damage, damageHeavyArmor, innerRadius, outerRadius, entity owner, PopcornInfo popcornInfo, customFxTable = null )
{
	clusterExplosionEnt.EndSignal( "OnDestroy" )
	Assert( IsValid( owner ), "ClusterRocketBurst had invalid owner" )

	// first explosion always happens where you fired
	//int eDamageSource = popcornInfo.damageSourceId
	int numBursts = popcornInfo.count
	float popRangeBase = popcornInfo.range
	float popDelayBase = popcornInfo.delay
	float popDelayRandRange = popcornInfo.offset
	float duration = popcornInfo.duration
	int groupSize = popcornInfo.groupSize

	int counter = 0
	vector randVec
	float randRangeMod
	float popRange
	vector popVec
	vector popOri = origin
	float popDelay
	float colTrace

	float burstDelay = duration / ( numBursts / groupSize )

	vector clusterBurstOrigin = origin + (popcornInfo.normal * 8.0)
	entity clusterBurstEnt = CreateClusterBurst( clusterBurstOrigin )

	OnThreadEnd(
		function() : ( clusterBurstEnt )
		{
			if ( IsValid( clusterBurstEnt ) )
			{
				foreach ( fx in clusterBurstEnt.e.fxArray )
				{
					if ( IsValid( fx ) )
						fx.Destroy()
				}
				clusterBurstEnt.Destroy()
			}
		}
	)

	while ( IsValid( clusterBurstEnt ) && counter <= numBursts / popcornInfo.groupSize )
	{
		randVec = RandomVecInDome( popcornInfo.normal )
		randRangeMod = RandomFloat( 1.0 )
		popRange = popRangeBase * randRangeMod
		popVec = randVec * popRange
		popOri = origin + popVec
		popDelay = popDelayBase + RandomFloatRange( -popDelayRandRange, popDelayRandRange )

		colTrace = TraceLineSimple( origin, popOri, null )
		if ( colTrace < 1 )
		{
			popVec = popVec * colTrace
			popOri = origin + popVec
		}

		clusterBurstEnt.SetOrigin( clusterBurstOrigin )

		vector velocity = GetVelocityForDestOverTime( clusterBurstEnt.GetOrigin(), popOri, burstDelay - popDelay )
		clusterBurstEnt.SetVelocity( velocity )

		clusterBurstOrigin = popOri

		counter++

		wait burstDelay - popDelay

		Explosion(
			clusterBurstOrigin,
			owner,
			clusterExplosionEnt,
			damage,
			damageHeavyArmor,
			innerRadius,
			outerRadius,
			SF_ENVEXPLOSION_NOSOUND_FOR_ALLIES,
			clusterBurstOrigin,
			damage,
			damageTypes.explosive,
			popcornInfo.damageSourceId,
			customFxTable )
	}
}


entity function CreateClusterBurst( vector origin )
{
	entity prop_physics = CreateEntity( "prop_physics" )
	prop_physics.SetValueForModelKey( $"models/weapons/bullets/projectile_rocket.mdl" )
	prop_physics.kv.spawnflags = 4 // 4 = SF_PHYSPROP_DEBRIS
	prop_physics.kv.fadedist = 2000
	prop_physics.kv.renderamt = 255
	prop_physics.kv.rendercolor = "255 255 255"
	prop_physics.kv.CollisionGroup = TRACE_COLLISION_GROUP_DEBRIS

	prop_physics.kv.minhealthdmg = 9999
	prop_physics.kv.nodamageforces = 1
	prop_physics.kv.inertiaScale = 1.0

	prop_physics.SetOrigin( origin )
	DispatchSpawn( prop_physics )
	prop_physics.SetModel( $"models/weapons/grenades/m20_f_grenade.mdl" )

	entity fx = PlayFXOnEntity( $"P_wpn_dumbfire_burst_trail", prop_physics )
	prop_physics.e.fxArray.append( fx )

	return prop_physics
}
#endif // SERVER

vector function GetVelocityForDestOverTime( vector startPoint, vector endPoint, float duration )
{
	const GRAVITY = 750

	float Vox = (endPoint.x - startPoint.x) / duration
	float Voy = (endPoint.y - startPoint.y) / duration
	float Voz = (endPoint.z + 0.5 * GRAVITY * duration * duration - startPoint.z) / duration

	return Vector( Vox, Voy, Voz )
}

vector function GetPlayerVelocityForDestOverTime( vector startPoint, vector endPoint, float duration )
{
	// Same as above but accounts for player gravity setting not being 1.0

	float gravityScale = expect float( GetPlayerSettingsFieldForClassName( DEFAULT_PILOT_SETTINGS, "gravityscale" ) )
	float GRAVITY = 750 * gravityScale // adjusted for new gravity scale

	float Vox = (endPoint.x - startPoint.x) / duration
	float Voy = (endPoint.y - startPoint.y) / duration
	float Voz = (endPoint.z + 0.5 * GRAVITY * duration * duration - startPoint.z) / duration

	return Vector( Vox, Voy, Voz )
}

bool function HasLockedTarget( weapon )
{
	if ( weapon.SmartAmmo_IsEnabled() )
	{
		local targets = weapon.SmartAmmo_GetTargets()
		if ( targets.len() > 0 )
		{
			foreach ( target in targets )
			{
				if ( target.fraction == 1 )
					return true
			}
		}
	}
	return false
}

function CanWeaponShootWhileRunning( entity weapon )
{
	if ( "primary_fire_does_not_block_sprint" in weapon.s )
		return weapon.s.primary_fire_does_not_block_sprint

	if ( weapon.GetWeaponInfoFileKeyField( "primary_fire_does_not_block_sprint" ) == 1 )
	{
		weapon.s.primary_fire_does_not_block_sprint <- true
		return true
	}

	weapon.s.primary_fire_does_not_block_sprint <- false
	return false
}

#if CLIENT
function ServerCallback_GuidedMissileDestroyed()
{
	entity player = GetLocalViewPlayer()

	// guided missiles has not been updated to work with replays. added this if statement defensively just in case. - Roger
	if ( !( "missileInFlight" in player.s ) )
		return

	player.s.missileInFlight = false
}

function ServerCallback_AirburstIconUpdate( toggle )
{
	entity player = GetLocalViewPlayer()
	entity cockpit = player.GetCockpit()
	if ( cockpit )
	{
		entity mainVGUI = cockpit.e.mainVGUI
		if ( mainVGUI )
		{
			if ( toggle )
				cockpit.s.offhandHud[OFFHAND_RIGHT].icon.SetImage( $"vgui/HUD/dpad_airburst_activate" )
			else
				cockpit.s.offhandHud[OFFHAND_RIGHT].icon.SetImage( $"vgui/HUD/dpad_airburst" )
		}
	}
}

bool function IsOwnerViewPlayerFullyADSed( entity weapon )
{
	entity owner = weapon.GetOwner()
	if ( !IsValid( owner ) )
		return false

	if( !owner.IsPlayer() )
		return false

	if ( owner != GetLocalViewPlayer() )
		return false

	float zoomFrac = owner.GetZoomFrac()
	if ( zoomFrac < 1.0 )
		return false

	return true

}
#endif // CLIENT

array<entity> function FireExpandContractMissiles( entity weapon, WeaponPrimaryAttackParams attackParams, vector attackPos, vector attackDir, int damageType, int explosionDamageType, shouldPredict, int rocketsPerShot, missileSpeed, launchOutAng, launchOutTime, launchInAng, launchInTime, launchInLerpTime, launchStraightLerpTime, applyRandSpread, int burstFireCountOverride = -1, debugDrawPath = false )
{
	local missileVecs = GetExpandContractRocketTrajectories( weapon, attackParams.burstIndex, attackPos, attackDir, rocketsPerShot, launchOutAng, launchInAng, burstFireCountOverride )
	entity owner = weapon.GetWeaponOwner()
	array<entity> firedMissiles

	vector missileEndPos = owner.EyePosition() + ( attackDir * 5000 )

	for ( int i = 0; i < rocketsPerShot; i++ )
	{
		entity missile = weapon.FireWeaponMissile( attackPos, attackDir, missileSpeed, damageType, explosionDamageType, false, shouldPredict )

		if ( missile )
		{
			/*
			missile.s.flightData <- {
								launchOutVec = missileVecs[i].outward,
								launchOutTime = launchOutTime,
								launchInLerpTime = launchInLerpTime,
								launchInVec = missileVecs[i].inward,
								launchInTime = launchInTime,
								launchStraightLerpTime = launchStraightLerpTime,
								endPos = missileEndPos,
								applyRandSpread = applyRandSpread
							}
			*/

			missile.InitMissileExpandContract( missileVecs[i].outward, missileVecs[i].inward, launchOutTime, launchInLerpTime, launchInTime, launchStraightLerpTime, missileEndPos, applyRandSpread )

			if ( IsServer() && debugDrawPath )
				thread DebugDrawMissilePath( missile )

			//InitMissileForRandomDrift( missile, attackPos, attackDir )
			missile.InitMissileForRandomDriftFromWeaponSettings( attackPos, attackDir )

			firedMissiles.append( missile )
		}
	}

	return firedMissiles
}

array<entity> function FireExpandContractMissiles_S2S( entity weapon, WeaponPrimaryAttackParams attackParams, vector attackPos, vector attackDir, shouldPredict, int rocketsPerShot, missileSpeed, launchOutAng, launchOutTime, launchInAng, launchInTime, launchInLerpTime, launchStraightLerpTime, applyRandSpread, int burstFireCountOverride = -1, debugDrawPath = false )
{
	local missileVecs = GetExpandContractRocketTrajectories( weapon, attackParams.burstIndex, attackPos, attackDir, rocketsPerShot, launchOutAng, launchInAng, burstFireCountOverride )
	entity owner = weapon.GetWeaponOwner()
	array<entity> firedMissiles

	vector missileEndPos = attackPos + ( attackDir * 5000 )

	for ( int i = 0; i < rocketsPerShot; i++ )
	{
		entity missile = weapon.FireWeaponMissile( attackPos, attackDir, missileSpeed, DF_GIB | DF_IMPACT, damageTypes.explosive, false, shouldPredict )
		missile.SetOrigin( attackPos )//HACK why do I have to do this?
		if ( missile )
		{
			/*
			missile.s.flightData <- {
								launchOutVec = missileVecs[i].outward,
								launchOutTime = launchOutTime,
								launchInLerpTime = launchInLerpTime,
								launchInVec = missileVecs[i].inward,
								launchInTime = launchInTime,
								launchStraightLerpTime = launchStraightLerpTime,
								endPos = missileEndPos,
								applyRandSpread = applyRandSpread
							}
			*/

			missile.InitMissileExpandContract( missileVecs[i].outward, missileVecs[i].inward, launchOutTime, launchInLerpTime, launchInTime, launchStraightLerpTime, missileEndPos, applyRandSpread )

			if ( IsServer() && debugDrawPath )
				thread DebugDrawMissilePath( missile )

			//InitMissileForRandomDrift( missile, attackPos, attackDir )
			missile.InitMissileForRandomDriftFromWeaponSettings( attackPos, attackDir )

			firedMissiles.append( missile )
		}
	}

	return firedMissiles
}

function GetExpandContractRocketTrajectories( entity weapon, int burstIndex, vector attackPos, vector attackDir, int rocketsPerShot, launchOutAng, launchInAng, int burstFireCount = -1 )
{
	bool DEBUG_DRAW_MATH = false

	if ( burstFireCount == -1 )
		burstFireCount = weapon.GetWeaponBurstFireCount()

	local additionalRotation = ( ( 360.0 / rocketsPerShot ) / burstFireCount ) * burstIndex
	//printt( "burstIndex:", burstIndex )
	//printt( "rocketsPerShot:", rocketsPerShot )
	//printt( "burstFireCount:", burstFireCount )

	vector ang = VectorToAngles( attackDir )
	vector forward = AnglesToForward( ang )
	vector right = AnglesToRight( ang )
	vector up = AnglesToUp( ang )

	if ( DEBUG_DRAW_MATH )
		DebugDrawLine( attackPos, attackPos + ( forward * 1000 ), 255, 0, 0, true, 30.0 )

	// Create points on circle
	float offsetAng = 360.0 / rocketsPerShot
	for ( int i = 0; i < rocketsPerShot; i++ )
	{
		local a = offsetAng * i + additionalRotation
		vector vec = Vector( 0, 0, 0 )
		vec += up * deg_sin( a )
		vec += right * deg_cos( a )

		if ( DEBUG_DRAW_MATH )
			DebugDrawLine( attackPos, attackPos + ( vec * 50 ), 10, 10, 10, true, 30.0 )
	}

	// Create missile points
	vector x = right * deg_sin( launchOutAng )
	vector y = up * deg_sin( launchOutAng )
	vector z = forward * deg_cos( launchOutAng )
	vector rx = right * deg_sin( launchInAng )
	vector ry = up * deg_sin( launchInAng )
	vector rz = forward * deg_cos( launchInAng )
	local missilePoints = []
	for ( int i = 0; i < rocketsPerShot; i++ )
	{
		local points = {}

		// Outward vec
		local a = offsetAng * i + additionalRotation
		float s = deg_sin( a )
		float c = deg_cos( a )
		vector vecOut = z + x * c + y * s
		vecOut = Normalize( vecOut )
		points.outward <- vecOut

		// Inward vec
		vector vecIn = rz + rx * c + ry * s
		points.inward <- vecIn

		// Add to array
		missilePoints.append( points )

		if ( DEBUG_DRAW_MATH )
		{
			DebugDrawLine( attackPos, attackPos + ( vecOut * 50 ), 255, 255, 0, true, 30.0 )
			DebugDrawLine( attackPos + vecOut * 50, attackPos + vecOut * 50 + ( vecIn * 50 ), 255, 0, 255, true, 30.0 )
		}
	}

	return missilePoints
}

function DebugDrawMissilePath( entity missile )
{
	EndSignal( missile, "OnDestroy" )
	vector lastPos = missile.GetOrigin()
	while ( true )
	{
		WaitFrame()
		if ( !IsValid( missile ) )
			return
		DebugDrawLine( lastPos, missile.GetOrigin(), 0, 255, 0, true, 20.0 )
		lastPos = missile.GetOrigin()
	}
}


function RegenerateOffhandAmmoOverTime( entity weapon, float rechargeTime, int maxAmmo, int offhandIndex )
{
	weapon.Signal( "RegenAmmo" )
	weapon.EndSignal( "RegenAmmo" )
	weapon.EndSignal( "OnDestroy" )

	#if CLIENT
	entity weaponOwner = weapon.GetWeaponOwner()
	if ( IsValid( weaponOwner ) && weaponOwner.IsPlayer() )
	{
		entity cockpit = weaponOwner.GetCockpit()
		if ( IsValid( cockpit ) )
		{
			cockpit.s.offhandHud[offhandIndex].bar.SetBarProgressSource( ProgressSource.PROGRESS_SOURCE_SCRIPTED )
			cockpit.s.offhandHud[offhandIndex].bar.SetBarProgressRemap( 0.0, 1.0, 0.0, 1.0 )
			cockpit.s.offhandHud[offhandIndex].bar.SetBarProgressAndRate( 1.0 / maxAmmo , 1 / ( rechargeTime * maxAmmo ) )
		}
	}
	#endif

	if ( !( "totalChargeTime" in weapon.s ) )
		weapon.s.totalChargeTime <- rechargeTime

	if ( !( "nextChargeTime" in weapon.s ) )
		weapon.s.nextChargeTime <- null

	for ( ;; )
	{
		weapon.s.nextChargeTime = rechargeTime + Time()

		wait rechargeTime

		if ( IsServer() )
		{
			int max = maxAmmo
			int weaponMax = weapon.GetWeaponPrimaryClipCountMax()
			if ( weaponMax < max )
				max = weaponMax

			int ammo = weapon.GetWeaponPrimaryClipCount()
			if ( ammo < max )
				weapon.SetWeaponPrimaryClipCount( ammo + 1 )
		}
	}
}

bool function IsPilotShotgunWeapon( string weaponName )
{
	return GetWeaponInfoFileKeyField_Global( weaponName, "weaponSubClass" ) == "shotgun"
}

array<string> function GetWeaponBurnMods( string weaponClassName )
{
	array<string> burnMods = []
	array<string> mods = GetWeaponMods_Global( weaponClassName )
	string prefix = "burn_mod"
	foreach ( mod in mods )
	{
		if ( mod.find( prefix ) == 0 )
			burnMods.append( mod )
	}

	return burnMods
}

int function TEMP_GetDamageFlagsFromProjectile( entity projectile )
{
	var damageFlagsString = projectile.ProjectileGetWeaponInfoFileKeyField( "damage_flags" )
	if ( damageFlagsString == null )
		return 0
	expect string( damageFlagsString )

	return TEMP_GetDamageFlagsFromString( damageFlagsString )
}

int function TEMP_GetDamageFlagsFromString( string damageFlagsString )
{
	int damageFlags = 0

	array<string> damageFlagTokens = split( damageFlagsString, "|" )
	foreach ( token in damageFlagTokens )
	{
		damageFlags = damageFlags | getconsttable()[strip(token)]
	}

	return damageFlags
}

#if SERVER
function PROTO_InitTrackedProjectile( entity projectile )
{
	// HACK: accessing ProjectileGetWeaponInfoFileKeyField or ProjectileGetWeaponClassName during CodeCallback_OnSpawned causes a code assert
	projectile.EndSignal( "OnDestroy" )
	WaitFrame()

	entity owner = projectile.GetOwner()

	if ( !IsValid( owner ) || !owner.IsPlayer() )
		return

	int maxDeployed = projectile.GetProjectileWeaponSettingInt( eWeaponVar.projectile_max_deployed )
	if ( maxDeployed != 0 )
	{
		AddToScriptManagedEntArray( owner.s.activeTrapArrayId, projectile )

		array<entity> traps = GetScriptManagedEntArray( owner.s.activeTrapArrayId )
		array<entity> sameTypeTrapEnts
		foreach ( ent in traps )
		{
			if ( ent.ProjectileGetWeaponClassName() != projectile.ProjectileGetWeaponClassName() )
				continue

			sameTypeTrapEnts.append( ent )
		}

		int numToDestroy = sameTypeTrapEnts.len() - maxDeployed
		if ( numToDestroy > 0 )
		{
			sameTypeTrapEnts.sort( CompareCreation )
			foreach ( ent in sameTypeTrapEnts )
			{
				ent.Destroy()
				numToDestroy--

				if ( !numToDestroy )
					break
			}
		}
	}
}


function PROTO_CleanupTrackedProjectiles( entity player )
{
	array<entity> traps = GetScriptManagedEntArray( player.s.activeTrapArrayId )
	foreach ( ent in traps )
	{
		ent.Destroy()
	}
}

int function CompareCreation( entity a, entity b )
{
	if ( a.GetProjectileCreationTime() > b.GetProjectileCreationTime() )
		return 1

	return -1
}

int function CompareCreationReverse( entity a, entity b )
{
	if ( a.GetProjectileCreationTime() > b.GetProjectileCreationTime() )
		return 1

	return -1
}

void function PROTO_TrackedProjectile_OnPlayerRespawned( entity player )
{
	thread PROTO_TrackedProjectile_OnPlayerRespawned_Internal( player )
}

void function PROTO_TrackedProjectile_OnPlayerRespawned_Internal( entity player )
{
	player.EndSignal( "OnDeath" )

	if ( player.s.inGracePeriod )
		player.WaitSignal( "GracePeriodDone" )

	entity ordnance = player.GetOffhandWeapon( OFFHAND_ORDNANCE )

	array<entity> traps = GetScriptManagedEntArray( player.s.activeTrapArrayId )
	foreach ( ent in traps )
	{
		if ( ordnance && ent.ProjectileGetWeaponClassName() == ordnance.GetWeaponClassName() )
			continue

		ent.Destroy()
	}
}

function PROTO_PlayTrapLightEffect( entity ent, string tag, int team )
{
	asset ownerFx = ent.ProjectileGetWeaponInfoFileKeyFieldAsset( "trap_warning_owner_fx" )
	if ( ownerFx != $"" )
	{
		entity ownerFxEnt = CreateServerEffect_Owner( ownerFx, ent.GetOwner() )
		SetServerEffectControlPoint( ownerFxEnt, 0, FRIENDLY_COLOR  )
		StartServerEffectOnEntity( ownerFxEnt, ent, tag )
	}

	asset friendlyFx = ent.ProjectileGetWeaponInfoFileKeyFieldAsset( "trap_warning_friendly_fx" )
	if ( friendlyFx != $"" )
	{
		entity friendlyFxEnt = CreateServerEffect_Friendly( friendlyFx, team )
		SetServerEffectControlPoint( friendlyFxEnt, 0, FRIENDLY_COLOR_FX )
		StartServerEffectOnEntity( friendlyFxEnt, ent, tag )
	}

	asset enemyFx = ent.ProjectileGetWeaponInfoFileKeyFieldAsset( "trap_warning_enemy_fx" )
	if ( enemyFx != $"" )
	{
		entity enemyFxEnt = CreateServerEffect_Enemy( enemyFx, team )
		SetServerEffectControlPoint( enemyFxEnt, 0, ENEMY_COLOR_FX )
		StartServerEffectOnEntity( enemyFxEnt, ent, tag )
	}
}

string ornull function GetCooldownBeepPrefix( weapon )
{
	var reloadBeepPrefix = weapon.GetWeaponInfoFileKeyField( "cooldown_sound_prefix" )
	if ( reloadBeepPrefix == null )
		return null

	expect string( reloadBeepPrefix )

	return reloadBeepPrefix
}

void function PROTO_DelayCooldown( entity weapon )
{
	weapon.s.nextCooldownTime = Time() + weapon.s.cooldownDelay
}

string function GetBeepSuffixForAmmo( int currentAmmo, int maxAmmo )
{
	float frac = float( currentAmmo ) / float( maxAmmo )

	if ( frac >= 1.0 )
		return "_full"

	if ( frac >= 0.25 )
		return ""

	return "_low"
}

#endif //SERVER

bool function PROTO_CanPlayerDeployWeapon( entity player )
{
	if ( player.IsPhaseShifted() )
		return false

	if ( player.ContextAction_IsActive() == true )
	{
		if ( player.IsZiplining() )
			return true
		else
			return false
	}

	return true
}

#if SERVER
void function PROTO_FlakCannonMissiles( entity projectile, float speed )
{
	projectile.EndSignal( "OnDestroy" )

	float radius = projectile.GetProjectileWeaponSettingFloat( eWeaponVar.explosionradius )
	vector velocity = projectile.GetVelocity()
	vector currentPos = projectile.GetOrigin()
	int team = projectile.GetTeam()

	float waitTime = 0.1
	float distanceInterval = speed * waitTime
	int forwardDistanceChecks = int( ceil( distanceInterval / radius ) )
	bool forceExplosion = false
	while ( forceExplosion == false )
	{
		currentPos = projectile.GetOrigin()
		for ( int i = 0; i < forwardDistanceChecks; i++ )
		{
			float frac = float( i ) / float (forwardDistanceChecks )
			if ( PROTO_FlakCannon_HasNearbyEnemies( currentPos + velocity * waitTime * frac , team, radius ) )
			{
				if ( i == 0 )
				{
					forceExplosion = true
					break
				}
				else
				{
					projectile.SetVelocity( velocity * ( frac - 0.05 ) )
					break
				}
			}
		}

		if ( forceExplosion == false )
			wait waitTime
	}

	projectile.MissileExplode()
}

bool function PROTO_FlakCannon_HasNearbyEnemies( vector origin, int team, float radius )
{
	float worldSpaceCenterBuffer = 200

	array<entity> guys = GetPlayerArrayEx( "any", TEAM_ANY, team, origin, radius + worldSpaceCenterBuffer )
	foreach ( guy in guys )
	{
		if ( IsAlive( guy ) && Distance( origin, guy.GetWorldSpaceCenter() ) < radius )
			return true
	}

	array<entity> ai = GetNPCArrayEx( "any", TEAM_ANY, team, origin, radius + worldSpaceCenterBuffer )
	foreach ( guy in ai )
	{
		if ( IsAlive( guy ) && Distance( origin, guy.GetWorldSpaceCenter() ) < radius )
			return true
	}

	return false
}
#endif // #if SERVER

void function GiveEMPStunStatusEffects( entity ent, float duration, float fadeoutDuration = 0.5, float slowTurn = EMP_SEVERITY_SLOWTURN, float slowMove = EMP_SEVERITY_SLOWMOVE)
{
	entity target = ent.IsTitan() ? ent.GetTitanSoul() : ent
	int slowEffect = StatusEffect_AddTimed( target, eStatusEffect.turn_slow, slowTurn, duration, fadeoutDuration )
	int turnEffect = StatusEffect_AddTimed( target, eStatusEffect.move_slow, slowMove, duration, fadeoutDuration )

	#if SERVER
	if ( ent.IsPlayer() )
	{
		ent.p.empStatusEffectsToClearForPhaseShift.append( slowEffect )
		ent.p.empStatusEffectsToClearForPhaseShift.append( turnEffect )
	}
	#endif
}

#if DEV
string ornull function FindEnumNameForValue( table searchTable, int searchVal )
{
	foreach( string keyname, int value in searchTable )
	{
		if ( value == searchVal )
			return keyname;
	}
	return null
}

void function DevPrintAllStatusEffectsOnEnt( entity ent )
{
	printt( "Effects:", ent )
	array<float> effects = StatusEffect_GetAll( ent )
	int length = effects.len()
	int found = 0;
	for ( int idx = 0; idx < length; idx++ )
	{
		float severity = effects[idx];
		if ( severity <= 0.0 )
			continue
		string ornull name = FindEnumNameForValue( eStatusEffect, idx )
		Assert( name )
		expect string( name )
		printt( " eStatusEffect." + name + ": " + severity )
		found++;
	}
	printt( found + " effects active.\n" );
}
#endif // #if DEV

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

		primaryWeapons.append( weaponEnt )
	}
	return primaryWeapons
}

array<entity> function GetSidearmWeapons( entity player )
{
	array<entity> sidearmWeapons
	array<entity> weapons = player.GetMainWeapons()
	foreach ( weaponEnt in weapons )
	{
		if ( weaponEnt.GetWeaponType() != WT_SIDEARM )
			continue

		sidearmWeapons.append( weaponEnt )
	}
	return sidearmWeapons
}

array<entity> function GetATWeapons( entity player )
{
	array<entity> atWeapons
	array<entity> weapons = player.GetMainWeapons()
	foreach ( weaponEnt in weapons )
	{
		if ( weaponEnt.GetWeaponType() != WT_ANTITITAN )
			continue

		atWeapons.append( weaponEnt )
	}
	return atWeapons
}

entity function GetPlayerFromTitanWeapon( entity weapon )
{
	entity titan = weapon.GetWeaponOwner()
	entity player

	if ( titan == null )
		return null

	if ( !titan.IsPlayer() )
		player = titan.GetBossPlayer()
	else
		player = titan

	return player
}


const asset CHARGE_SHOT_PROJECTILE = $"models/weapons/bullets/temp_triple_threat_projectile_large.mdl"

const asset CHARGE_EFFECT_1P = $"P_ordnance_charge_st_FP" // $"P_wpn_defender_charge_FP"
const asset CHARGE_EFFECT_3P = $"P_ordnance_charge_st" // $"P_wpn_defender_charge"
const asset CHARGE_EFFECT_DLIGHT = $"defender_charge_CH_dlight"

const string CHARGE_SOUND_WINDUP_1P = "Weapon_ChargeRifle_WindUp_1P"
const string CHARGE_SOUND_WINDUP_3P = "Weapon_ChargeRifle_WindUp_3P"
const string CHARGE_SOUND_WINDDOWN_1P = "Weapon_ChargeRifle_WindDown_1P"
const string CHARGE_SOUND_WINDDOWN_3P = "Weapon_ChargeRifle_WindDown_3P"

void function ChargeBall_Precache()
{
#if SERVER
	PrecacheModel( CHARGE_SHOT_PROJECTILE )
	PrecacheEffect( CHARGE_EFFECT_1P )
	PrecacheEffect( CHARGE_EFFECT_3P )
#endif // #if SERVER
}

void function ChargeBall_FireProjectile( entity weapon, vector position, vector direction, bool shouldPredict )
{
	weapon.EmitWeaponNpcSound( LOUD_WEAPON_AI_SOUND_RADIUS_MP, 0.2 )

	entity owner = weapon.GetWeaponOwner()
	const float MISSILE_SPEED = 1200.0
	const int CONTACT_DAMAGE_TYPES = (damageTypes.projectileImpact | DF_DOOM_FATALITY)
	const int EXPLOSION_DAMAGE_TYPES = damageTypes.explosive
	const bool DO_POPUP = false

	if ( shouldPredict )
	{
		entity missile = weapon.FireWeaponMissile( position, direction, MISSILE_SPEED, CONTACT_DAMAGE_TYPES, EXPLOSION_DAMAGE_TYPES, DO_POPUP, shouldPredict )
		if ( missile )
		{
			EmitSoundOnEntity( owner, "ShoulderRocket_Cluster_Fire_3P" )
			missile.SetModel( CHARGE_SHOT_PROJECTILE )
#if CLIENT
			const ROCKETEER_MISSILE_EXPLOSION = $"xo_exp_death"
			const ROCKETEER_MISSILE_SHOULDER_FX = $"wpn_mflash_xo_rocket_shoulder_FP"
			entity owner = weapon.GetWeaponOwner()
			vector origin = owner.OffsetPositionFromView( Vector(0, 0, 0), Vector(25, -25, 15) )
			vector angles = owner.CameraAngles()
			StartParticleEffectOnEntityWithPos( owner, GetParticleSystemIndex( ROCKETEER_MISSILE_SHOULDER_FX ), FX_PATTACH_EYES_FOLLOW, -1, origin, angles )
#else // #if CLIENT
			missile.SetProjectileImpactDamageOverride( 1440 )
			missile.kv.damageSourceId = eDamageSourceId.charge_ball
#endif // #else // #if CLIENT
		}
	}
}

bool function ChargeBall_ChargeBegin( entity weapon, string tagName )
{
#if CLIENT
	if ( InPrediction() && !IsFirstTimePredicted() )
		return true
#endif // #if CLIENT

	weapon.w.statusEffects.append( StatusEffect_AddEndless( weapon.GetWeaponOwner(), eStatusEffect.move_slow, 0.6 ) )
	weapon.w.statusEffects.append( StatusEffect_AddEndless( weapon.GetWeaponOwner(), eStatusEffect.turn_slow, 0.35 ) )

	weapon.PlayWeaponEffect( CHARGE_EFFECT_1P, CHARGE_EFFECT_3P, tagName )
	weapon.PlayWeaponEffect( $"", CHARGE_EFFECT_DLIGHT, tagName )

#if SERVER
	StopSoundOnEntity( weapon, CHARGE_SOUND_WINDDOWN_3P )
	entity weaponOwner = weapon.GetWeaponOwner()
	if ( IsValid( weaponOwner ) )
	{
		if ( weaponOwner.IsPlayer() )
			EmitSoundOnEntityExceptToPlayer( weapon, weaponOwner, CHARGE_SOUND_WINDUP_3P )
		else
			EmitSoundOnEntity( weapon, CHARGE_SOUND_WINDUP_3P )
	}
#else
	StopSoundOnEntity( weapon, CHARGE_SOUND_WINDDOWN_1P )
	EmitSoundOnEntity( weapon, CHARGE_SOUND_WINDUP_1P )
#endif

	return true
}

void function ChargeBall_ChargeEnd( entity weapon )
{
#if CLIENT
	if ( InPrediction() && !IsFirstTimePredicted() )
		return
#endif

	if ( IsValid( weapon.GetWeaponOwner() ) )
	{
		#if CLIENT
		if ( InPrediction() && IsFirstTimePredicted() )
		{
		#endif

			foreach ( effect in weapon.w.statusEffects )
			{
				StatusEffect_Stop( weapon.GetWeaponOwner(), effect )
			}

		#if CLIENT
		}
		#endif
	}

#if SERVER
	StopSoundOnEntity( weapon, CHARGE_SOUND_WINDUP_3P )
	entity weaponOwner = weapon.GetWeaponOwner()
	if ( IsValid( weaponOwner ) )
	{
		if ( weaponOwner.IsPlayer() )
			EmitSoundOnEntityExceptToPlayer( weapon, weaponOwner, CHARGE_SOUND_WINDDOWN_3P )
		else
			EmitSoundOnEntity( weapon, CHARGE_SOUND_WINDDOWN_3P )
	}
#else
	StopSoundOnEntity( weapon, CHARGE_SOUND_WINDUP_1P )
	EmitSoundOnEntity( weapon, CHARGE_SOUND_WINDDOWN_1P )
#endif

	ChargeBall_StopChargeEffects( weapon )
}

void function ChargeBall_StopChargeEffects( entity weapon )
{
	Assert( IsValid( weapon ) )
	// weapon.StopWeaponEffect( CHARGE_EFFECT_1P, CHARGE_EFFECT_3P )
	// weapon.StopWeaponEffect( CHARGE_EFFECT_3P, CHARGE_EFFECT_1P )
	// weapon.StopWeaponEffect( CHARGE_EFFECT_DLIGHT, CHARGE_EFFECT_DLIGHT )
	thread HACK_Deplayed_ChargeBall_StopChargeEffects( weapon )
}

void function HACK_Deplayed_ChargeBall_StopChargeEffects( entity weapon )
{
	weapon.EndSignal( "OnDestroy" )
	wait 0.2
	weapon.StopWeaponEffect( CHARGE_EFFECT_1P, CHARGE_EFFECT_3P )
	weapon.StopWeaponEffect( CHARGE_EFFECT_3P, CHARGE_EFFECT_1P )
	weapon.StopWeaponEffect( CHARGE_EFFECT_DLIGHT, CHARGE_EFFECT_DLIGHT )
}

float function ChargeBall_GetChargeTime()
{
	return 1.05
}

#if SERVER
void function GivePlayerAmpedWeapon( entity player, string weaponName )
{
	array<entity> weapons = player.GetMainWeapons()
	int numWeapons = weapons.len()
	if ( numWeapons == 0 )
		return

	//Figure out what weapon to take away.
	//This is more complicated than it should be because of rules of what weapons can be in what slots, e.g.  your anti-titan weapon can't be replaced by non anti-titan weapons
	if ( HasWeapon( player, weaponName ) )
	{
		//Simplest case:
		//Take away the currently existing version of the weapon you already have.
		player.TakeWeaponNow( weaponName )
	}
	else
	{
		bool ampedWeaponIsAntiTitan = GetWeaponInfoFileKeyField_Global( weaponName, "weaponType" ) == "anti_titan"
		if ( ampedWeaponIsAntiTitan )
		{
			foreach( weapon in weapons )
			{
				string currentWeaponClassName = weapon.GetWeaponClassName()
				if ( GetWeaponInfoFileKeyField_Global( currentWeaponClassName, "weaponType" ) == "anti_titan" )
				{
					player.TakeWeaponNow( currentWeaponClassName )
					break
				}
			}

			unreachable //We had no anti-titan weapon? Shouldn't ever be possible

		}
		else
		{
			string currentActiveWeaponClassName = player.GetActiveWeapon().GetWeaponClassName()
			if ( ShouldReplaceWeaponInFirstSlot( player, currentActiveWeaponClassName ) )
			{
				//Current weapon is anti_titan, but amped weapon we are trying to give is not. Just replace the weapon that is in the first slot.
				//Assumes that weapon in first slot is not an anti-titan weapon
				//We could get even fancier and look to see if the amped weapon is a primary weapon or a sidearm and replace the slot accordingly, but
				//that makes it more complicated, plus there are cases where you can have no primary weapons/no side arms etc
				string firstWeaponClassName = weapons[ 0 ].GetWeaponClassName()
				Assert( GetWeaponInfoFileKeyField_Global( firstWeaponClassName, "weaponType" ) != "anti_titan"  )
				player.TakeWeaponNow( firstWeaponClassName )
			}
			else
			{
				player.TakeWeaponNow( currentActiveWeaponClassName )
			}
		}
	}

	array<string> burnMods = GetWeaponBurnMods( weaponName )
	entity ampedWeapon = player.GiveWeapon( weaponName, burnMods )
	ampedWeapon.SetWeaponPrimaryClipCount( ampedWeapon.GetWeaponPrimaryClipCountMax() ) //Needed for weapons that give a mod with extra clip size
}

bool function ShouldReplaceWeaponInFirstSlot( entity player, string currentActiveWeaponClassName )
{
	if ( GetWeaponInfoFileKeyField_Global( currentActiveWeaponClassName, "weaponType" ) == "anti_titan" ) //Active weapon is anti-titan weapon. Can't replace anti-titan weapon slot with non-anti-titan weapon
		return true

	if ( currentActiveWeaponClassName == player.GetOffhandWeapon( OFFHAND_ORDNANCE ).GetWeaponClassName() )
		return true

	return false

}

void function GivePlayerAmpedWeaponAndSetAsActive( entity player, string weaponName )
{
	GivePlayerAmpedWeapon( player, weaponName )
	player.SetActiveWeaponByName( weaponName )
}

void function ReplacePlayerOffhand( entity player, string offhandName, array<string> mods = [] )
{
	player.TakeOffhandWeapon( OFFHAND_SPECIAL )
	player.GiveOffhandWeapon( offhandName, OFFHAND_SPECIAL, mods )
}

void function ReplacePlayerOrdnance( entity player, string ordnanceName, array<string> mods = [] )
{
	player.TakeOffhandWeapon( OFFHAND_ORDNANCE )
	player.GiveOffhandWeapon( ordnanceName, OFFHAND_ORDNANCE, mods )
}

void function PAS_CooldownReduction_OnKill( entity victim, entity attacker, var damageInfo )
{
	if ( !IsAlive( attacker ) || !IsPilot( attacker ) )
		return

	array<string> weaponMods = GetWeaponModsFromDamageInfo( damageInfo )

	if ( GetCurrentPlaylistVarInt( "featured_mode_tactikill", 0 ) > 0 )
	{
		entity weapon = attacker.GetOffhandWeapon( OFFHAND_LEFT )

		switch ( GetWeaponInfoFileKeyField_Global( weapon.GetWeaponClassName(), "cooldown_type" ) )
		{
			case "grapple":
				attacker.SetSuitGrapplePower( attacker.GetSuitGrapplePower() + 100 )
				break

			case "ammo":
			case "ammo_instant":
			case "ammo_deployed":
			case "ammo_timed":
				int maxAmmo = weapon.GetWeaponPrimaryClipCountMax()
				weapon.SetWeaponPrimaryClipCountNoRegenReset( maxAmmo )
				break

			case "chargeFrac":
				weapon.SetWeaponChargeFraction( 0 )
				break

	//		case "mp_ability_ground_slam":
	//			break

			default:
				Assert( false, weapon.GetWeaponClassName() + " needs to be updated to support cooldown_type setting" )
				break
		}
	}
	else
	{
		if ( !PlayerHasPassive( attacker, ePassives.PAS_CDR_ON_KILL ) && !weaponMods.contains( "tactical_cdr_on_kill" ) )
			return

		entity weapon = attacker.GetOffhandWeapon( OFFHAND_LEFT )

		switch ( GetWeaponInfoFileKeyField_Global( weapon.GetWeaponClassName(), "cooldown_type" ) )
		{
			case "grapple":
				attacker.SetSuitGrapplePower( attacker.GetSuitGrapplePower() + 25 )
				break

			case "ammo":
			case "ammo_instant":
			case "ammo_deployed":
			case "ammo_timed":
				int maxAmmo = weapon.GetWeaponPrimaryClipCountMax()
				weapon.SetWeaponPrimaryClipCountNoRegenReset( min( maxAmmo, weapon.GetWeaponPrimaryClipCount() + ( maxAmmo / 4 ) ) )
				break

			case "chargeFrac":
				weapon.SetWeaponChargeFraction( max( 0, weapon.GetWeaponChargeFraction() - 0.25 ) )
				break

	//		case "mp_ability_ground_slam":
	//			break

			default:
				Assert( false, weapon.GetWeaponClassName() + " needs to be updated to support cooldown_type setting" )
				break
		}
	}
}

void function DisableWeapons( entity player, array<string> excludeNames )
{
	array<entity> weapons = GetPlayerWeapons( player, excludeNames )
	foreach ( weapon in weapons )
		weapon.AllowUse( false )
}

void function EnableWeapons( entity player, array<string> excludeNames )
{
	array<entity> weapons = GetPlayerWeapons( player, excludeNames )
	foreach ( weapon in weapons )
		weapon.AllowUse( true )
}

array<entity> function GetPlayerWeapons( entity player, array<string> excludeNames )
{
	array<entity> weapons = player.GetMainWeapons()
	weapons.extend( player.GetOffhandWeapons() )

	for ( int idx = weapons.len() - 1; idx > 0; idx-- )
	{
		foreach ( excludeName in excludeNames )
		{
			if ( weapons[idx].GetWeaponClassName() == excludeName )
				weapons.remove( idx )
		}
	}

	return weapons
}

void function WeaponAttackWave( entity ent, int projectileCount, entity inflictor, vector pos, vector dir, bool functionref( entity, int, entity, entity, vector, vector, int ) waveFunc )
{
	ent.EndSignal( "OnDestroy" )

	entity weapon
	entity projectile
	int maxCount
	float step
	entity owner
	int damageNearValueTitanArmor
	int count = 0
	array<vector> positions = []
	vector lastDownPos
	bool firstTrace = true

	dir = <dir.x, dir.y, 0.0>
	dir = Normalize( dir )
	vector angles = VectorToAngles( dir )

	if ( ent.IsProjectile() )
	{
		projectile = ent
		string chargedPrefix = ""
		if ( ent.proj.isChargedShot )
			chargedPrefix = "charge_"

		maxCount = expect int( ent.ProjectileGetWeaponInfoFileKeyField( chargedPrefix + "wave_max_count" ) )
		step = expect float( ent.ProjectileGetWeaponInfoFileKeyField( chargedPrefix + "wave_step_dist" ) )
		owner = ent.GetOwner()
		damageNearValueTitanArmor = projectile.GetProjectileWeaponSettingInt( eWeaponVar.damage_near_value_titanarmor )
	}
	else
	{
		weapon = ent
		maxCount = expect int( ent.GetWeaponInfoFileKeyField( "wave_max_count" ) )
		step = expect float( ent.GetWeaponInfoFileKeyField( "wave_step_dist" ) )
		owner = ent.GetWeaponOwner()
		damageNearValueTitanArmor = weapon.GetWeaponSettingInt( eWeaponVar.damage_near_value_titanarmor )
	}

	owner.EndSignal( "OnDestroy" )

	for ( int i = 0; i < maxCount; i++ )
	{
		vector newPos = pos + dir * step

		vector traceStart = pos
		vector traceEndUnder = newPos
		vector traceEndOver = newPos

		if ( !firstTrace )
		{
			traceStart = lastDownPos + <0.0, 0.0, 80.0 >
			traceEndUnder = <newPos.x, newPos.y, traceStart.z - 40.0 >
			traceEndOver = <newPos.x, newPos.y, traceStart.z + step * 0.57735056839> // The over height is to cover the case of a sheer surface that then continues gradually upwards (like mp_box)
		}
		firstTrace = false

		VortexBulletHit ornull vortexHit = VortexBulletHitCheck( owner, traceStart, traceEndOver )
		if ( vortexHit )
		{
			expect VortexBulletHit( vortexHit )
			entity vortexWeapon = vortexHit.vortex.GetOwnerWeapon()

			if ( vortexWeapon && vortexWeapon.GetWeaponClassName() == "mp_titanweapon_vortex_shield" )
				VortexDrainedByImpact( vortexWeapon, weapon, projectile, null ) // drain the vortex shield
			else if ( IsVortexSphere( vortexHit.vortex ) )
				VortexSphereDrainHealthForDamage( vortexHit.vortex, damageNearValueTitanArmor )

			WaitFrame()
			continue
		}

		//DebugDrawLine( traceStart, traceEndUnder, 0, 255, 0, true, 25.0 )
		array ignoreArray = []
		if ( IsValid( inflictor ) && inflictor.GetOwner() != null )
			ignoreArray.append( inflictor.GetOwner() )

		TraceResults forwardTrace = TraceLine( traceStart, traceEndUnder, ignoreArray, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_BLOCK_WEAPONS )
		if ( forwardTrace.fraction == 1.0 )
		{
			//DebugDrawLine( forwardTrace.endPos, forwardTrace.endPos + <0.0, 0.0, -1000.0>, 255, 0, 0, true, 25.0 )
			TraceResults downTrace = TraceLine( forwardTrace.endPos, forwardTrace.endPos + <0.0, 0.0, -1000.0>, ignoreArray, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_BLOCK_WEAPONS )
			if ( downTrace.fraction == 1.0 )
				break

			entity movingGeo = null
			if ( downTrace.hitEnt && downTrace.hitEnt.HasPusherRootParent() && !downTrace.hitEnt.IsMarkedForDeletion() )
				movingGeo = downTrace.hitEnt

			if ( !waveFunc( ent, projectileCount, inflictor, movingGeo, downTrace.endPos, angles, i ) )
				return

			lastDownPos = downTrace.endPos
			pos = forwardTrace.endPos

			WaitFrame()
			continue
		}
		else
		{
			if ( IsValid( forwardTrace.hitEnt ) && (StatusEffect_Get( forwardTrace.hitEnt, eStatusEffect.pass_through_amps_weapon ) > 0) && !CheckPassThroughDir( forwardTrace.hitEnt, forwardTrace.surfaceNormal, forwardTrace.endPos ) )
				break;
		}

		TraceResults upwardTrace = TraceLine( traceStart, traceEndOver, ignoreArray, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_BLOCK_WEAPONS )
		//DebugDrawLine( traceStart, traceEndOver, 0, 0, 255, true, 25.0 )
		if ( upwardTrace.fraction < 1.0 )
		{
			if ( IsValid( upwardTrace.hitEnt ) )
			{
				if ( upwardTrace.hitEnt.IsWorld() || upwardTrace.hitEnt.IsPlayer() || upwardTrace.hitEnt.IsNPC() )
					break
			}
		}
		else
		{
			TraceResults downTrace = TraceLine( upwardTrace.endPos, upwardTrace.endPos + <0.0, 0.0, -1000.0>, ignoreArray, TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_BLOCK_WEAPONS )
			if ( downTrace.fraction == 1.0 )
				break

			entity movingGeo = null
			if ( downTrace.hitEnt && downTrace.hitEnt.HasPusherRootParent() && !downTrace.hitEnt.IsMarkedForDeletion() )
				movingGeo = downTrace.hitEnt

			if ( !waveFunc( ent, projectileCount, inflictor, movingGeo, downTrace.endPos, angles, i ) )
				return

			lastDownPos = downTrace.endPos
			pos = forwardTrace.endPos
		}

		WaitFrame()
	}
}

void function AddActiveThermiteBurn( entity ent )
{
	AddToScriptManagedEntArray( file.activeThermiteBurnsManagedEnts, ent )
}

array<entity> function GetActiveThermiteBurnsWithinRadius( vector origin, float dist, team = TEAM_ANY )
{
	return GetScriptManagedEntArrayWithinCenter( file.activeThermiteBurnsManagedEnts, team, origin, dist )
}

void function EMP_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	Elecriticy_DamagedPlayerOrNPC( ent, damageInfo, FX_EMP_BODY_HUMAN, FX_EMP_BODY_TITAN, EMP_SEVERITY_SLOWTURN, EMP_SEVERITY_SLOWMOVE )
}

void function VanguardEnergySiphon_DamagedPlayerOrNPC( entity ent, var damageInfo )
{
	entity attacker = DamageInfo_GetAttacker( damageInfo )
	if ( IsValid( attacker ) && attacker.GetTeam() == ent.GetTeam() )
		return

	Elecriticy_DamagedPlayerOrNPC( ent, damageInfo, FX_VANGUARD_ENERGY_BODY_HUMAN, FX_VANGUARD_ENERGY_BODY_TITAN, LASER_STUN_SEVERITY_SLOWTURN, LASER_STUN_SEVERITY_SLOWMOVE )
}

void function Elecriticy_DamagedPlayerOrNPC( entity ent, var damageInfo, asset humanFx, asset titanFx, float slowTurn, float slowMove )
{
	if ( !IsValid( ent ) )
		return

	if ( DamageInfo_GetCustomDamageType( damageInfo ) & DF_DOOMED_HEALTH_LOSS )
		return

	local inflictor = DamageInfo_GetInflictor( damageInfo )
	if( !IsValid( inflictor ) )
		return

	// Do electrical effect on this ent that everyone can see if they are a titan
	string tag = ""
	asset effect

	if ( ent.IsTitan() )
	{
		tag = "exp_torso_front"
		effect = titanFx
	}
	else if ( IsStalker( ent ) || IsSpectre( ent ) )
	{
		tag = "CHESTFOCUS"
		effect = humanFx
		if ( !ent.ContextAction_IsActive() && IsAlive( ent ) && ent.IsInterruptable() )
		{
			ent.Anim_ScriptedPlayActivityByName( "ACT_STUNNED", true, 0.1 )
		}
	}
	else if ( IsSuperSpectre( ent ) )
	{
		tag = "CHESTFOCUS"
		effect = humanFx

		if ( ent.GetParent() == null && !ent.ContextAction_IsActive() && IsAlive( ent ) && ent.IsInterruptable() )
		{
			ent.Anim_ScriptedPlayActivityByName( "ACT_STUNNED", true, 0.1 )
		}
	}
	else if ( IsGrunt( ent ) )
	{
		tag = "CHESTFOCUS"
		effect = humanFx
		if ( !ent.ContextAction_IsActive() && IsAlive( ent ) && ent.IsInterruptable() )
		{
			ent.Anim_ScriptedPlayActivityByName( "ACT_STUNNED", true, 0.1 )
			ent.EnableNPCFlag( NPC_PAIN_IN_SCRIPTED_ANIM )
		}
	}
	else if ( IsPilot( ent ) )
	{
		tag = "CHESTFOCUS"
		effect = humanFx
	}
	else if ( IsAirDrone( ent ) )
	{
		if ( GetDroneType( ent ) == "drone_type_marvin" )
			return
		tag = "HEADSHOT"
		effect = humanFx
		thread NpcEmpRebootPrototype( ent, damageInfo, humanFx, titanFx )
	}
	else if ( IsGunship( ent ) )
	{
		tag = "ORIGIN"
		effect = titanFx
		thread NpcEmpRebootPrototype( ent, damageInfo, humanFx, titanFx )
	}

	ent.Signal( "ArcStunned" )

	if ( tag != "" )
	{
		local inflictor = DamageInfo_GetInflictor( damageInfo )
		Assert( !(inflictor instanceof CEnvExplosion) )
		if ( IsValid( inflictor ) )
		{
			float duration = EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MAX
			if ( inflictor instanceof CBaseGrenade )
			{
				local entCenter = ent.GetWorldSpaceCenter()
				local dist = Distance( DamageInfo_GetDamagePosition( damageInfo ), entCenter )
				local damageRadius = inflictor.GetDamageRadius()
				duration = GraphCapped( dist, damageRadius * 0.5, damageRadius, EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MIN, EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MAX )
			}
			thread EMP_FX( effect, ent, tag, duration )
		}
	}

	if ( StatusEffect_Get( ent, eStatusEffect.destroyed_by_emp ) )
		DamageInfo_SetDamage( damageInfo, ent.GetHealth() )

	// Don't do arc beams to entities that are on the same team... except the owner
	entity attacker = DamageInfo_GetAttacker( damageInfo )
	if ( IsValid( attacker ) && attacker.GetTeam() == ent.GetTeam() && attacker != ent )
		return

	if ( ent.IsPlayer() )
	{
		thread EMPGrenade_EffectsPlayer( ent, damageInfo )
	}
	else if ( ent.IsTitan() )
	{
		EMPGrenade_AffectsShield( ent, damageInfo )
		#if MP
		GiveEMPStunStatusEffects( ent, 2.5, 1.0, slowTurn, slowMove )
		#endif
		thread EMPGrenade_AffectsAccuracy( ent )
	}
	else if ( ent.IsMechanical() )
	{
		#if MP
		GiveEMPStunStatusEffects( ent, 2.5, 1.0, slowTurn, slowMove )
		DamageInfo_ScaleDamage( damageInfo, 2.05 )
		#endif
	}
	else if ( ent.IsHuman() )
	{
		#if MP
		DamageInfo_ScaleDamage( damageInfo, 0.99 )
		#endif
	}

	if ( inflictor instanceof CBaseGrenade )
	{
		if ( !ent.IsPlayer() || ent.IsTitan() ) //Beam should hit cloaked targets, when cloak is updated make IsCloaked() function.
			EMPGrenade_ArcBeam( DamageInfo_GetDamagePosition( damageInfo ), ent )
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HACK: might make sense to move this to code
void function NpcEmpRebootPrototype( entity npc, var damageInfo, asset humanFx, asset titanFx )
{
	if ( !IsValid( npc ) )
		return

	npc.EndSignal( "OnDeath" )
	npc.EndSignal( "OnDestroy" )

	if ( !( "rebooting" in npc.s ) )
		npc.s.rebooting <- null

	 if ( npc.s.rebooting ) // npc already knocked down and in rebooting process
		return

	float rebootTime
	vector groundPos
	local nearestNode
	local neighborNodes
	local groundNodePos
	local origin = npc.GetOrigin()
	local startOrigin = origin
	local classname = npc.GetClassName()
	local soundPowerDown
	local soundPowerUp

	//------------------------------------------------------
	// Custom stuff depending on AI type
	//------------------------------------------------------
	switch ( classname )
	{
		case "npc_drone":
			soundPowerDown = "Drone_Power_Down"
			soundPowerUp = "Drone_Power_On"
			rebootTime = DRONE_REBOOT_TIME
			break
		case "npc_gunship":
			soundPowerDown = "Gunship_Power_Down"
			soundPowerUp = "Gunship_Power_On"
			rebootTime = GUNSHIP_REBOOT_TIME
			break
		default:
			Assert( 0, "Unhandled npc type: " + classname )

	}

	//------------------------------------------------------
	// NPC stunned and is rebooting
	//------------------------------------------------------
	npc.Signal( "OnStunned" )
	npc.s.rebooting = true


	//TODO: make drone/gunship slowly drift to the ground while rebooting
	/*
	groundPos = OriginToGround( origin )
	groundPos += Vector( 0, 0, 32 )


	//DebugDrawLine(origin, groundPos, 255, 0, 0, true, 15 )

	//thread AssaultOrigin( drone, groundPos, 16 )
	//thread PlayAnim( drone, "idle" )
	*/


	thread EmpRebootFxPrototype( npc, humanFx, titanFx )
	npc.EnableNPCFlag( NPC_IGNORE_ALL )
	npc.SetNoTarget( true )
	npc.EnableNPCFlag( NPC_DISABLE_SENSING )	// don't do traces to look for enemies or players

	if ( IsAttackDrone( npc ) )
		npc.SetAttackMode( false )

	EmitSoundOnEntity( npc, soundPowerDown )

	wait rebootTime

	EmitSoundOnEntity( npc, soundPowerUp )
	npc.DisableNPCFlag( NPC_IGNORE_ALL )
	npc.SetNoTarget( false )
	npc.DisableNPCFlag( NPC_DISABLE_SENSING )	// don't do traces to look for enemies or players

	if ( IsAttackDrone( npc ) )
		npc.SetAttackMode( true )

	npc.s.rebooting = false
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HACK: might make sense to move this to code
function EmpRebootFxPrototype( npc, asset humanFx, asset titanFx )
{
	expect entity( npc )

	if ( !IsValid( npc ) )
		return

	npc.EndSignal( "OnDeath" )
	npc.EndSignal( "OnDestroy" )

	string classname = npc.GetClassName()
	vector origin
	float delayDuration
	entity fxHandle
	asset fxEMPdamage
	string fxTag
	float rebootTime
	string soundEMPdamage

	//------------------------------------------------------
	// Custom stuff depending on AI type
	//------------------------------------------------------
	switch ( classname )
	{
		case "npc_drone":
			if ( GetDroneType( npc ) == "drone_type_marvin" )
				return
			fxEMPdamage = humanFx
			fxTag = "HEADSHOT"
			rebootTime = DRONE_REBOOT_TIME
			soundEMPdamage = "Titan_Blue_Electricity_Cloud"
			break
		case "npc_gunship":
			fxEMPdamage = titanFx
			fxTag = "ORIGIN"
			rebootTime = GUNSHIP_REBOOT_TIME
			soundEMPdamage = "Titan_Blue_Electricity_Cloud"
			break
		default:
			Assert( 0, "Unhandled npc type: " + classname )

	}

	//------------------------------------------------------
	// Play Fx/Sound till reboot finishes
	//------------------------------------------------------
	fxHandle = ClientStylePlayFXOnEntity( fxEMPdamage, npc, fxTag, rebootTime )
	EmitSoundOnEntity( npc, soundEMPdamage )

	while ( npc.s.rebooting == true )
	{
		delayDuration = RandomFloatRange( 0.4, 1.2 )
		origin = npc.GetOrigin()


		EmitSoundAtPosition( npc.GetTeam(), origin, SOUND_EMP_REBOOT_SPARKS )
		PlayFX( FX_EMP_REBOOT_SPARKS, origin )
		PlayFX( FX_EMP_REBOOT_SPARKS, origin )

		OnThreadEnd(
			function() : ( fxHandle, npc, soundEMPdamage )
			{
				if ( IsValid( fxHandle ) )
					fxHandle.Fire( "StopPlayEndCap" )
				if ( IsValid( npc ) )
					StopSoundOnEntity( npc, soundEMPdamage )
			}
		)

		wait ( delayDuration )
	}
}

function EMP_FX( asset effect, entity ent, string tag, float duration )
{
	if ( !IsAlive( ent ) )
		return

	ent.Signal( "EMP_FX" )
	ent.EndSignal( "OnDestroy" )
	ent.EndSignal( "OnDeath" )
	ent.EndSignal( "StartPhaseShift" )
	ent.EndSignal( "EMP_FX" )

	bool isPlayer = ent.IsPlayer()

	int fxId = GetParticleSystemIndex( effect )
	int attachId = ent.LookupAttachment( tag )

	entity fxHandle = StartParticleEffectOnEntity_ReturnEntity( ent, fxId, FX_PATTACH_POINT_FOLLOW, attachId )
	fxHandle.kv.VisibilityFlags = ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY
	fxHandle.SetOwner( ent )

	OnThreadEnd(
		function() : ( fxHandle, ent )
		{
			if ( IsValid( fxHandle ) )
			{
				EffectStop( fxHandle )
			}

			if ( IsValid( ent ) )
				StopSoundOnEntity( ent, "Titan_Blue_Electricity_Cloud" )
		}
	)

	if ( !isPlayer )
	{
		EmitSoundOnEntity( ent, "Titan_Blue_Electricity_Cloud" )
		wait duration
	}
	else
	{
		EmitSoundOnEntityExceptToPlayer( ent, ent, "Titan_Blue_Electricity_Cloud" )

		var endTime = Time() + duration
		bool effectsActive = true
		while( endTime > Time() )
		{
			if ( ent.IsPhaseShifted() )
			{
				if ( effectsActive )
				{
					effectsActive = false
					if ( IsValid( fxHandle ) )
						EffectSleep( fxHandle )

					if ( IsValid( ent ) )
						StopSoundOnEntity( ent, "Titan_Blue_Electricity_Cloud" )
				}
			}
			else if ( effectsActive == false )
			{
				EffectWake( fxHandle )
				EmitSoundOnEntityExceptToPlayer( ent, ent, "Titan_Blue_Electricity_Cloud" )
				effectsActive = true
			}

			WaitFrame()
		}
	}
}

function EMPGrenade_AffectsShield( entity titan, damageInfo )
{
	int shieldHealth = titan.GetTitanSoul().GetShieldHealth()
	int shieldDamage = int( titan.GetTitanSoul().GetShieldHealthMax() * 0.5 )

	titan.GetTitanSoul().SetShieldHealth( maxint( 0, shieldHealth - shieldDamage ) )

	// attacker took down titan shields
	if ( shieldHealth && !titan.GetTitanSoul().GetShieldHealth() )
	{
		entity attacker = DamageInfo_GetAttacker( damageInfo )
		if ( attacker && attacker.IsPlayer() )
			EmitSoundOnEntityOnlyToPlayer( attacker, attacker, "titan_energyshield_down" )
	}
}

function EMPGrenade_AffectsAccuracy( npcTitan )
{
	npcTitan.EndSignal( "OnDestroy" )

	npcTitan.kv.AccuracyMultiplier = 0.5
	wait EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MAX
	npcTitan.kv.AccuracyMultiplier = 1.0
}


function EMPGrenade_EffectsPlayer( entity player, damageInfo )
{
	player.Signal( "OnEMPPilotHit" )
	player.EndSignal( "OnEMPPilotHit" )

	if ( player.IsPhaseShifted() )
		return

	entity inflictor = DamageInfo_GetInflictor( damageInfo )
	local dist = Distance( DamageInfo_GetDamagePosition( damageInfo ), player.GetWorldSpaceCenter() )
	local damageRadius = 128
	if ( inflictor instanceof CBaseGrenade )
		damageRadius = inflictor.GetDamageRadius()
	float frac = GraphCapped( dist, damageRadius * 0.5, damageRadius, 1.0, 0.0 )
	local strength = EMP_GRENADE_PILOT_SCREEN_EFFECTS_MIN + ( ( EMP_GRENADE_PILOT_SCREEN_EFFECTS_MAX - EMP_GRENADE_PILOT_SCREEN_EFFECTS_MIN ) * frac )
	float fadeoutDuration = EMP_GRENADE_PILOT_SCREEN_EFFECTS_FADE * frac
	float duration = EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MIN + ( ( EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MAX - EMP_GRENADE_PILOT_SCREEN_EFFECTS_DURATION_MIN ) * frac ) - fadeoutDuration
	local origin = inflictor.GetOrigin()

	int dmgSource = DamageInfo_GetDamageSourceIdentifier( damageInfo )
	if ( dmgSource == eDamageSourceId.mp_weapon_proximity_mine || dmgSource == eDamageSourceId.mp_titanweapon_stun_laser )
	{
		strength *= 0.1
	}

	if ( player.IsTitan() )
	{
		// Hit player should do EMP screen effects locally
		Remote_CallFunction_Replay( player, "ServerCallback_TitanCockpitEMP", duration )

		EMPGrenade_AffectsShield( player, damageInfo )

		Remote_CallFunction_Replay( player, "ServerCallback_TitanEMP", strength, duration, fadeoutDuration )
	}
	else
	{
		if ( IsCloaked( player ) )
			player.SetCloakFlicker( 0.5, duration )

		// duration = 0
		// fadeoutDuration = 0

		StatusEffect_AddTimed( player, eStatusEffect.emp, strength, duration, fadeoutDuration )
		//DamageInfo_SetDamage( damageInfo, 0 )
	}

	GiveEMPStunStatusEffects( player, (duration + fadeoutDuration), fadeoutDuration)
}

function EMPGrenade_ArcBeam( grenadePos, ent )
{
	if ( !ent.IsPlayer() && !ent.IsNPC() )
		return

	Assert( IsValid( ent ) )
	local lifeDuration = 0.5

	// Control point sets the end position of the effect
	entity cpEnd = CreateEntity( "info_placement_helper" )
	SetTargetName( cpEnd, UniqueString( "emp_grenade_beam_cpEnd" ) )
	cpEnd.SetOrigin( grenadePos )
	DispatchSpawn( cpEnd )

	entity zapBeam = CreateEntity( "info_particle_system" )
	zapBeam.kv.cpoint1 = cpEnd.GetTargetName()
	zapBeam.SetValueForEffectNameKey( EMP_GRENADE_BEAM_EFFECT )
	zapBeam.kv.start_active = 0
	zapBeam.SetOrigin( ent.GetWorldSpaceCenter() )
	if ( !ent.IsMarkedForDeletion() ) // TODO: This is a hack for shipping. Should not be parenting to deleted entities
	{
		zapBeam.SetParent( ent, "", true, 0.0 )
	}

	DispatchSpawn( zapBeam )

	zapBeam.Fire( "Start" )
	zapBeam.Fire( "StopPlayEndCap", "", lifeDuration )
	zapBeam.Kill_Deprecated_UseDestroyInstead( lifeDuration )
	cpEnd.Kill_Deprecated_UseDestroyInstead( lifeDuration )
}

void function GetWeaponDPS( bool vsTitan = false )
{
	entity player = GetPlayerArray()[0]
	entity weapon = player.GetActiveWeapon()

	local fire_rate = weapon.GetWeaponInfoFileKeyField( "fire_rate" )
	local burst_fire_count = weapon.GetWeaponInfoFileKeyField( "burst_fire_count" )
	local burst_fire_delay = weapon.GetWeaponInfoFileKeyField( "burst_fire_delay" )

	local damage_near_value = weapon.GetWeaponInfoFileKeyField( "damage_near_value" )
	local damage_far_value = weapon.GetWeaponInfoFileKeyField( "damage_far_value" )

	if ( vsTitan )
	{
		damage_near_value = weapon.GetWeaponInfoFileKeyField( "damage_near_value_titanarmor" )
		damage_far_value = weapon.GetWeaponInfoFileKeyField( "damage_far_value_titanarmor" )
	}

	if ( burst_fire_count )
	{
		local timePerShot = 1 / fire_rate
		local timePerBurst = (timePerShot * burst_fire_count) + burst_fire_delay
		local burstPerSecond = 1 / timePerBurst

		printt( timePerBurst )

		printt( "DPS Near", (burstPerSecond * burst_fire_count) * damage_near_value )
		printt( "DPS Far ", (burstPerSecond * burst_fire_count) * damage_far_value )
	}
	else
	{
		printt( "DPS Near", fire_rate * damage_near_value )
		printt( "DPS Far ", fire_rate * damage_far_value )
	}
}


void function GetTTK( string weaponRef, float health = 100.0 )
{
	local fire_rate = GetWeaponInfoFileKeyField_Global( weaponRef, "fire_rate" ).tofloat()
	local burst_fire_count = GetWeaponInfoFileKeyField_Global( weaponRef, "burst_fire_count" )
	if ( burst_fire_count != null )
		burst_fire_count = burst_fire_count.tofloat()

	local burst_fire_delay = GetWeaponInfoFileKeyField_Global( weaponRef, "burst_fire_delay" )
	if ( burst_fire_delay != null )
		burst_fire_delay = burst_fire_delay.tofloat()

	local damage_near_value = GetWeaponInfoFileKeyField_Global( weaponRef, "damage_near_value" ).tointeger()
	local damage_far_value = GetWeaponInfoFileKeyField_Global( weaponRef, "damage_far_value" ).tointeger()

	local nearBodyShots = ceil( health / damage_near_value ) - 1
	local farBodyShots = ceil( health / damage_far_value ) - 1

	local delayAdd = 0
	if ( burst_fire_count && burst_fire_count < nearBodyShots )
		delayAdd += burst_fire_delay

	printt( "TTK Near", (nearBodyShots * (1 / fire_rate)) + delayAdd, " (" + (nearBodyShots + 1) + ")" )


	delayAdd = 0
	if ( burst_fire_count && burst_fire_count < farBodyShots )
		delayAdd += burst_fire_delay

	printt( "TTK Far ", (farBodyShots * (1 / fire_rate)) + delayAdd, " (" + (farBodyShots + 1) + ")" )
}

array<string> function GetWeaponModsFromDamageInfo( var damageInfo )
{
	entity weapon = DamageInfo_GetWeapon( damageInfo )
	entity inflictor = DamageInfo_GetInflictor( damageInfo )
	int damageType = DamageInfo_GetCustomDamageType( damageInfo )

	if ( IsValid( weapon ) )
	{
		return weapon.GetMods()
	}
	else if ( IsValid( inflictor ) )
	{
		if ( "weaponMods" in inflictor.s && inflictor.s.weaponMods )
		{
			array<string> temp
			foreach ( string mod in inflictor.s.weaponMods )
			{
				temp.append( mod )
			}

			return temp
		}
		else if( inflictor.IsProjectile() )
			return inflictor.ProjectileGetMods()
		else if ( damageType & DF_EXPLOSION && inflictor.IsPlayer() && IsValid( inflictor.GetActiveWeapon() ) )
			return inflictor.GetActiveWeapon().GetMods()
		//Hack - Splash damage doesn't pass mod weapon through. This only works under the assumption that offhand weapons don't have mods.
	}
	return []
}

void function OnPlayerGetsNewPilotLoadout( entity player, PilotLoadoutDef loadout )
{
	if ( GetCurrentPlaylistVarInt( "featured_mode_amped_tacticals", 0 ) >= 1 )
	{
		player.GiveExtraWeaponMod( "amped_tacticals" )
	}

	if ( GetCurrentPlaylistVarInt( "featured_mode_all_grapple", 0 ) >= 1 )
	{
		player.GiveExtraWeaponMod( "all_grapple" )
	}

	if ( GetCurrentPlaylistVarInt( "featured_mode_all_phase", 0 ) >= 1 )
	{
		player.GiveExtraWeaponMod( "all_phase" )
	}

	SetPlayerCooldowns( player )
}

void function SetPlayerCooldowns( entity player )
{
	if ( player.IsTitan() )
		return

	array<int> offhandIndices = [ OFFHAND_LEFT, OFFHAND_RIGHT ]

	foreach ( index in offhandIndices )
	{
		float lastUseTime = player.p.lastPilotOffhandUseTime[ index ]
		float lastChargeFrac = player.p.lastPilotOffhandChargeFrac[ index ]
		float lastClipFrac = player.p.lastPilotClipFrac[ index ]

		if ( lastUseTime >= 0.0 )
		{
			entity weapon = player.GetOffhandWeapon( index )
			if ( !IsValid( weapon ) )
				continue

			string weaponClassName = weapon.GetWeaponClassName()

			switch ( GetWeaponInfoFileKeyField_Global( weaponClassName, "cooldown_type" ) )
			{
				case "grapple":
					// GetPlayerSettingsField isn't working for moddable fields? - Bug 129567
					float powerRequired = 100.0 // GetPlayerSettingsField( "grapple_power_required" )
					float regenRefillDelay = 3.0 // GetPlayerSettingsField( "grapple_power_regen_delay" )
					float regenRefillRate = 5.0 // GetPlayerSettingsField( "grapple_power_regen_rate" )
					float suitPowerToRestore = powerRequired - player.p.lastSuitPower
					float regenRefillTime = suitPowerToRestore / regenRefillRate

					float regenStartTime = lastUseTime + regenRefillDelay

					float newSuitPower = GraphCapped( Time() - regenStartTime, 0.0, regenRefillTime, player.p.lastSuitPower, powerRequired )

					player.SetSuitGrapplePower( newSuitPower )
					break

				case "ammo":
				case "ammo_instant":
				case "ammo_deployed":
				case "ammo_timed":
					int maxAmmo = weapon.GetWeaponPrimaryClipCountMax()
					float fireDuration = weapon.GetWeaponSettingFloat( eWeaponVar.fire_duration )
					float regenRefillDelay = weapon.GetWeaponSettingFloat( eWeaponVar.regen_ammo_refill_start_delay )
					float regenRefillRate = weapon.GetWeaponSettingFloat( eWeaponVar.regen_ammo_refill_rate )
					int startingClipCount = int( lastClipFrac * maxAmmo )
					int ammoToRestore = maxAmmo - startingClipCount
					float regenRefillTime = ammoToRestore / regenRefillRate

					float regenStartTime = lastUseTime + fireDuration + regenRefillDelay

					int newAmmo = int( GraphCapped( Time() - regenStartTime, 0.0, regenRefillTime, startingClipCount, maxAmmo ) )

					weapon.SetWeaponPrimaryClipCountAbsolute( newAmmo )
					break

				case "chargeFrac":
					float chargeCooldownDelay = weapon.GetWeaponSettingFloat( eWeaponVar.charge_cooldown_delay )
					float chargeCooldownTime = weapon.GetWeaponSettingFloat( eWeaponVar.charge_cooldown_time )
					float regenRefillTime = lastChargeFrac * chargeCooldownTime
					float regenStartTime = lastUseTime + chargeCooldownDelay

					float newCharge = GraphCapped( Time() - regenStartTime, 0.0, regenRefillTime, lastChargeFrac, 0.0 )

					weapon.SetWeaponChargeFraction( newCharge )
					break

				default:
					printt( weaponClassName + " needs to be updated to support cooldown_type setting" )
					break
			}
		}
	}
}

void function ResetPlayerCooldowns( entity player )
{
	if ( player.IsTitan() )
		return

	array<int> offhandIndices = [ OFFHAND_LEFT, OFFHAND_RIGHT ]

	foreach ( index in offhandIndices )
	{
		float lastUseTime = -99.0//player.p.lastPilotOffhandUseTime[ index ]
		float lastChargeFrac = -1.0//player.p.lastPilotOffhandChargeFrac[ index ]
		float lastClipFrac = 1.0//player.p.lastPilotClipFrac[ index ]

		entity weapon = player.GetOffhandWeapon( index )
		if ( !IsValid( weapon ) )
			continue

		string weaponClassName = weapon.GetWeaponClassName()

		switch ( GetWeaponInfoFileKeyField_Global( weaponClassName, "cooldown_type" ) )
		{
			case "grapple":
				// GetPlayerSettingsField isn't working for moddable fields? - Bug 129567
				float powerRequired = 100.0 // GetPlayerSettingsField( "grapple_power_required" )
				player.SetSuitGrapplePower( powerRequired )
				break

			case "ammo":
			case "ammo_instant":
			case "ammo_deployed":
			case "ammo_timed":
				int maxAmmo = weapon.GetWeaponPrimaryClipCountMax()
				weapon.SetWeaponPrimaryClipCountAbsolute( maxAmmo )
				break

			case "chargeFrac":
				weapon.SetWeaponChargeFraction( 1.0 )
				break

			default:
				printt( weaponClassName + " needs to be updated to support cooldown_type setting" )
				break
		}
	}
}

void function OnPlayerKilled( entity player, entity attacker, var damageInfo )
{
	StoreOffhandData( player )
}

void function StoreOffhandData( entity player, bool waitEndFrame = true )
{
	thread StoreOffhandDataThread( player, waitEndFrame )
}

void function StoreOffhandDataThread( entity player, bool waitEndFrame )
{
	if ( !IsValid( player ) )
		return

	player.EndSignal( "OnDestroy" )

	if ( waitEndFrame )
		WaitEndFrame() // Need to WaitEndFrame so clip counts can be updated if player is dying the same frame

	array<int> offhandIndices = [ OFFHAND_LEFT, OFFHAND_RIGHT ]

	// Reset all values for full cooldown
	player.p.lastSuitPower = 0.0

	foreach ( index in offhandIndices )
	{
		player.p.lastPilotOffhandChargeFrac[ index ] = 1.0
		player.p.lastPilotClipFrac[ index ] = 1.0

		player.p.lastTitanOffhandChargeFrac[ index ] = 1.0
		player.p.lastTitanClipFrac[ index ] = 1.0
	}

	if ( player.IsTitan() )
		return

	foreach ( index in offhandIndices )
	{
		entity weapon = player.GetOffhandWeapon( index )
		if ( !IsValid( weapon ) )
			continue

		string weaponClassName = weapon.GetWeaponClassName()

		switch ( GetWeaponInfoFileKeyField_Global( weaponClassName, "cooldown_type" ) )
		{
			case "grapple":
				player.p.lastSuitPower = player.GetSuitGrapplePower()
				break

			case "ammo":
			case "ammo_instant":
			case "ammo_deployed":
			case "ammo_timed":

				if ( player.IsTitan() )
				{
					if ( !weapon.IsWeaponRegenDraining() )
						player.p.lastTitanClipFrac[ index ] = min( 1.0, weapon.GetWeaponPrimaryClipCount() / float( weapon.GetWeaponPrimaryClipCountMax() ) ) //Was returning greater than one with extraweaponmod timing.
					else
						player.p.lastTitanClipFrac[ index ] = 0.0
				}
				else
				{
					if ( !weapon.IsWeaponRegenDraining() )
						player.p.lastPilotClipFrac[ index ] = min( 1.0, weapon.GetWeaponPrimaryClipCount() / float( weapon.GetWeaponPrimaryClipCountMax() ) ) //Was returning greater than one with extraweaponmod timing.
					else
						player.p.lastPilotClipFrac[ index ] = 0.0
				}
				break

			case "chargeFrac":
				if ( player.IsTitan() )
					player.p.lastTitanOffhandChargeFrac[ index ] = weapon.GetWeaponChargeFraction()
				else
					player.p.lastPilotOffhandChargeFrac[ index ] = weapon.GetWeaponChargeFraction()
				break

			default:
				printt( weaponClassName + " needs to be updated to support cooldown_type setting" )
				break
		}
	}
}
#endif // #if SERVER

void function PlayerUsedOffhand( entity player, entity offhandWeapon )
{
	array<int> offhandIndices = [ OFFHAND_LEFT, OFFHAND_RIGHT, OFFHAND_ANTIRODEO, OFFHAND_EQUIPMENT ]

	foreach ( index in offhandIndices )
	{
		entity weapon = player.GetOffhandWeapon( index )
		if ( !IsValid( weapon ) )
			continue

		if ( weapon != offhandWeapon )
			continue

		#if SERVER
			if ( player.IsTitan() )
				player.p.lastTitanOffhandUseTime[ index ] = Time()
			else
				player.p.lastPilotOffhandUseTime[ index ] = Time()

			#if MP
				string weaponName = offhandWeapon.GetWeaponClassName()
				if ( weaponName != "mp_ability_grapple" ) // handled in CodeCallback_OnGrapple   // nope, it's not (?)
				{
					string category
					float duration
					if ( index == OFFHAND_EQUIPMENT && player.IsTitan() )
					{
						category = "core"
						duration = -1
					}
					else
					{
						category = ""
						duration = Time() - offhandWeapon.GetNextAttackAllowedTimeRaw()
					}
					PIN_PlayerAbility( player, category, weaponName, {}, duration )
				}
			#endif
		#endif // SERVER

		#if HAS_TITAN_TELEMETRY && CLIENT
			ClTitanHints_ClearOffhandHint( index )
		#endif

		#if HAS_TITAN_TELEMETRY && SERVER
			TitanHints_NotifyUsedOffhand( index )
		#endif

		return
	}
}

RadiusDamageData function GetRadiusDamageDataFromProjectile( entity projectile, entity owner )
{
	RadiusDamageData radiusDamageData

	radiusDamageData.explosionDamage = -1
	radiusDamageData.explosionDamageHeavyArmor = -1

	if ( owner.IsNPC() )
	{
		radiusDamageData.explosionDamage = projectile.GetProjectileWeaponSettingInt( eWeaponVar.npc_explosion_damage )
		radiusDamageData.explosionDamageHeavyArmor = projectile.GetProjectileWeaponSettingInt( eWeaponVar.npc_explosion_damage_heavy_armor )
	}

	if ( radiusDamageData.explosionDamage == -1 )
		radiusDamageData.explosionDamage = projectile.GetProjectileWeaponSettingInt( eWeaponVar.explosion_damage )

	if ( radiusDamageData.explosionDamageHeavyArmor == -1 )
		radiusDamageData.explosionDamageHeavyArmor = projectile.GetProjectileWeaponSettingInt( eWeaponVar.explosion_damage_heavy_armor )

	radiusDamageData.explosionRadius = projectile.GetProjectileWeaponSettingFloat( eWeaponVar.explosionradius )
	radiusDamageData.explosionInnerRadius = projectile.GetProjectileWeaponSettingFloat( eWeaponVar.explosion_inner_radius )

	Assert( radiusDamageData.explosionRadius > 0, "Created RadiusDamageData with 0 radius" )
	Assert( radiusDamageData.explosionDamage > 0 || radiusDamageData.explosionDamageHeavyArmor > 0, "Created RadiusDamageData with 0 damage" )
	return radiusDamageData
}

#if SERVER
void function Thermite_DamagePlayerOrNPCSounds( entity ent )
{
	if ( ent.IsTitan() )
	{
		if ( ent.IsPlayer() )
		{
		 	EmitSoundOnEntityOnlyToPlayer( ent, ent, "titan_thermiteburn_3p_vs_1p" )
			EmitSoundOnEntityExceptToPlayer( ent, ent, "titan_thermiteburn_1p_vs_3p" )
		}
		else
		{
		 	EmitSoundOnEntity( ent, "titan_thermiteburn_1p_vs_3p" )
		}
	}
	else
	{
		if ( ent.IsPlayer() )
		{
		 	EmitSoundOnEntityOnlyToPlayer( ent, ent, "flesh_thermiteburn_3p_vs_1p" )
			EmitSoundOnEntityExceptToPlayer( ent, ent, "flesh_thermiteburn_1p_vs_3p" )
		}
		else
		{
		 	EmitSoundOnEntity( ent, "flesh_thermiteburn_1p_vs_3p" )
		}
	}
}
#endif

#if SERVER
void function RemoveThreatScopeColorStatusEffect( entity player )
{
	for ( int i = file.colorSwapStatusEffects.len() - 1; i >= 0; i-- )
	{
		entity owner = file.colorSwapStatusEffects[i].weaponOwner
		if ( !IsValid( owner ) )
		{
			file.colorSwapStatusEffects.remove( i )
			continue
		}
		if ( owner == player )
		{
			StatusEffect_Stop( player, file.colorSwapStatusEffects[i].statusEffectId )
			file.colorSwapStatusEffects.remove( i )
		}
	}
}

void function AddThreatScopeColorStatusEffect( entity player )
{
	ColorSwapStruct info
	info.weaponOwner = player
	info.statusEffectId = StatusEffect_AddTimed( player, eStatusEffect.cockpitColor, COCKPIT_COLOR_THREAT, 100000, 0 )
	file.colorSwapStatusEffects.append( info )
}
#endif