File: doofus.cpp

package info (click to toggle)
postal1 2015.git20250526%2Bds-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 14,024 kB
  • sloc: cpp: 130,877; ansic: 38,942; python: 874; makefile: 351; sh: 61
file content (4116 lines) | stat: -rw-r--r-- 122,401 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// doofus.cpp
// Project: Postal
//
// This module implements the CDoofus class which is the class of enemy
//	guys for the game.  
//
// History:
//		01/13/97 BRH	Started this file from CDude and modified it
//							to do some enemy logic using the same assets
//							as the sample 2D guy.  
//
//		01/15/97 BRH	Changed the render to draw the guy with his 
//							hotspot between his feet.
//
//		02/04/97	JMI	Changed LoadDib() call to Load() (which now supports
//							loading of DIBs).
//
//		02/05/97 BRH	Fixed problem loading Instance ID.  Also fixed some other
//							problems with the run routine.  He now will follow the 
//							bouys to get to the bouy nearest the CDude.
//
//		02/23/97 BRH	Changed coordinate system to x, -z in Find Direction.
//
//		02/25/97 BRH	Fixed problem with the Startup where the height was not
//							being multiplied by 4, so enemies would start too low
//							if placed on a roof.
//
//		03/04/97 BRH	Derived this from CCharacter instead of CThing
//
//		03/05/97 BRH	Added SelectRandomBouy function which picks a random
//							bouy number (a valid one) or returns 0 if there are
//							no bouys.
//
//		03/06/97 BRH	Added realignment timer and function so that the
//							direction to the bouy can be recalculated every
//							so often to avoid missing it.
//
//		03/13/97	JMI	Load now takes a version number.
//
//		03/14/97	JMI	SelectDude() now chooses the closest dude on the X/Z plane.
//
//		04/04/97	JMI	SelectDude() no longer chooses dead dudes.
//							Also, last update to make SelectDude() find the closest 
//							CDude was not comparing the distance to the CDude from this
//							guy, but instead was comparing the distance to the CDude from
//							(0, 0, 0).
//
//		04/16/97 BRH	Changed references to the realm's list of CThings to use
//							the new non-STL methods.
//
//		04/22/97 BRH	Moved common code and some variables like the animations
//							to the base class.  Put common logic routines like the
//							reactions to weapons in this base class.
//
//		04/24/97 BRH	Added TryClearDirection function that uses the 
//							IsPathClear() funciton to try 3 directions to see if they
//							are clear.
//
//		05/02/97	JMI	Added check to make sure not already in shot state or
//							writhing state before changing to shot state in OnShotMsg.
//							Also, now OnBurnMsg() sets him into the m_animOnFire in-
//							stead of m_animRun.
//
//		05/04/97 BRH	Removed #ifdef code sections referring to STL lists.
//
//		05/06/97 BRH	Added Popout logic, detection smash.
//
//		05/09/97 BRH	Added Writhing and Shot logic from CPerson.
//
//		05/11/97 BRH	Fixed problem with Logic_Guard.
//
//		05/15/97 BRH	In the popout and run & shoot wait states, changed from
//							the temporary timeout method to checking for the
//							triggered pylon before running the logic.
//
//		05/18/97 BRH	Added some logic functions for the victims to use.
//
//		05/20/97 BRH	Added the hiding states.  Also added calls to 
//							ReevaluateState() at times in the action cycles
//							where the action can be changed.  Changed Logic_PylonDetect
//							to set flags for use in ReevaluateState() and
//							in the logic table variables evaluation.
//
//		05/21/97 BRH	Added m_dAnimRot to specify the direction the guy is 
//							facing and separating that from the direction he is
//							moving.  This will be used for the run and shoot
//							so that he can run and face sideways.  
//
//		05/22/97 BRH	Fixed typo bug in Logic_Shoot.
//
//		05/25/97 BRH	Added the m_ShootAngle variable and an override for
//							ShootWeapon that uses this angle to aim the weapon.
//
//		05/26/97 BRH	Changed ShootWeapon so that CSmash bits are passed in
//							so that enemy bullets don't hit other enemies.
//
//		05/26/97 BRH	Added a timer for shooting to limit the number of shots
//							for each type of gun.  Also added some avoidance 
//							of obstacles during MoveNext in case the guy gets stuck
//							trying to get to the next bouy.
//
//		05/27/97 BRH	Fixed a few problems with logic table transitions.
//
//		05/27/97 BRH	Added some avoidance of obstacles to Logic_PopBegin in
//							case he gets stuck on walls while trying to find the 
//							first pylon.
//
//		05/31/97	JMI	Replaced m_pDude with m_idDude.  The problem was that, by
//							just using a pointer to the dude, we never found out when
//							the dude was gone (deleted).  Although this is rare for
//							CDudes, it does happen.  For example, in the beginning of
//							a level all CDudes that do not have an associated player
//							are sent a Delete msg.  They do not process this message
//							until their respective Update() calls.  If a CDoofus 
//							derived guy happened to be placed in the level before a 
//							CDude (that is, the CDoofus' Update() got called before the
//							CDude's), and the CDoofus happened to point its m_pDude at 
//							this CDude (that was destined to soon be deleted), later 
//							when referencing the pointer to the freed and/or reallocated
//							memory, the CDoofus could cause a protection	fault or	math 
//							overflow (due to invalid values returned by 
//							m_pDude->GetX, Y, Z() with the non-CDude 'this' pointer).
//							Also, in the case that SelectDude() did not select a dude,
//							SQDistanceToDude() was returning an unitialized double
//							which, in some cases, could be a totally illegal double
//							value.
//
//		06/02/97 BRH	Added AdvanceHold action and state so that once he reaches
//							the end of the advancement, he goes into this hold state
//							rather than Engage automatically.  This way the logic
//							table can have more control over the next state.
//
//		06/02/97 BRH	Changed TryClearShot to use the CRealm version of
//							IsPathClear which just checks for terrain obstacles.
//
//		06/05/97	JMI	Changed m_sHitPoints to m_stockpile.m_sHitPoints to 
//							accommodate new m_stockpile in base class, CThing3d (which
//							used to contain the m_sHitPoints).
//
//		06/10/97 BRH	Now sends messages to CDemon for Explosion, and burning.
//
//		06/10/97 BRH	Added RunIdleAnimation() function which monitors the
//							idle timer and controls which of 3 idle animations to
//							use.  This should be called when in some kind of wait
//							state.
//
//		06/10/97 BRH	Fixed "YMCA" bug where the enemy guy would cycle 
//							each frame between Advance and AdvanceHold.
//
//		06/11/97 BRH	Fixed the crouch and search animations since the
//							search is done from the crouch posiiton.  It was
//							previously backwards because I thought the search
//							animation was done from a standing position.
//
//		06/13/97	JMI	Changed FindDirection() to return m_dRot if we cannot find
//							a CDude.
//							Also, changed Logic_Shoot() over to using events.
//
//		06/17/97 BRH	Changed NEAR_DEATH_HITPOINTS to a higher value since the
//							machine gun bullets were increased, it was diffucult to
//							get a writhing person.
//
//		06/17/97 BRH	Attempted to make enemies stop shooting dead CDudes.
//
//		06/17/97	JMI	Now doubles smash radius when in writhing state.
//
//		06/18/97	JMI	Changed PlaySoundWrithing() to return the duration of the
//							played sample.
//
//		06/18/97 BRH	Changed over to using GetRandom()
//
//		06/24/97	JMI	Added intialization of m_sRotateDir.
//
//		06/26/97 BRH	Added a special case for Writhers who get burned. 
//							Previously they didn't react because their smash bits
//							were changed when they went into writhing.  Then we wanted
//							them to get killed by fire so included the AlmostDead bits
//							but they they would jump to their feet and run around
//							once they got burned.  So now they will just lie there
//							and die.
//
//		06/26/97 BRH	When a doofus is killed after preparing a weapon but 
//							before shooting it, he will drop it if it was a throwing
//							weapon, but will just delete it if it was a launched
//							weapon.
//
//		06/27/97 BRH	Added a flag for recently stuck so that when a character
//							gets stuck on a wall, he sets the flag, then when he gets
//							free of the obstacle, it will get the closest bouy rather
//							than trying to align to the one it was trying to get to
//							previously which many times caused him to get stuck in 
//							the same manner.
//
//		06/28/97 BRH	Changed the RegisterBirth and RegisterDeath calls to pass 
//							m_bCivilian so that the scoring can updated for hostiles
//							or civilians.
//
//		07/09/97 BRH	Added logic for walking and running around on a bouy
//							network - used for victims.
//
//		07/11/97 BRH	Added call to inline Cheater() to disable game if necessary
//
//		07/12/97 BRH	Added addional text strings for the new actions that were
//							added.  Also changed PylonDetect function to use 
//							QuickCheckClosest rather than QuickCheck so that enemies
//							will detect the pylon you put them closest to and not
//							just a marker pylon.
//
//		07/12/97 BRH	Changed macro MAX_STEPUP_THRESHOLD to use the CThing3d
//							definitino MaxStepUpThreshold so that the detecting and
//							ability to move will be the same.
//
//		07/15/97 BRH	Added a few more calls to Cheater.
//
//		07/20/97 BRH	Effectively canceled the DelayShoot state by setting
//							the timeout to zero since it caused the guys to
//							not shoot very often on levels that were difficult
//							to move in.
//
//		07/21/97	JMI	Now Update() calls base class version.
//
//		07/23/97 BRH	Added tunable values for different timeouts which will get
//							set in doofus to the default static values that they were
//							before, and can be set in Person to the personatorium values
//							so that different people have different traits.
//
//		08/01/97 BRH	Changed the aiming so that it is based on the game
//							difficulty setting.
//
//		08/02/97 BRH	Added YellForHelp funciton that enemies can call when they
//							get shot to alert others in the are that they need help.
//
//		08/05/97 BRH	Fixed the problem with the doofus leaving the Run&Shoot
//							state at higher difficulty settings due to re-aligning
//							the angles with the shoot angle.	  
//
//		08/06/97 BRH	Changed TryClearShot to first do the point translation
//							to the rigid body where the weapon is shot from, in order
//							to get the correct height.  This will give the guys more
//							opportunities to shoot, and will work when the guys
//							are scaled larger or smaller.
//
//		08/06/97	JMI	Added m_ptransExecutionTarget link point for execution
//							sphere.  Also, added PositionSmash() to provide overridable
//							method for updating the collision sphere.
//
//		08/06/97	JMI	Now TryClearPath() returns false if there's no weapon
//							link point.
//
//		08/07/97	JMI	Added ms_awdWeapons[], ms_apszWeaponResNames[], and 
//							GetResources() and FreeResources() for loading these anims.
//							Also, added ms_lWeaponResRefCount so we could know when the
//							weapons were no longer needed.
//
//		08/08/97	JMI	Now Logic_Shoot() handles flamer.
//
//		08/08/97	JMI	Now Logic_Shoot() handles AutoRifle, Uzi, and SmallPistol.
//
//		08/08/97 BRH	Added start and end bouy ID's for special cases like
//							marching.  Added these to load and save.  They are set
//							by the dialog in the CPerson.  Also added marching logic.
//
//		08/09/97 BRH	Changed panic to be vicinity based so only the nearby
//							people panic.  Also added checks for prepared weapons
//							when guys get blown up or burned, where they should
//							either randomly discard their weapon, or delete it.
//
//		08/10/97	JMI	Moved CDoofus() and ~CDoofus() into doofus.cpp from 
//							doofus.h.
//							Was going to move the registering of the birth into the
//							constructor but I realized that m_bCivilian probably won't
//							get set until Load() so I left it in Startup() (it could
//							probably also get set via EditModify() but this doesn't 
//							matter b/c that's in edit mode only).
//							Now Registers death with the realm in the destructor if 
//							m_bRegisteredBirth is true.
//							Also, now OnShotMsg() calls base class version even if
//							other states don't permit a state change b/c this gives
//							better feedback to the user (base class OnShotMsg() creates
//							blood).
//
//		08/10/97	JMI	Moved NoWeapon up to enum value 0 and created a new one
//							to take its -1 place as an invalid weapon (InvalidWeapon).
//							Also, added block in PrepareWeapon() for the NoWeapon case.
//							Also, moved prepare weapon from the .H to the .CPP.
//
//		08/11/97 BRH	Found the problem with the parade level victims where they
//							were flipping around one bouy.  The problem was that they
//							asked how to get to a particular bouy which was unreachable
//							because the network was not fully connected, so when it
//							got the unreachable flag, it kept retrying the same bouy.  
//							I fixed the problem so they will pick a new bouy, but also
//							we are deleting the unconnected nodes in the parade level.
//								
//		08/11/97	JMI	Now sets backup weapon to default 'none' and uses the 
//							backup weapon when there's no animation for the current
//							weapon type.
//							Also, changed incorrectly name ms_awtType2Id to 
//							ms_awtId2Type mapping.
//
//		08/11/97 BRH	Fixed problem with run & shoot not using the correct
//							angle.
//
//		08/12/97	JMI	Now hides weapon if current event is 10 or more.
//
//		08/12/97 BRH	Checks for events channel in render so that people
//							without animation events like the band guys will still
//							work.  Also made shooting timing based on game
//							difficulty.
//
//		08/13/97	JMI	Changed so OnShotMsg() calls base class to generate blood
//							no matter what.
//
//		08/14/97	JMI	Switched references to g_GameSettings.m_sDifficulty to
//							m_pRealm->m_flags.sDifficulty.
//
//		08/14/97 BRH	Added static default bits to pass to weapons for their
//							collision testing.  Changed call to WhileHoldingWeapon
//							to include these defaults.
//
//		08/15/97 BRH	Changed the check for available pylons to check for a
//							clear path to the pylon before saying it is available.
//							Some guys were getting stuck on fences between themselves
//							an an available pylon.  Also fixed the writhing to
//							executed transition so that the guys don't flip around
//							180 degrees.  Also fixed the smash bits that get passed
//							to the missile weapons.
//
//		08/16/97 BRH	Changed the person's PlaySound functions so that comments
//							are only made when the CDude is alive.  So in this module, I
//							made sure that the victims were also calling SelectDude()
//							for the logic that they were doing, just to keep track of
//							whether the CDude was alive or dead.  Also tuned the
//							shooting accuracy for the levels to make them more accurate
//							on the easier levels since the easy dudes were missing too
//							much.
//
//		08/18/97 BRH	Added virtual override for CCharacter's WhileHoldingWeapon
//							so that for higher difficulty settings where the enemies
//							re-aim after preparing the weapon, they could do it
//							every frame between PrepareWeapon and ShootWeapon so that
//							they turned smoothy and didn't just flip around when they
//							got to ShootWeapon.  This was a problem with the Rocketman
//							who had a long shoot animation.  If the target moved a
//							quite a bit between PrepareWeapon and ShootWeapon, he would
//							spin around just before releasing the shot.  Also fixed
//							a problem with the ShootWeapon adjustment of the
//							random shooting innacuracy when I changed the values 
//							last time, I adjusted the max left swing, but forgot to
//							adjust the random amount.
//
//		08/18/97	JMI	Now sends doofuses who are writhing to the back most sprite
//							layer.  As people pointed out this is another of two evils.
//							It is, however, a lessor.  It appears a little wierd in one
//							case but better in all others I've seen so far.
//
//		08/19/97	JMI	Now sends doofuses who are dying to the back as well.
//
//		08/19/97	JMI	No longer shoots CSmash::Misc items.
//
//		08/20/97	JMI	Now Logic_Shot() does not wait to the end of the animation
//							to check for death.  This way they don't seem to kick back
//							from the shot, shoot forward, and then die.
//
//		08/20/97 BRH	Trying a smaller tolerance on the Bouys so that the
//							enemies must get closer to the hotspot before
//							moving to the next one.  We wanted to see if this helps
//							certain situations where guys are getting stuck.  Changed
//							from 10 pixel radius to 5.
//
//		08/21/97	JMI	Now does deluxe reporting on whether this doofus finds his
//							NavNet. 
//
//		08/21/97	JMI	Now after reporting that the doofus did not find its NavNet
//							it sets him to the current NavNet.
//
//		08/21/97 BRH	Added a blooc counter so that the number of blood pools
//							created while writhing could be cut down a little bit.
//
//		08/24/97 BRH	Changed the TryClearShot to use the Character version of
//							IsPathClear which also checks for people in the way.  Added
//							an additional call to TryClearShot in ShootWeapon which is
//							after the weapon has been re-aimed to make sure that the
//							path is still clear.  It was a problem with the rocketman
//							who has the slowest animation and may turn completely
//							around before shooting.
//
//		08/24/97 BRH	Aborts sample that was playing when the guy gets executed
//							so that he doesn't keep making noises after he is dead.
//
//		08/25/97 BRH	Undid a bunch of changes made yesterday which changed the
//							logic too much which threw off the tuning.  Added two new
//							escape routes for the Engage mode instead.  Fixed the 
//							shoot timer which was being set to two different values
//							in two different places.  Made the shooting more accurate
//							and more of the difficulty tuning will be with the 
//							shooting times.
//
//		08/27/97 BRH	Victims now panic when they are shot.
//
//		09/03/97	JMI	Sentries now exclude CSmash::Bads and CSmash::Civilians.
//
//		09/07/97 BRH	As Steve requested, the medium difficulty will now
//							re-adjust aiming just like hard difficulty in ShootWeapon.
//
//		12/18/97	JMI	Changed SelectRandomBouy() to return 0 if a the number of
//							bouys is less than or equal to one.  It used to be less 
//							than one but, for some reason, GetNumNodes() returns 1 when
//							there's no bouys.  This caused it to lock up when no bouys
//							for some lgk files.
//
////////////////////////////////////////////////////////////////////////////////
#define DOOFUS_CPP

#include "RSPiX.h"
#include <math.h>

#include "doofus.h"
#include "dude.h"
#include "SampleMaster.h"
#include "grenade.h"
#include "pylon.h"

////////////////////////////////////////////////////////////////////////////////
// Macros/types/etc.
////////////////////////////////////////////////////////////////////////////////

#define	NEAR_DEATH_HITPOINTS 31							// Below this, start writhing
#define  MS_BETWEEN_SAMPLES	100						// Time between pain groans.
#define  BURNT_BRIGHTNESS		-40						// -128 to 127.

////////////////////////////////////////////////////////////////////////////////
// Variables/data
////////////////////////////////////////////////////////////////////////////////

// These are default values -- actually values are set using the editor!
double CDoofus::ms_dAccUser     = 150.0;				// Acceleration due to user
double CDoofus::ms_dAccDrag     = 80.0;				// Acceleration due to drag

double CDoofus::ms_dMaxVelFore  = 80.0;				// Maximum forward velocity
double CDoofus::ms_dMaxVelBack  = -60.0;				// Maximum backward velocity

double CDoofus::ms_dDegPerSec   = 150.0;				// Degrees of rotation per second
double CDoofus::ms_dOffScreenDistance = 500*500;	// Square distance off screen
double CDoofus::ms_dGuardDistance = 300*300;			// Square distance before attacking
double CDoofus::ms_dThrowHorizVel = 200;				// Throw out at this velocity
double CDoofus::ms_dMinFightDistance = 80.0;			// Closest you want to get
double CDoofus::ms_dMedFightDistance = 200.0;		// Median distance for fighting
double CDoofus::ms_dMaxFightDistance = 400.0;		// Farthest distance for fighting
double CDoofus::ms_dMinFightDistanceSQ = 80.0*80.0;// Square distance for 
double CDoofus::ms_dMedFightDistanceSQ	= 200.0*200.0;
double CDoofus::ms_dMaxFightDistanceSQ = 400.0*400.0;	
double CDoofus::ms_dMarchVelocity = 20.0;				// Speed at which to march
int32_t CDoofus::ms_lDefaultAlignTime = 100; //2000;	// Time to realign to bouy position
int32_t CDoofus::ms_lGuardTimeoutMin = 4000;				// Time to check for CDudes again
int32_t CDoofus::ms_lGuardTimeoutInc = 500;				// Interval to add for each easier difficulty level
int32_t CDoofus::ms_lShootTimeoutMin = 1000;				// Min time between shots, adjused for difficulty
int32_t CDoofus::ms_lShootTimeoutInc = 200;				// Adjustment time for difficulty level between shots
int32_t CDoofus::ms_lDetectionRadius = 100;//80			// Radius of detection smash sphere
int32_t CDoofus::ms_lRunShootInterval = 2000;			// Time between shots while running
int32_t CDoofus::ms_lReseekTime = 15 * 1000;				// Seek the dude again after this time
int32_t CDoofus::ms_lShotTimeout = 3000;					// Time between full shot reaction animations
																	// which gives him a chance to attack or run
int32_t CDoofus::ms_lStuckRecoveryTime = 5000;			// Time to stay in recoverys state
int32_t CDoofus::ms_lAvoidRadius = 40;						// Radius of fire detection smash
int32_t CDoofus::ms_lYellRadius = 150;						// Yell for help in this vicinity
int32_t CDoofus::ms_lHelpTimeout = 3000;					// Time to react to a call for help.
int32_t CDoofus::ms_lDelayShootTimeout = 0; //2000;			// Time before shooting
int32_t CDoofus::ms_lHelpingTimeout = 1000;				// Only shoot every this often

// Note that these seem to apply to all weapons except bullet weapons.  That is, these are
// passed to WhileHoldingWeapon() which passes them on to ShootWeapon(), but WhileHoldingWeapon()
// is only used for non-bullet weapons.  In the bullet weapons case, it uses the default parameters
// to ShootWeapon().
U32 CDoofus::ms_u32CollideBitsInclude = CSmash::Character | CSmash::Barrel;
U32 CDoofus::ms_u32CollideBitsDontcare = CSmash::Good | CSmash::Bad;
U32 CDoofus::ms_u32CollideBitsExclude = CSmash::SpecialBarrel | CSmash::Ducking | CSmash::Bad | CSmash::Civilian;

int16_t CDoofus::ms_sStuckLimit = 3;						// Number of times to retry before attempting to
																	// get free of whatever you are stuck on.

// Weapon animations.
CAnim3D	CDoofus::ms_aanimWeapons[NumWeaponTypes];
// Current ref count on ms_aanimWeapons[].
int32_t		CDoofus::ms_lWeaponResRefCount	= 0;

// Weapon details (descriptions, res names, etc.).
CDoofus::WeaponDetails	CDoofus::ms_awdWeapons[NumWeaponTypes]	=
{
	//////// NoWeapon
	{	// pszName, pszResName, CThing ID
		"Verbal Abuse",
		NULL,
		TotalIDs,
	},

	//////// Rocket
	{	// pszName, pszResName, CThing ID
		"Rocket",
		"3d/launcher",
		CRocketID,
	},

	//////// Grenade
	{	// pszName, pszResName, CThing ID
		"Grenade",
		NULL,
		CGrenadeID,
	},

	//////// Napalm
	{	// pszName, pszResName, CThing ID
		"Napalm",
		"3d/napalmer",
		CNapalmID,
	},

	//////// Firebomb
	{	// pszName, pszResName, CThing ID
		"Cocktail",
		NULL,
		CFirebombID,
	},

	//////// ProximityMine
	{	// pszName, pszResName, CThing ID
		"ProximityMine",
		NULL,
		CProximityMineID,
	},

	//////// TimedMine
	{	// pszName, pszResName, CThing ID
		"TimedMine",
		NULL,
		CTimedMineID,
	},

	//////// RemoteMine
	{	// pszName, pszResName, CThing ID
		"RemoteMine",
		NULL,
		CRemoteControlMineID,
	},

	//////// BouncingBetty
	{	// pszName, pszResName, CThing ID
		"BouncingBetty",
		NULL,
		CBouncingBettyMineID,
	},

	//////// Flamer
	{	// pszName, pszResName, CThing ID
		"Flamer",
		"3d/flmthrower",
		CFirestreamID,
	},

	//////// Pistol
	{	// pszName, pszResName, CThing ID
		"Pistol",		
		"3d/bigpistol",
		CPistolID,
	},

	//////// MachineGun
	{	// pszName, pszResName, CThing ID
		"MachineGun",
		"3d/submachine",
		CMachineGunID,
	},

	//////// ShotGun
	{	// pszName, pszResName, CThing ID
		"ShotGun",
		"3d/ShotGun",
		CShotGunID,
	},

	//////// Heatseeker
	{	// pszName, pszResName, CThing ID
		"Heatseeker",
		"3d/launcher",
		CHeatseekerID,
	},

	//////// Assault
	{	// pszName, pszResName, CThing ID
		"Assault",
		"3d/SprayGun",
		CAssaultWeaponID,
	},

	//////// DeathWad
	{	// pszName, pszResName, CThing ID
		"DeathWad",
		"3d/napalmer",
		CDeathWadID,
	},

	//////// DoubleBarrel
	{	// pszName, pszResName, CThing ID
		"DoubleBarrel",
		"3d/shotgun",
		CDoubleBarrelID,
	},

	//////// Uzi
	{	// pszName, pszResName, CThing ID
		"Uzi",
		"3d/Uzi",
		CUziID,
	},

	//////// AutoRifle
	{	// pszName, pszResName, CThing ID
		"AutoRifle",
		"3d/AutoRifle",
		CAutoRifleID,
	},

	//////// SmallPistol
	{	// pszName, pszResName, CThing ID
		"SmallPistol",
		"3d/Pistol",
		CSmallPistolID,
	},

	//////// Dynamite
	{	// pszName, pszResName, CThing ID
		"Dynamite",
		NULL,
		CDynamiteID,
	},


};

// Maps a CThing ID to a WeaponType enum.
CDoofus::WeaponType	CDoofus::ms_awtId2Type[TotalIDs]	=	
{
	NoWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	Rocket,
	Grenade,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	Napalm,
	InvalidWeapon,
	InvalidWeapon,
	Firebomb,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	ProximityMine,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	Pistol,
	MachineGun,
	ShotGun,
	InvalidWeapon,
	TimedMine,
	BouncingBettyMine,
	RemoteControlMine,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	Heatseeker,
	InvalidWeapon,
	Assault,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	InvalidWeapon,
	Flamer,
	DeathWad,
	DoubleBarrel,
	Uzi,
	AutoRifle,
	SmallPistol,
	Dynamite,
};

char* CDoofus::ms_apszActionNames[] = 
{
	"Guard",
	"Advance",
	"Retreat",
	"Engage",
	"Popout",
	"Run&Shoot",
	"Hide",
	"Advance-Hold",
	"Walk",
	"Panic",
	"March",
	"Madness",
	"Help",
};

// Let this auto-init to 0
int16_t CDoofus::ms_sFileCount;


//
//

////////////////////////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////////////////////////
CDoofus::CDoofus(CRealm* pRealm, ClassIDType id)
	: CCharacter(pRealm, id)
	{
	m_sSuspend = 0;
	m_pNavNet = NULL;
	m_u16NavNetID = 0;
	m_idDude = CIdBank::IdNil;
	m_pNextBouy = NULL;
	m_sNextX = m_sNextZ = 0;
	m_ucDestBouyID = m_ucNextBouyID = 0;
	m_lAlignTimer = 0;
	m_lEvalTimer = 0;
	m_lShootTimer = 0;
	m_lShotTimeout = 0;
	m_pPylonStart = NULL;
	m_pPylonEnd = NULL;
	m_lCommentTimer = 0;
	m_usCommentCounter = 0;
	m_lLastHelpCallTime = 0;
	m_lSampleTimeIsPlaying = 0;
	m_bRecentlyStuck = false;
	m_bCivilian = false;
	m_ptransExecutionTarget	= NULL;
	m_spriteWeapon.m_pthing	= this;
	m_ucSpecialBouy0ID = 0;
	m_ucSpecialBouy1ID = 0;
	m_bPanic = false;
	m_bRegisteredBirth = false;
	// Default to no fallback weapon.
	m_eFallbackWeaponType	= TotalIDs;
	m_sStuckCounter = 0;
	m_usBloodCounter = 0;
	m_siPlaying = 0;

    // explicitly initialize to stop Valgrind whining. --ryan.
	m_lIdleTimer = pRealm->m_time.GetGameTime() + 2000 + GetRandom() % 2000;
	m_lStuckTimeout = 0;

	m_u16KillerId = 0;
	}

////////////////////////////////////////////////////////////////////////////////
// Destructor
////////////////////////////////////////////////////////////////////////////////
CDoofus::~CDoofus()
	{
	// If we've been born . . .
	if (m_bRegisteredBirth == true)
		{
		// See who killed us, if anyone
		bool bPlayerKill = false;
		CThing*	pthing;
		if (m_u16KillerId != 0 && m_pRealm->m_idbank.GetThingByID(&pthing, m_u16KillerId) == 0)
			if (pthing->GetClassID() == CDudeID)
				bPlayerKill = true; // Dude killed us.

		// Good bye.
		m_pRealm->RegisterDeath(m_bCivilian, bPlayerKill);
		}
	}

////////////////////////////////////////////////////////////////////////////////
// Load object (should call base class version!)
////////////////////////////////////////////////////////////////////////////////
int16_t CDoofus::Load(										// Returns 0 if successfull, non-zero otherwise
	RFile* pFile,											// In:  File to load from
	bool bEditMode,										// In:  True for edit mode, false otherwise
	int16_t sFileCount,										// In:  File count (unique per file, never 0)
	uint32_t	ulFileVersion)									// In:  Version of file format to load.
	{
	int16_t sResult = CCharacter::Load(pFile, bEditMode, sFileCount, ulFileVersion);

	if (sResult == SUCCESS)
	{
		// Load common data just once per file (not with each object)
		if (ms_sFileCount != sFileCount)
		{
			ms_sFileCount = sFileCount;

			// Load static data
			switch (ulFileVersion)
			{
				default:
				case 1:
					pFile->Read(&ms_dAccUser);
					pFile->Read(&ms_dAccDrag);
					pFile->Read(&ms_dMaxVelFore);
					pFile->Read(&ms_dMaxVelBack);
					pFile->Read(&ms_dDegPerSec);
					// Clear the panic flag at the load of a level.
					m_bPanic = false;
					break;
			}
		}

		// Load object data

		switch (ulFileVersion)
		{
			default:
			case 43:
				pFile->Read(&m_ucSpecialBouy0ID);
				pFile->Read(&m_ucSpecialBouy1ID);

			case 42:
			case 41:
			case 40:
			case 39:
			case 38:
			case 37:
			case 36:
			case 35:
			case 34:
			case 33:
			case 32:
			case 31:
			case 30:
			case 29:
			case 28:
			case 27:
			case 26:
			case 25:
			case 24:
			case 23:
			case 22:
			case 21:
			case 20:
			case 19:
			case 18:
			case 17:
			case 16:
			case 15:
			case 14:
			case 13:
			case 12:
			case 11:
			case 10:
			case 9:
			case 8:
			case 7:
			case 6:
			case 5:
			case 4:
			case 3:
			case 2:
			case 1:
				// Get the instance ID for the NavNet
				U16 u16Data;
				int16_t sres = pFile->Read(&u16Data);
				m_u16NavNetID = u16Data;
				break;
		}
		
		// Make sure there were no file errors
		if (!pFile->Error())
		{
			// Get resources
		}
		else
		{
			sResult = -1;
			TRACE("CDoofus::Load(): Error reading from file!\n");
		}
	}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
// Save object (should call base class version!)
////////////////////////////////////////////////////////////////////////////////
int16_t CDoofus::Save(										// Returns 0 if successfull, non-zero otherwise
	RFile* pFile,											// In:  File to save to
	int16_t sFileCount)										// In:  File count (unique per file, never 0)
	{
	// Call the base class save to save the u16InstanceID
	int16_t sResult = CCharacter::Save(pFile, sFileCount);
	if (sResult == SUCCESS)
	{
		// Save common data just once per file (not with each object)
		if (ms_sFileCount != sFileCount)
			{
			ms_sFileCount = sFileCount;

			// Save static data
			pFile->Write(&ms_dAccUser);
			pFile->Write(&ms_dAccDrag);
			pFile->Write(&ms_dMaxVelFore);
			pFile->Write(&ms_dMaxVelBack);
			pFile->Write(&ms_dDegPerSec);
			}

		// Save object data

		// Save the instance ID for the parent NavNet so it can be connected
		// again after load
		pFile->Write(&m_ucSpecialBouy0ID);
		pFile->Write(&m_ucSpecialBouy1ID);
		U16 u16Data = CIdBank::IdNil;	// Safety.
		if (m_pNavNet)
			u16Data	= m_pNavNet->GetInstanceID();
		pFile->Write(&u16Data);

		sResult = pFile->Error();
	}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
// Startup object
////////////////////////////////////////////////////////////////////////////////
int16_t CDoofus::Startup(void)								// Returns 0 if successfull, non-zero otherwise
{
	CCharacter::Startup();

	// If we don't have a pointer to the Nav Net yet, get it from the ID
	if (m_pNavNet == NULL)
		{
		if (m_pRealm->m_idbank.GetThingByID((CThing**) &m_pNavNet, m_u16NavNetID) == 0)
			{
			// Verify it's a NavNet . . .
			if (m_pNavNet->GetClassID() == CNavigationNetID)
				{
				// Wahoo.
				}
			else
				{
				m_pNavNet	= NULL;
				}
			}

		// If still no nav net . . .
		if (m_pNavNet == NULL)
			{
			// Message depends on user mode.
			if (m_pRealm->m_flags.bEditing)
				{
				rspMsgBox(
					RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
					g_pszAppName,
					g_pszDoofusCannotFindNavNet_EditMode_hu_hu,
					m_u16InstanceId,
					m_u16NavNetID);
				}
			else
				{
				rspMsgBox(
					RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
					g_pszAppName,
					g_pszDoofusCannotFindNavNet_PlayMode_hu_hu,
					m_u16InstanceId,
					m_u16NavNetID);
				}

			// Use the current NavNet.
			m_pNavNet	= m_pRealm->GetCurrentNavNet();
			if (m_pNavNet)
				{
				// Remember to reset our ID so this doesn't happen again.
				m_u16NavNetID	= m_pNavNet->GetInstanceID();
				}
			}
		}

	// Clear stuck counter
	m_sStuckCounter = 0;

	// Init other stuff
	m_dVel = 0.0;
	m_dRot = 0.0;
	m_dAnimRot = 0.0;
	m_sPrevHeight = (int16_t) m_dY;
	m_sRotateDir = 0;

	// Set up the detection smash
	m_smashDetect.m_pThing = this;
	m_smashDetect.m_bits = 0;
	m_smashDetect.m_sphere.sphere.lRadius = ms_lDetectionRadius;

	// Set up the fire avoidance smash
	m_smashAvoid.m_sphere.sphere.X = m_dX + (rspCos(m_dRot) * ms_lAvoidRadius);
	m_smashAvoid.m_sphere.sphere.Y = m_dY;
	m_smashAvoid.m_sphere.sphere.Z = m_dZ - (rspSin(m_dRot) * ms_lAvoidRadius);
	m_smashAvoid.m_sphere.sphere.lRadius = ms_lAvoidRadius;
	m_smashAvoid.m_bits = 0;
	m_smashAvoid.m_pThing = this;

	// Setup weapon sprite.
	m_spriteWeapon.m_sInFlags	= CSprite::InHidden;
	m_sprite.AddChild(&m_spriteWeapon);


	// Start in a neutral state
	m_state = State_Idle;
	// Hello, world.
	m_pRealm->RegisterBirth(m_bCivilian);
	// Note that we've registered our birth so we know later that we need to
	// register our death.
	m_bRegisteredBirth	= true;

	// Set tunable values to their doofus defaults
	m_lShootTimeout = ms_lShootTimeoutMin + ((11-m_pRealm->m_flags.sDifficulty) * ms_lShootTimeoutInc);
	m_lRunShootInterval = ms_lRunShootInterval;
	m_lShotReactionTimeout = ms_lShotTimeout;

	return 0;
}


////////////////////////////////////////////////////////////////////////////////
// Called by editor to init new object at specified position
////////////////////////////////////////////////////////////////////////////////
int16_t CDoofus::EditNew(									// Returns 0 if successfull, non-zero otherwise
	int16_t sX,												// In:  New x coord
	int16_t sY,												// In:  New y coord
	int16_t sZ)												// In:  New z coord
{
	int16_t sResult = 0;

	CCharacter::EditNew(sX, sY, sZ);	

	// Since we were just created in the editor, set our nav net to the
	// current one for this realm.
	m_pNavNet = m_pRealm->GetCurrentNavNet();
	m_u16NavNetID = m_pNavNet->GetInstanceID();

	return sResult;
}

////////////////////////////////////////////////////////////////////////////////
// Render - This override version temporarily replaces the m_dRot with the
//				m_dAnimRot so that it draws the person in the desired facing 
//				direction.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Render(void)
{
	double dSaveRotation = m_dRot;
	m_dRot = m_dAnimRot;

	CCharacter::Render();
	
	m_dRot = dSaveRotation;

	CAnim3D*		panimWeapon	= NULL;

	if (m_panimCur->m_pevent)
	{	
		// Get current event.
		U8	u8Event	= *( (U8*)(m_panimCur->m_pevent->GetAtTime(m_lAnimTime) ) );

		// If gun not hidden by Randy . . .
		if (u8Event < 10)
		{
			panimWeapon	= GetWeaponAnim(m_eWeaponType);
			// If we got an anim . . .
			if (panimWeapon)
			{
				// If this anim is empty (and not intentional) . . .
				if (panimWeapon->m_pmeshes == NULL && m_eWeaponType != TotalIDs)
				{
					// Get fallback weapon, if any.
					panimWeapon	= GetWeaponAnim(m_eFallbackWeaponType);
				}
			}
		}
	}

	// If we have a visible weapon . . .
	if (panimWeapon)
	{
		// If we have the necessary components . . .
		if (panimWeapon->m_pmeshes && m_panimCur->m_ptransWeapon)
		{
			// Show weapon sprite.
			m_spriteWeapon.m_sInFlags	&= ~CSprite::InHidden;

			m_spriteWeapon.m_pmesh		= panimWeapon->m_pmeshes->GetAtTime(m_lAnimTime);
			m_spriteWeapon.m_psop		= panimWeapon->m_psops->GetAtTime(m_lAnimTime);
			m_spriteWeapon.m_ptex		= panimWeapon->m_ptextures->GetAtTime(m_lAnimTime);
			m_spriteWeapon.m_psphere	= panimWeapon->m_pbounds->GetAtTime(m_lAnimTime);
			m_spriteWeapon.m_ptrans		= m_panimCur->m_ptransWeapon->GetAtTime(m_lAnimTime);
		}
		else
		{
			// Hide weapon sprite.
			m_spriteWeapon.m_sInFlags	|= CSprite::InHidden;
		}
	}
	else
	{
		// Hide weapon sprite.
		m_spriteWeapon.m_sInFlags	|= CSprite::InHidden;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Called by editor to render object
////////////////////////////////////////////////////////////////////////////////
void CDoofus::EditRender(void)
{
	// In some cases, object's might need to do a special-case render in edit
	// mode because Startup() isn't called.  In this case it doesn't matter, so
	// we can call the normal Render().
	Render();
}

////////////////////////////////////////////////////////////////////////////////
// SelectDude
////////////////////////////////////////////////////////////////////////////////

int16_t CDoofus::SelectDudeBouy(void)
{
	int16_t sReturn = SUCCESS;
//	CDude* pDude;
//	CBouy* pBouytest;

	if (SelectDude() == SUCCESS)
		{
		CDude*	pdude;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pdude, m_idDude) == 0)
			{
			m_ucDestBouyID = m_pNavNet->FindNearestBouy(pdude->GetX(), pdude->GetZ());
			}
		}
	else
		sReturn = FAILURE;

/*
	if (m_pRealm->m_asClassNumThings[CThing::CDudeID] > 0)
	{
		pDude = (CDude*) m_pRealm->m_aclassHeads[CThing::CDudeID].GetNext();
		m_ucDestBouyID = m_pNavNet->FindNearestBouy(pDude->GetX(), pDude->GetZ());
	}
	else
	{
		if (m_pNavNet->GetNumNodes() < 1)
			sReturn = FAILURE;
		else
		{
			pBouytest = NULL;
			while (pBouytest == NULL)		
			{
				m_ucDestBouyID = GetRandom() % m_pNavNet->GetNumNodes();
				pBouytest = m_pNavNet->GetBouy(m_ucDestBouyID);		
			}
		}
	}
*/
	return sReturn;

}

////////////////////////////////////////////////////////////////////////////////
// SelectRandomBouy - make sure it exists before setting it
////////////////////////////////////////////////////////////////////////////////

uint8_t CDoofus::SelectRandomBouy(void)
{
	uint8_t ucSelect = 0;
	CBouy* pBouy = NULL;

	if (m_pNavNet->GetNumNodes() <= 1)
		return 0;

	while (pBouy == NULL)
	{
		ucSelect = GetRandom() % m_pNavNet->GetNumNodes();
		pBouy = m_pNavNet->GetBouy(ucSelect);
	}
	return ucSelect;
}

////////////////////////////////////////////////////////////////////////////////
// SelectDude - Picks the closest dude from the dude list and assignes it to
//					 this enemy's CDude pointer.
////////////////////////////////////////////////////////////////////////////////

int16_t CDoofus::SelectDude(void)
{
//	Things::iterator i;
//	Things* pDudes;

	m_idDude = CIdBank::IdNil;
	uint32_t	ulSqrDistance;
	uint32_t	ulCurSqrDistance	= 0xFFFFFFFF;
	uint32_t	ulDistX;
	uint32_t	ulDistZ;
//	pDudes = m_pRealm->m_apthings[CThing::CDudeID];
	CDude*	pdude;

	CListNode<CThing>* pDudeList = m_pRealm->m_aclassHeads[CThing::CDudeID].m_pnNext;

	while (pDudeList && pDudeList->m_powner)
	{
		pdude = (CDude*) pDudeList->m_powner;
		// If this dude is not dead . . .
		if (pdude->m_state != State_Dead)
		{
			ulDistX	= pdude->m_dX - m_dX;
			ulDistZ	= pdude->m_dZ - m_dZ;
			ulSqrDistance	= ulDistX * ulDistX + ulDistZ * ulDistZ;
			if (ulSqrDistance < ulCurSqrDistance)
			{
				// This one is closer.
				ulCurSqrDistance	= ulSqrDistance;
				m_idDude	= pdude->GetInstanceID();
			}
		}
		pDudeList = pDudeList->m_pnNext;
	}

	return (m_idDude != CIdBank::IdNil) ? SUCCESS : FAILURE;
}

////////////////////////////////////////////////////////////////////////////////
// FindDirection - gives the direction toward the cDude
////////////////////////////////////////////////////////////////////////////////

int16_t CDoofus::FindDirection()
{
	int16_t sAngle;
	double dDudeX;
	double dDudeZ;
	double dX;
	double dZ;

	if (m_idDude == CIdBank::IdNil)
		SelectDude();

	if (m_idDude != CIdBank::IdNil)
	{
		CDude*	pdude;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pdude, m_idDude) == 0)
		{
			dDudeX = pdude->GetX();
			dDudeZ = pdude->GetZ();
			dX = dDudeX - m_dX;
			dZ = m_dZ - dDudeZ;
			sAngle = rspATan(dZ, dX);
		}
		else
			sAngle = m_dRot;
	}
	else
		sAngle = m_dRot;

	return sAngle;
}

////////////////////////////////////////////////////////////////////////////////
// Return the square of the distance to the guy (to test for proximity
////////////////////////////////////////////////////////////////////////////////

double CDoofus::SQDistanceToDude()
{
	double dSquareDistance	= 0.0;
	double dX;
	double dZ;
		
	if (m_idDude == CIdBank::IdNil)
		SelectDude();

	if (m_idDude != CIdBank::IdNil)
	{
		CDude*	pdude;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pdude, m_idDude) == 0)
		{
			dX = pdude->GetX() - m_dX;
			dZ = pdude->GetZ() - m_dZ;
			dSquareDistance = (dX * dX) + (dZ * dZ);
		}
	}

	return dSquareDistance;
}


////////////////////////////////////////////////////////////////////////////////
// AlignToBouy - When timer is up, recalculate direction to bouy
////////////////////////////////////////////////////////////////////////////////

void CDoofus::AlignToBouy(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	if (lThisTime > m_lAlignTimer || m_bRecentlyStuck)
	{
		// If he got stuck and is now free, pick a new bouy
		if (m_bRecentlyStuck)
		{
			m_bRecentlyStuck = false;
			m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);

			if (m_ucNextBouyID > 0)
			{
				m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
				if (m_pNextBouy != NULL)
				{
					m_sNextX = m_pNextBouy->GetX();
					m_sNextZ = m_pNextBouy->GetZ();			
				}
			}
		}
		m_lAlignTimer = lThisTime + ms_lDefaultAlignTime;
		m_dAnimRot = m_dRot = rspATan(m_dZ - m_sNextZ, m_sNextX - m_dX);
	}
}

////////////////////////////////////////////////////////////////////////////////
// TryClearDirection - Given an angle, and a variance, checks the given angle
//							  to see if it is clear.  If it is blocked by walls or fire
//							  it will try the max variance in either direction for a 
//							  clear path and set the angle if it finds one.  If these
//							  three angles fail, it will return false.
//
// Enemy guys can use this to attempt several paths before moving.  If it fails
// then they can fall back on using a random direction, or they could try again
//	with a completely different angle and variance.
////////////////////////////////////////////////////////////////////////////////

bool CDoofus::TryClearDirection(double* pdRot, int16_t sVariance)
{
	bool bFoundPath = false;
	int16_t sTries = 0;
	int16_t sX, sY, sZ;
	double dRotAttempt = *pdRot;
	CThing* pthing;

	while (!bFoundPath && sTries < 2)
	{
		// Check clear path
		if (IsPathClear(							// Returns true, if the entire path is clear.
														// Returns false, if only a portion of the path is clear.
														// (see *psX, *psY, *psZ, *ppthing).
			m_dX,										// In:  Starting X.
			m_dY,										// In:  Starting Y.
			m_dZ,										// In:  Starting Z.
			dRotAttempt,							// In:  Rotation around y axis (direction on X/Z plane).
			10,										// In:  Rate at which to scan ('crawl') path in pixels per
														// iteration.
														// NOTE: We scan terrain using GetFloorAttributes()
														// so small values of sCrawl are not necessary.
														// NOTE: We could change this to a speed in pixels per second
														// where we'd assume a certain frame rate.
			200,										// In:  Range on X/Z plane.
			m_smash.m_sphere.sphere.lRadius,	// In:  Radius of path traverser.
			MaxStepUpThreshold,					// In:  Max traverser can step up.
			CSmash::Fire,							// In:  Mask of CSmash bits that would terminate path.
			CSmash::Bad | CSmash::Good,		// In:  Mask of CSmash bits that would not affect path.
			CSmash::Dead,							// In:  Mask of CSmash bits that cannot affect path.
			&sX,										// Out: Point of intercept, if any, on path.
			&sY,										// Out: Point of intercept, if any, on path.
			&sZ,										// Out: Point of intercept, if any, on path.
			&pthing,									// Out: Thing that intercepted us or NULL, if none.
			&m_smash)								// In:  Optional CSmash to exclude or NULL, if none.
			== false)
			{
				switch (sTries)
				{
					case 0:
						dRotAttempt = rspMod360(dRotAttempt + (sVariance/2));
						break;
					case 1:
						dRotAttempt = rspMod360(dRotAttempt - sVariance);
						break;
				}
			}
			else
			{
				bFoundPath = true;
				*pdRot = dRotAttempt;
			}

			sTries++;
	}

	return bFoundPath;
}

////////////////////////////////////////////////////////////////////////////////
// TryClearShot - Works like the TryClearDirection, but doesn't check for 
//						fire, only walls.  So it knows if it could hit the target
//						from here.
////////////////////////////////////////////////////////////////////////////////

bool CDoofus::TryClearShot(double dRot, int16_t sVariance)
{
	bool bFoundPath = false;

	// If we have a weapon transform . . .
	if (m_panimCur->m_ptransRigid)
	{
		int16_t sTries = 0;
		int16_t sX, sY, sZ;
		CThing* pthing = NULL;
		double dRotAttempt = dRot;

		// Do a translation to the weapon position so that it is at the correct
		// height for checking

		double	dMuzzleX, dMuzzleY, dMuzzleZ;
		GetLinkPoint(														// Returns nothing.
			m_panimCur->m_ptransRigid->GetAtTime(m_lAnimTime),	// In:  Transform specifying point.
			&dMuzzleX,														// Out: Point speicfied.
			&dMuzzleY,														// Out: Point speicfied.
			&dMuzzleZ);														// Out: Point speicfied.			// Update execution point via link point.

		while (!bFoundPath && sTries < 2)
		{
			// Check clear path
/*
				// This one checks terrain and for people in the way
				if (IsPathClear(
					(short) (m_dX + dMuzzleX),			// Start x position
					(short) (m_dY + dMuzzleY),			// Start y position
					(short) (m_dZ + dMuzzleZ),			// Start z position
					(short) dRotAttempt,					// Angle of shot
					4,											// Crawl rate
					rspSqrt(CDoofus::SQDistanceToDude()),
					2,											// radius of traverser
					2,											// vertical tolerance
					CSmash::Bad,							// Bits that would terminate path
					0,											// Bits that would not affect path
					0,											// Bits that cannot affect path
					&sX,										// pointer to terminating point
					&sY,										// pointer to terminating point
					&sZ,										// pointer to terminating point
					&pthing,									// handle to terminating target
					&m_smash)								// exclude your own smash
					== false)
*/
				// This one only checks terrain
				if (m_pRealm->IsPathClear(
					 m_dX + dMuzzleX,
					 m_dY + dMuzzleY,
					 m_dZ + dMuzzleZ,
					 (int16_t) dRotAttempt,
					 3,
					 rspSqrt(CDoofus::SQDistanceToDude()),
					 0,
					 &sX,
					 &sY,
					 &sZ)
					 == false)

				{
					switch (sTries)
					{
						case 0:
							dRotAttempt = rspMod360(dRotAttempt + (sVariance/2));
							break;
						case 1:
							dRotAttempt = rspMod360(dRotAttempt - sVariance);
							break;
					}
				}
				else
				{
					bFoundPath = true;
				}

				sTries++;
		}
	}

	return bFoundPath;
}

////////////////////////////////////////////////////////////////////////////////
// Update - default implementation of logic for enemy characters
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Update(void)
{
	if (!m_sSuspend)
	{
		int32_t lThisTime = m_pRealm->m_time.GetGameTime();

		// Check for new messages that may change the state
		ProcessMessages();

		// If he has no network, then he should stick to Guard mode
//		if (m_pNavNet == NULL)
//			m_state = State_Guard;

		// See if there are any pylons nearby that he wants to use.
		if (m_state == State_Idle || 
		    m_state == State_Wait ||
			 m_state == State_Hunt)
			Logic_PylonDetect();
	 
		switch (m_state)
		{
			case State_Guard:
				Logic_Guard();
				break;

			case State_PopBegin:
				Logic_PopBegin();
				break;

			case State_PopWait:
				Logic_PopWait();
				break;

			case State_Popout:
				Logic_Popout();
				break;

			case State_RunShootBegin:
				Logic_RunShootBegin();
				break;

			case State_RunShoot:
				Logic_RunShoot();
				break;

			case State_RunShootWait:
				Logic_RunShootWait();
				break;

			case State_Shoot:
				Logic_Shoot();
				break;

			case State_Hunt:
				Logic_Hunt();
				break;

			case State_HuntNext:
				Logic_MoveNext();
				break;

			case State_Shot:
				Logic_Shot();
				break;

			case State_BlownUp:
				Logic_BlownUp();
				break;

			case State_Burning:
				Logic_Burning();
				break;

			case State_Die:
				Logic_Die();
				break;

			case State_Dead:
				CCharacter::OnDead();
				delete this;
				return;
				break;

		}	

		// Determine appropriate position for main smash.
		PositionSmash();

		// Update the smash.
		m_pRealm->m_smashatorium.Update(&m_smash);
		
		m_lPrevTime = lThisTime;

		// Call base class //////////////////////////////////////////////////////

		CCharacter::Update();
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Shot - You got shot so check your damage
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Shot(void)
{
	if (m_stockpile.m_sHitPoints > NEAR_DEATH_HITPOINTS)
	// Restore previous state & go back to what you were doing
	{
		// If your shot animation is over...
		if (m_lAnimTime > m_panimCur->m_psops->TotalTime())
		{
			// Add this check for low health -> retreat
			// if (m_stockpile.m_sHitPoints < DefHitPoints / 2)
			//{
			//	m_state = State_Retreat;
			//	m_panimCur = &m_animRun;
			//	m_lAnimTime = 0;
			//	m_dRot = rspMod360(CDoofus::FindDirection() + 180);
			//	if (CDoofus::TryClearDirection(&m_dRot, 90) == false)
			//		m_dRot = rspMod360(GetRandom());
			//}
			// 
			// else // go back to previous state
			m_state = m_ePreviousState;
			m_panimCur = m_panimPrev;
			m_lAnimTime = 0;
		}
		else
		// Else continue shot animation
		{
			m_lAnimTime += m_pRealm->m_time.GetGameTime() - m_lPrevTime;
		}

		Cheater();
	}
	else
	// else you are dead or writhing so die
	{
		m_state = State_Die;
		m_panimCur = &m_animDie;
		m_lAnimTime = 0;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_BlownUp - You were blown up so pop up into the air and come down again
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_BlownUp(void)
{
	// Make him animate
	m_lAnimTime += (m_pRealm->m_time.GetGameTime() - m_lPrevTime);

	if (!WhileBlownUp())
		m_state = State_Dead;
	else
		UpdateFirePosition();

	Cheater();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Burning - You are on fire, so run aroudn burning until you are dead
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Burning(void)
{
	m_lAnimTime += m_pRealm->m_time.GetGameTime() - m_lPrevTime;

	if (!CCharacter::WhileBurning())
	{
		m_state = State_Die;
		m_lAnimTime = 0;
		m_panimCur = &m_animDie;
	}

	Cheater();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Die - You are about to die, so look like it!
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Die(void)
{
	// Change our smashatorium bits
	// enable this if you want them to always writhe when dead - for testing
#if 0
	if ((m_smash.m_bits & CSmash::AlmostDead) == 0)
	{
		m_smash.m_bits |= CSmash::AlmostDead;
		m_stockpile.m_sHitPoints = 30;
	}
#else
	m_smash.m_bits |= CSmash::AlmostDead;
#endif

	// Send to back.
	m_sLayerOverride	= CRealm::LayerSprite1; 

	// When the die animation is finsihed, so are you.
	if (m_lAnimTime > m_panimCur->m_psops->TotalTime())
	{
		if (m_stockpile.m_sHitPoints > 0)
		{
			m_state = State_Writhing;
			m_panimCur = &m_animWrithing;
			m_lAnimTime = 0;
			GameMessage msg;
			msg.msg_Writhing.eType = typeWrithing;
			msg.msg_Writhing.sPriority = 0;
			CThing* pDemon = m_pRealm->m_aclassHeads[CThing::CDemonID].GetNext();
			if (pDemon)
				SendThingMessage(&msg, pDemon);				
		}
		else
		{
			m_state = State_Dead;
		}
	}	
	else
	{
		CWeapon* pweapon;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pweapon, m_u16IdWeapon) == 0)
		{
			// It should drop like a rock if its a throwing weapon or just delete it if it
			// is a launched weapon
			if (m_eWeaponType == CHeatseekerID || m_eWeaponType == CRocketID || m_eWeaponType == CNapalmID)
			{
				GameMessage msg;
				msg.msg_ObjectDelete.eType = typeObjectDelete;
				msg.msg_ObjectDelete.sPriority = 0;
				SendThingMessage(&msg, pweapon);
			}
			else
			{
				pweapon->m_dHorizVel = (GetRandom() % (int16_t) CGrenade::ms_dThrowHorizVel);
				m_dShootAngle = pweapon->m_dRot = GetRandom() % 360;
				ShootWeapon();
			}
		}
		m_lAnimTime += m_pRealm->m_time.GetGameTime() - m_lPrevTime;

#if 0  // causes people to spin when they die. --ryan.
		// Rotate him so that he doesn't fall the same way
		// Don't rotate again if he was writhing and has been executed
		if (m_panimCur != &m_animExecuted)
		{
			short sRot = GetRandom() % 2;
			if (sRot & 0x01)
				sRot++;

			if (((short) m_dRot) & 0x01)
				m_dAnimRot = m_dRot = rspMod360(m_dRot + sRot);
			else
				m_dAnimRot = m_dRot = rspMod360(m_dRot - sRot);
		}
#endif
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Writhing - Rolling around on the ground in pain, waiting to be
//						  executed or until the pain is no longer tolerable.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Writhing(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lTimeDifference = lThisTime - m_lPrevTime;

	// Send to back.
	m_sLayerOverride	= CRealm::LayerSprite1; 

	if (m_lAnimTime > m_panimCur->m_psops->TotalTime())
	{
		if (--m_stockpile.m_sHitPoints <= 0)
		{
			// Die. - Run the executed anim first to transition between the
			// writhing animation and being dead, otherwise some characters will
			// die on their knees.
			m_state = State_Die;
			m_panimCur = &m_animExecuted;
			m_lAnimTime = 0;
//			m_state = State_Dead;
		}
		else
		{
			// Whoa!  MOD EQUALS is deep, man!
			m_lAnimTime	%= m_panimCur->m_psops->TotalTime();
			// Now you can tune the amount of blood if it gets too thick.
			if ((++m_usBloodCounter % 2) == 0)
				MakeBloodPool();

			if (lThisTime >= m_lTimer)
			{
				// Launch a sample and get the duration of the sample.
				int32_t	lSampleDuration;
				PlaySoundWrithing(&lSampleDuration);

				m_lTimer	= lThisTime	+ lSampleDuration + MS_BETWEEN_SAMPLES;
			}
		}
	}
	else
	{	
		CWeapon*	pweapon;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pweapon, m_u16IdWeapon) == 0)
		{
			// It should drop like a rock if its a throwing weapon or just delete it if it
			// is a launched weapon
			if (m_eWeaponType == CHeatseekerID || m_eWeaponType == CRocketID || m_eWeaponType == CNapalmID)
			{
				GameMessage msg;
				msg.msg_ObjectDelete.eType = typeObjectDelete;
				msg.msg_ObjectDelete.sPriority = 0;
				SendThingMessage(&msg, pweapon);
			}
			else
			{
				pweapon->m_dHorizVel = (GetRandom() % (int16_t) CGrenade::ms_dThrowHorizVel);
				m_dShootAngle = pweapon->m_dRot = GetRandom() % 360;
				ShootWeapon();
			}
		}
		m_lAnimTime += lTimeDifference;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Guard - Guard the area until a CDude is nearby
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Guard(void)
{
	int32_t lThisTime;
	int32_t lTimeDifference;
	double dSeconds;

	// Get new time
	lThisTime = m_pRealm->m_time.GetGameTime();
	lTimeDifference = lThisTime - m_lPrevTime;
	m_eCurrentAction = Action_Guard;

	// Calculate the elapsed time in seconds
	dSeconds = (double)(lThisTime - m_lPrevTime) / 1000.0;

//	if (m_panimCur != &m_animStand)
//	{
//		m_panimCur = &m_animStand;
//		m_lAnimTime = 0;
//	}
	m_dRot = m_dAnimRot = m_dShootAngle = FindDirection();
	RunIdleAnimation();

	// We assume at first that nothing much is going on in the area, so he
	// only evaluates CDude position every once in a while to cut down on
	// the processing.
	if (lThisTime > m_lTimer)
	{
		m_eCurrentAction = Action_Guard;
		m_lTimer = lThisTime + m_lGuardTimeout;
		if (SelectDude() == SUCCESS && SQDistanceToDude() < ms_dGuardDistance)
		{	
			if (CDoofus::TryClearShot(m_dRot, 20) == true)
			{
				CWeapon*	pweapon	= PrepareWeapon();
				if (pweapon != NULL)
				{
					// Keep it hidden, for now.
					pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
					pweapon->SetRangeToTarget(rspSqrt(SQDistanceToDude()));
				}
				m_panimCur = &m_animShoot;
				m_lAnimTime = 0;
				SelectDude();
				m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();	
				m_state = State_Shoot;
				m_eNextState = State_Guard;
				m_lTimer = lThisTime + m_lShootTimeout;
			}
			else
			{
				m_lTimer = lThisTime + m_lShootTimeout;
			}
		}
	}
	else
		ReevaluateState();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Patrol - Keep an eye on the CDude and look like you're doing something
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Patrol(void)
{
	// Turn to face dude but do not attack yet
	m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Hunt - Find a CDude, use the bouy network to get to him wherever he is
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Hunt(void)
{
	// Find the destination bouy (one closest to the Dude)
	m_eDestinationState = State_HuntHold;
	SelectDudeBouy();
	m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
	if (m_ucNextBouyID > 0)
	{
		m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
		if (m_pNextBouy != NULL)
		{
			m_sNextX = m_pNextBouy->GetX();
			m_sNextZ = m_pNextBouy->GetZ();			
			m_state = State_HuntNext;
			m_lTimer = m_pRealm->m_time.GetGameTime() + ms_lReseekTime;
		}
		else
		{
			// Couldn't get bouy position, so stay put
			m_state = State_Guard;
			m_eCurrentAction = Action_Guard;
		}	
	}
	else
	{
		// Couldn't find a bouy so stay put
		m_state = State_Guard;
		m_eCurrentAction = Action_Guard;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_HuntHold - This state means that you were trying to advance to the
//						  Dude and have got to the bouy closest to the Dude.  The
//						  Logic table can either break you out into Engage or 
//						  whatever, or you will stay in this state where you will 
//						  be in a guard mode, but always looking to see if you should
//						  move to a closer bouy once the Dude changes his position.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_HuntHold(void)
{
	// Evaluate the logic table suggestion to see if you should change states
	m_eCurrentAction = Action_AdvanceHold;
	if (!ReevaluateState())
	{
		// Check to see if the dude has moved and you should move	
		int32_t lThisTime = m_pRealm->m_time.GetGameTime();

		if (lThisTime > m_lTimer)
		{
			m_lTimer = lThisTime + 1000;
			SelectDudeBouy();
			m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
			// See if he should move closer.
			if (m_ucNextBouyID != m_ucDestBouyID)
			{
				m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
				if (m_pNextBouy != NULL)
				{
					m_sNextX = m_pNextBouy->GetX();
					m_sNextZ = m_pNextBouy->GetZ();
					m_lTimer = lThisTime + ms_lReseekTime;
					m_state = State_HuntNext;
					m_eCurrentAction = Action_Advance;
				}
			}
			// Else see if he is close enough to take a shot.
			else
			{
				if (SelectDude() == SUCCESS && SQDistanceToDude() < ms_dGuardDistance)
				{	
					CWeapon*	pweapon	= PrepareWeapon();
					if (pweapon != NULL)
					{
						// Keep it hidden, for now.
						pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
						pweapon->SetRangeToTarget(rspSqrt(SQDistanceToDude()));
					}
					m_panimCur = &m_animShoot;
					m_lAnimTime = 0;
					SelectDude();
					m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();	
					m_state = State_Shoot;
					m_eNextState = State_HuntHold;
					m_lTimer = lThisTime + m_lGuardTimeout;
				}
			}
		}

		// Check to see if the dude is nearby and you should shoot at him.
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_HuntNext - going to next bouy in network en route to final destination
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_MoveNext(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lElapsedTime = lThisTime - m_lPrevTime;
	double dSeconds = lElapsedTime / 1000.0;
	double dStartX = m_dX;
	double dStartZ = m_dZ;

	if (!ReevaluateState())
	{
		// Make sure its using the correct animation
		if (m_state == State_MarchNext || m_state == State_WalkNext)
		{
			if (m_panimCur != &m_animWalk)
			{
				m_panimCur = &m_animWalk;
				m_lAnimTime = 0;
			}
			else
				m_lAnimTime += lElapsedTime;

			// Cheat and make him walk slower by continuously
			// resetting the velocity.
			m_dVel = ms_dMarchVelocity;
		}
		// Normally use run
		else
		{
			if (m_panimCur != &m_animRun)
			{
				m_panimCur = &m_animRun;
				m_lAnimTime = 0;
			}
			else
				m_lAnimTime += lElapsedTime;
		}

		AlignToBouy();
		m_dAcc = ms_dAccUser;

		DeluxeUpdatePosVel(dSeconds);

		// If not moving when you are trying to, rotate 
		if (m_dX == dStartX && m_dZ == dStartZ)
		{
			if (m_sRotateDir)
				m_dAnimRot = m_dRot = rspMod360(m_dRot + 20);
			else
				m_dAnimRot = m_dRot = rspMod360(m_dRot - 20);
			// Reset alignment timer so he doesn't reseek the bouy direction immediately
			m_lAlignTimer = lThisTime + ms_lDefaultAlignTime;
			// Set a flag indicating that you were stuck, so we know what bouy to look
			// for once you get free
			m_bRecentlyStuck = true;
		}
		else
		{
			m_sRotateDir = GetRandom() % 2;
		}

		// See if we are at the next bouy yet
		double dX = m_dX - (double) m_sNextX;
		double dZ = m_dZ - (double) m_sNextZ;
		double dsq = (dX * dX) + (dZ * dZ);
		if (dsq < 5*5) // Was 10*10 for a long time, trying smaller to see if it keeps guys from getting stuck
		{
			uint8_t ucNext = m_pNextBouy->NextRouteNode(m_ucDestBouyID);
			if (ucNext == 0 || ucNext == 255) // you are here or you are lost
			{
				m_state = m_eDestinationState;
				switch (m_state)
				{
					case State_Engage:
						m_eCurrentAction = Action_Engage;
						break;

					case State_Guard:
						m_eCurrentAction = Action_Guard;
						break;

					case State_March:
						m_eCurrentAction = Action_March;
						break;

					case State_Walk:
						m_eCurrentAction = Action_Walk;
						break;
				}
			}
			else
			{
				// If the reseek timer has expired, find the Dude bouy 
				// again since he may have moved
				if (lThisTime > m_lTimer || ucNext == 255)
				{
					if (m_state == State_HuntNext)
						m_state = State_Hunt;
					else
						m_lTimer = lThisTime + ms_lReseekTime;
				}
				else
				{
					m_ucNextBouyID = ucNext;
					m_pNextBouy = m_pNavNet->GetBouy(ucNext);
					m_sNextX = m_pNextBouy->GetX();
					m_sNextZ = m_pNextBouy->GetZ();
				}
			}
		}
	}
	// Check for fire in your path so you don't keep moving
	AvoidFire();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PositionSet - Get yourself set up to get into range for shooting
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PositionSet(void)
{
	if (!ReevaluateState())
	{
		int32_t lThisTime = m_pRealm->m_time.GetGameTime();
		int16_t sVarRot = GetRandom() % 40;
		double dTargetDist = SQDistanceToDude();
		double dTestAngle;
		double dAngleTurn;

		// If he is out of range now, reset desired range to the middle value.
		if (dTargetDist < ms_dMinFightDistanceSQ || dTargetDist > ms_dMaxFightDistanceSQ)
			dTargetDist = ms_dMedFightDistanceSQ;

		bool bFoundDirection = false;
		int16_t sAttempts = 0;

		while (!bFoundDirection && sAttempts < 8)
		{
			switch (sAttempts)
			{
				case 0:
					if (sVarRot & 0x01)
						dTestAngle = rspMod360(m_dRot + 40 + sVarRot);
					else
						dTestAngle = rspMod360(m_dRot - 40 - sVarRot);
					dAngleTurn = 40 + sVarRot;
					break;
					
				case 1:
					if (sVarRot & 0x01)
						dTestAngle = rspMod360(m_dRot - 40 - sVarRot);
					else
						dTestAngle = rspMod360(m_dRot + 40 + sVarRot);
					// Same dAngleTurn as last time
					break;
					
				case 2:
					if (sVarRot & 0x01)
						dTestAngle = rspMod360(m_dRot + 20 + sVarRot);
					else
						dTestAngle = rspMod360(m_dRot - 20 - sVarRot);
					dAngleTurn = 20 + sVarRot;
					break;
					
				case 3:
					if (sVarRot & 0x01)
						dTestAngle = rspMod360(m_dRot - 20 - sVarRot);
					else
						dTestAngle = rspMod360(m_dRot + 20 + sVarRot);
					// Same dAngleTurn as last time
					break;
					
				case 4:
					dTestAngle = rspMod360(m_dRot + 95);
					break;
					
				case 5:
					dTestAngle = rspMod360(m_dRot - 95);
					break;

				case 6:
					dTestAngle = m_dRot;
					break;

				case 7:
					dTestAngle = rspMod360(m_dRot + 180);
					break;
			}

			if (CDoofus::TryClearDirection(&dTestAngle, 30) == true)
			{
				bFoundDirection = true;
				if (sAttempts < 4)
				{
					m_sDistRemaining = 2 * 3.1415 * rspSqrt(dTargetDist) * ((180.0-(2.0*(dAngleTurn)))/360.0);
					m_lTimer = lThisTime + (1000 * (m_sDistRemaining / ms_dMaxVelFore));		
				}
				else
				{
					m_lTimer = 800 + GetRandom() % 400;
				}
			}
			else
			{
				sAttempts++;
			}
		}

		// If you found a clear direction, take it
		if (bFoundDirection)
		{
				m_dAnimRot = m_dRot = dTestAngle;
				// Set new animation
				m_dAcc = ms_dAccUser;
				m_state = State_PositionMove;
				m_panimCur = &m_animRun;
				m_lAnimTime = 0;
		}
		else
		// else stay where you are.
		{
			m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();
			if (m_idDude != CIdBank::IdNil)
			{
				m_state = State_DelayShoot;
				m_lTimer = lThisTime + ms_lDelayShootTimeout;
				m_eNextState = State_PositionSet;
				m_sStuckCounter++;
				m_lAnimTime = 0;
				if (m_sStuckCounter > ms_sStuckLimit)
				{
					m_sStuckCounter = 0;
					m_lStuckTimeout = lThisTime + ms_lStuckRecoveryTime;
					ReevaluateState();
				}
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_DelayShoot - wait for timer to expire then shoot if clear
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_DelayShoot(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();

	// See if its time to shoot yet
	if (lThisTime > m_lTimer)
	{
		if (TryClearShot(m_dRot, 20) == true && SelectDude() == SUCCESS) 
		{
			CWeapon* pweapon = PrepareWeapon();
			if (pweapon != NULL)
			{
				pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
				pweapon->SetRangeToTarget(rspSqrt(SQDistanceToDude()));
			}
			m_panimCur = &m_animShoot;
			m_lAnimTime = 0;
			m_state = State_Shoot;
		}
		else
		// Skip the shot and go back to the correct state
		{
			m_state = m_eNextState;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PositionMove - Move into position then shoot
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PositionMove(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lTimeDifference = lThisTime - m_lPrevTime;
	double dSeconds = lTimeDifference / 1000.0;

	if (lThisTime > m_lTimer)
	{
		m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();
		// Check for clear shot before shooting.  If not clear, go back to moving
		if (CDoofus::TryClearShot(m_dRot, 20) == true && SelectDude() == SUCCESS)
		{
			CWeapon*	pweapon	= PrepareWeapon();
			if (pweapon != NULL)
			{
				// Keep it hidden, for now.
				pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
				pweapon->SetRangeToTarget(rspSqrt(SQDistanceToDude()));
			}
			m_state = State_Shoot;
			m_eNextState = State_PositionSet;
			m_panimCur = &m_animShoot;
			m_lAnimTime = 0;
		}
		// If path is blocked, go on the move again and don't shoot
		else
		{
			m_state = State_PositionSet;	
		}
	}
	else
	{
		double dLastPosX = m_dX;
		double dLastPosZ = m_dZ;

		DeluxeUpdatePosVel(dSeconds);
		m_lAnimTime += lTimeDifference;

		// If not moving when intending to, rotate one way or the other
		// to try to avoid the obstacle
		if (m_dVel != 0.0 && dLastPosX == m_dX && dLastPosZ == m_dZ)
		{
			if (((int16_t) m_dRot) & 0x01)
				m_dAnimRot = m_dRot = rspMod360(m_dRot + 20);
			else
				m_dAnimRot = m_dRot = rspMod360(m_dRot - 20);
		}
		// Avoid fire in your path
		AvoidFire();
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Engage - engage the Dude and start fighting at close range
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Engage(void)
{
	m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();
	m_state = State_PositionSet;
	m_sStuckCounter = 0;
}

////////////////////////////////////////////////////////////////////////////////
// Logic_BeSafe - Stay behind the SafeSpot bouy if the Dude is facing you
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_BeSafe(void)
{

}

////////////////////////////////////////////////////////////////////////////////
// Logic_Firefight - Shoot and move
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Firefight(void)
{

}

////////////////////////////////////////////////////////////////////////////////
// Logic_PylonDetect - If you detect that a pylon is near, find out what kind
//						     it is and decide if you will use it based on the
//							  suggested action.  This function is only called when
//							  the suggested action requires the use of a pylon.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PylonDetect(void)
{
	CSmash* pSmashPylon;
	CPylon* pPylon = NULL;		  
	double dSmashedX = 0.0;
	double dSmashedZ = 0.0;

	m_bPylonSafeAvailable = false;
	m_bPylonPopoutAvailable = false;
	m_bPylonRunShootAvailable = false;

	// Update the detection smash.
	m_smashDetect.m_sphere.sphere.X = m_dX;
	m_smashDetect.m_sphere.sphere.Y = m_dY;
	m_smashDetect.m_sphere.sphere.Z = m_dZ;

	// For now when we detect a pylon we are assuming that this
	// character should use that logic.  Later we will have to 
	// decide based on the personality numbers and current state.
	if (m_pRealm->m_smashatorium.QuickCheckClosest(&m_smashDetect,
																  CSmash::Pylon,
																  0,
																  0,
																  &pSmashPylon))
	{
		ASSERT(pSmashPylon);
		pPylon = (CPylon*) pSmashPylon->m_pThing;
		ASSERT(pPylon);

		if (pSmashPylon->m_pThing != this)
		{
			dSmashedX = pSmashPylon->m_sphere.sphere.X;
			dSmashedZ = pSmashPylon->m_sphere.sphere.Z;
			// Check IsPathClear to that thing
			if (m_pRealm->IsPathClear(	// Returns true, if the entire path is clear.                 
													// Returns false, if only a portion of the path is clear.     
													// (see *psX, *psY, *psZ).                                    
					(int16_t) m_dX, 				// In:  Starting X.                                           
					(int16_t) m_dY, 				// In:  Starting Y.                                           
					(int16_t) m_dZ, 				// In:  Starting Z.                                           
					3.0, 							// In:  Rate at which to scan ('crawl') path in pixels per    
													// iteration.                                                 
													// NOTE: Values less than 1.0 are inefficient.                
													// NOTE: We scan terrain using GetHeight()                    
													// at only one pixel.                                         
													// NOTE: We could change this to a speed in pixels per second 
													// where we'd assume a certain frame rate.                    
					(int16_t) dSmashedX,		// In:  Destination X.                                        
					(int16_t) dSmashedZ,		// In:  Destination Z.                                        
					0,								// In:  Max traverser can step up.                      
					NULL,							// Out: If not NULL, last clear point on path.                
					NULL,							// Out: If not NULL, last clear point on path.                
					NULL,							// Out: If not NULL, last clear point on path.                
					true) )						// In:  If true, will consider the edge of the realm a path
													// inhibitor.  If false, reaching the edge of the realm    
													// indicates a clear path. 
			{                                
				switch (pPylon->m_msg.msg_Generic.eType)
				{
					case typeSafeSpot:
						m_bPylonSafeAvailable = true;
						m_pPylonStart = pPylon;
						break;

					case typePopout:
						m_bPylonPopoutAvailable = true;
						m_pPylonStart = pPylon;
						break;

					case typeShootCycle:
						m_bPylonRunShootAvailable = true;
						m_pPylonStart = pPylon;
						break;

					default:
						break;
				}
			}
		}
	}
	else
	{
		// If no pylons were nearby where he started, and he was just idle,
		// then set him up as a stationary guard for now.
		if (m_state == State_Idle || m_state == State_Wait)
		{	
			// See if there are bouys, if there aren't any, then stay in Guard mode
			if (m_pNavNet->GetNumNodes() > 1)
			{
				m_state = State_Hunt;
				m_eCurrentAction = Action_Advance;
			}
			else
			{
				m_state = State_Guard;
				m_eCurrentAction = Action_Guard;
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_HideBegin - Go to the hiding pylon and then wait once you get there
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_HideBegin(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	// If we'renot using the run animation yet then switch to it
	if (m_panimCur != &m_animRun)
	{
		m_panimCur = &m_animRun;
		m_lAnimTime = 0;
	}
	else
		m_lAnimTime += lThisTime - m_lPrevTime;

	// Set angle to pylon.
	m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
	m_dAcc = ms_dAccUser;

	int32_t lElapsedTime = m_pRealm->m_time.GetGameTime() - m_lPrevTime;
	double dSeconds = lElapsedTime / 1000.0;
	DeluxeUpdatePosVel(dSeconds);

	//	if close to pylon, go to next state
	// for now just check the square distance, but later, probably use
	// QuickCheckCloses in smash to see if you are there yet.
	double dX = m_dX - (double) m_sNextX;
	double dZ = m_dZ - (double) m_sNextZ;
	double dsq = (dX * dX) + (dZ * dZ);
	if (dsq < 300)
	{
		m_state = State_Hide;
	}
	// Check for fire in your path
	AvoidFire();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Hide - Wait here and hope nobody sees you and blows you away.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Hide(void)
{
	ReevaluateState();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PopBegin - Once you have detected a nearby Pylon, begin the popout
//						  phase here by going to that pylon.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PopBegin(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	double dStartX = m_dX;
	double dStartZ = m_dZ;

	// If we're not using the run animation yet then switch to it
	if (m_panimCur != &m_animRun)
	{
		m_panimCur = &m_animRun;
		m_lAnimTime = 0;
	}
	else
		m_lAnimTime += lThisTime - m_lPrevTime;

	m_eCurrentAction = Action_Popout;
	// Set angle to pylon.
	if (lThisTime > m_lAlignTimer)
	{
		m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
		m_lAlignTimer = lThisTime + 100;
		m_sRotateDir = GetRandom() % 2;
	}
	m_dAcc = ms_dAccUser;

	int32_t lElapsedTime = m_pRealm->m_time.GetGameTime() - m_lPrevTime;
	double dSeconds = lElapsedTime / 1000.0;
	DeluxeUpdatePosVel(dSeconds);

	// Check for fire in your path
	AvoidFire();

	// If not moving when meaning to, rotate to avoid obstacle
	if (m_dX == dStartX && m_dZ == dStartZ)
	{
		if (m_sRotateDir)
			m_dAnimRot = m_dRot = rspMod360(m_dRot + 20);
		else
			m_dAnimRot = m_dRot = rspMod360(m_dRot - 20);
		m_lAlignTimer = lThisTime + 100;
	}

	//	if close to pylon, go to next state
	// for now just check the square distance, but later, probably use
	// QuickCheckCloses in smash to see if you are there yet.
	double dX = m_dX - (double) m_sNextX;
	double dZ = m_dZ - (double) m_sNextZ;
	double dsq = (dX * dX) + (dZ * dZ);
	if (dsq < 300)
	{
		m_state = State_PopWait;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PopWait - Wait at covered pylon until a CDude steps on the trigger
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PopWait(void)
{
	// If the stand animation is not being used yet then switch to it.
//	if (m_panimCur != &m_animStand)
//	{
//		m_panimCur = &m_animStand;
//		m_lAnimTime = 0;
//	}
	RunIdleAnimation();

	if (!ReevaluateState())
	{
		m_eCurrentAction = Action_Popout;
		if (m_pRealm->m_time.GetGameTime() > m_lTimer && m_pPylonStart->Triggered())
		{
			// Set next pylon to go to 
			m_sNextX = m_pPylonEnd->GetX();
			m_sNextZ = m_pPylonEnd->GetZ();
			m_state = State_Popout;

			m_panimCur = &m_animRun;
			m_lAnimTime = 0;
		}
	}
	else
	{
		m_pPylonStart = NULL;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Popout - When at a popout bouy, if the guy is close, popout, shoot, 
//						and duck back behind the bouy.  If he is not in range, stay
//						behind the bouy and wait for some amount of time.  Reevaluate
//						logic choice based on enemy attributes.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Popout(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lElapsedTime = lThisTime - m_lPrevTime;
	double dSeconds = lElapsedTime / 1000.0;
	m_lAnimTime += lElapsedTime;
	m_eCurrentAction = Action_Popout;

	// Go to next pylon
	m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
	m_dAcc = ms_dAccUser;
	DeluxeUpdatePosVel(dSeconds);

	// Check for fire in your path
	AvoidFire();

	// If you are at the pylon, then go to the next state
	//	if close to pylon, go to next state
	// for now just check the square distance, but later, probably use
	// QuickCheckCloses in smash to see if you are there yet.
	double dX = m_dX - (double) m_sNextX;
	double dZ = m_dZ - (double) m_sNextZ;
	double dsq;
	dsq = (dX * dX) + (dZ * dZ);
	if (dsq < 300)
	{
		m_state = State_Shoot;
		// After shooting, go back to beginning
		m_eNextState = State_PopBegin;
		m_lTimer = lThisTime + 2000 + GetRandom() % 2000;
		m_sNextX = m_pPylonStart->GetX();
		m_sNextZ = m_pPylonStart->GetZ();
		CWeapon*	pweapon	= PrepareWeapon();
		if (pweapon != NULL)
		{
			// Keep it hidden, for now.
			pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
		}
		m_panimCur = &m_animShoot;
		m_lAnimTime = 0;
		SelectDude();
		m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();	
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Shoot - run the animation to the proper time and then shoot the weapon
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Shoot(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lTimeDifference = lThisTime - m_lPrevTime;

	// Switch behavior on weapon type.
	switch (m_eWeaponType)
	{
		case CThing::CFirestreamID:
			// If out of fire streams . . .
			if (m_u16IdWeapon == CIdBank::IdNil)
				{
				// Must prepare more fire.
				if (PrepareWeapon() == NULL)
					break;
				}
			// Intentional fall through.
		case CThing::CShotGunID:
		case CThing::CMachineGunID:
		case CThing::CPistolID:
		case CThing::CAssaultWeaponID:
		case CThing::CDoubleBarrelID:
		case CUziID:
		case CAutoRifleID:
		case CSmallPistolID:
		{
			// Get event.
			U8	u8Event	= *( (U8*)(m_panimCur->m_pevent->GetAtTime(m_lAnimTime) ) );
			// We don't care about show point for these non-object weapon types.
			// If it's time to fire the weapon . . .
			if (u8Event > 0 && lThisTime > m_lShootTimer)
			{
				// Fire!
				ShootWeapon();

				switch (m_eWeaponType)
				{
					case CThing::CShotGunID:
					case CThing::CDoubleBarrelID:
						m_lShootTimer = lThisTime + 2000;
						break;

					case CUziID:
					case CAutoRifleID:
					case CThing::CMachineGunID:
					case CThing::CAssaultWeaponID:
					case CThing::CFirestreamID:
						m_lShootTimer = lThisTime + 100;
						break;

					case CSmallPistolID:
					case CThing::CPistolID:
						m_lShootTimer = lThisTime + 300;
						break;
				}
			}
			break;
		}
		
		// This is the "I don't have a weapon" case (i.e., NoWeapon).
		case TotalIDs:
			break;

		default:
			if (m_u16IdWeapon != CIdBank::IdNil)
			{
				if (WhileHoldingWeapon(ms_u32CollideBitsInclude, ms_u32CollideBitsDontcare, ms_u32CollideBitsExclude) == true)
				{
					// Note we are done with the child.  Now we're just finishing the anim.
					ASSERT(m_u16IdWeapon == CIdBank::IdNil);
				}
			}
			break;
	}

	// See if we are at the end of the animation or we have no weapon . . .
	if (m_lAnimTime > m_panimCur->m_psops->TotalTime() || m_eWeaponType == TotalIDs)
	{
		m_state = m_eNextState;
	}
	// Else advance the animation timer
	else
	{
		m_lAnimTime += lTimeDifference;					
	}
	
}

////////////////////////////////////////////////////////////////////////////////
// Logic_ShootRun - Shoot while running - use the Shoot logic to control
//						  the firing of the shot and the animation, and just add on
//						  the motion update
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_ShootRun(void)
{
	double dSeconds = (m_pRealm->m_time.GetGameTime() - m_lPrevTime) / 1000.0;

	Logic_Shoot();

	DeluxeUpdatePosVel(dSeconds);

	// Check for fire in your path
	AvoidFire();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_RunShootBegin - Set up the destination pylon and shooting interval
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_RunShootBegin(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lElapsedTime = lThisTime - m_lPrevTime;
	double dStartX = m_dX;
	double dStartZ = m_dZ;

	// If we're not using the run animation yet, then switch to it
	if (m_panimCur != &m_animRun)
	{
		m_panimCur = &m_animRun;
		m_lAnimTime = 0;
	}						 
	else
		m_lAnimTime += lElapsedTime;

	// Set angle to pylon.
	if (lThisTime > m_lAlignTimer)
	{
		m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
		m_lAlignTimer = lThisTime + 100;
		m_sRotateDir = GetRandom() % 2;
	}
	m_dAcc = ms_dAccUser;

	double dSeconds = lElapsedTime / 1000.0;
	DeluxeUpdatePosVel(dSeconds);

	// Check for fire in your path
	AvoidFire();

	// If not moving when you meant to, start to rotate to avoid obstacles
	if (m_dX == dStartX && m_dZ == dStartZ)
	{
		if (m_sRotateDir)
			m_dAnimRot = m_dRot = rspMod360(m_dRot + 20);
		else
			m_dAnimRot = m_dRot = rspMod360(m_dRot - 20);
		m_lAlignTimer = lThisTime + 100;
	}

	// If close to pylon, go to nex state
	double dX = m_dX - (double) m_sNextX;
	double dZ = m_dZ - (double) m_sNextZ;
	double dsq = (dX * dX) + (dZ * dZ);
	if (dsq < 300)
	{
		// Find position of destinaiton pylon
		m_sNextX = m_pPylonEnd->GetX();
		m_sNextZ = m_pPylonEnd->GetZ();
		m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
		m_lTimer = lThisTime + m_lRunShootInterval;
//		m_state = State_RunShoot;
		m_state = State_RunShootWait;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_RunShoot - Run and Shoot logic.  When near a ShootCycle bouy, hide, 
//						  run out and shoot at a Dude, run towards other bouy, stop
//						  and shoot again, then duck behind the second bouy.  Repeat
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_RunShoot(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	int32_t lElapsedTime = lThisTime - m_lPrevTime;

	// If its not using the run animation, then switch to it
	if (m_panimCur != &m_animRun)
	{
		m_panimCur = &m_animRun;
//		m_lAnimTime = 0;
		m_dAnimRot = m_dRot;
	}

	if (!ReevaluateState())
	{
		// Advance the run animation
		m_lAnimTime += lElapsedTime;

		// If its time to shoot then do it.
		if (lThisTime > m_lTimer)
		{
			m_state = State_ShootRun;
			// After shooting, go back to beginning
			m_eNextState = State_RunShoot;
			CWeapon*	pweapon	= PrepareWeapon();
			if (pweapon != NULL)
			{
				// Keep it hidden, for now.
				pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
			}
			SelectDude();

			int16_t sTargetAngle = FindDirection();
			m_dShootAngle = sTargetAngle;
			int16_t sAngleCCL = rspMod360(sTargetAngle - m_dRot);
			int16_t sAngleCL  = rspMod360((360 - sTargetAngle) + m_dRot);
			int16_t sAngleDistance = MIN(sAngleCCL, sAngleCL);
			if (sAngleCCL < sAngleCL)
			// Rotate Counter Clockwise - Use left animations
			{
				if (sAngleDistance > 150)
				{
					m_panimCur = &m_animShootRunBack;
					m_dAnimRot = rspMod360(m_dRot + (sAngleDistance - 180));
				}
				else
				{
					if (sAngleDistance > 68)
					{
						m_panimCur = &m_animShootRunL1;
						m_dAnimRot = rspMod360(m_dRot + (sAngleDistance - 90));
					}
					else
					{
						if (sAngleDistance > 23)
						{
							m_panimCur = &m_animShootRunL0;
							m_dAnimRot = rspMod360(m_dRot + (sAngleDistance - 45));
						}
						else
						{
							m_panimCur = &m_animShootRun;
							m_dAnimRot = rspMod360(m_dRot + sAngleDistance);
						}
					}
				}
			}
			else
			// Rotate Clockwise - Use right animations
			{
				if (sAngleDistance > 150)
				{
					m_panimCur = &m_animShootRunBack;
					m_dAnimRot = rspMod360(m_dRot - (sAngleDistance - 180));
				}
				else
				{
					if (sAngleDistance > 68)
					{
						m_panimCur = &m_animShootRunR1;
						m_dAnimRot = rspMod360(m_dRot - (sAngleDistance - 90));
					}
					else
					{
						if (sAngleDistance > 23)
						{
							m_panimCur = &m_animShootRunR0;
							m_dAnimRot = rspMod360(m_dRot - (sAngleDistance - 45));
						}
						else
						{
							m_panimCur = &m_animShootRun;
							m_dAnimRot = rspMod360(m_dRot - sAngleDistance);
						}
					}
				}
			}

			m_lTimer = lThisTime + m_lRunShootInterval;
			m_lAnimTime = 0;
		}
		else
		{
			// Set angle to pylon.
			m_dAnimRot = m_dRot = FindAngleTo(m_sNextX, m_sNextZ);
			m_dAcc = ms_dAccUser;

			double dSeconds = lElapsedTime / 1000.0;
			DeluxeUpdatePosVel(dSeconds);

			// Check for fire in your path
			AvoidFire();

			//	if close to pylon, go to next state
			// for now just check the square distance, but later, probably use
			// QuickCheckCloses in smash to see if you are there yet.
			double dX = m_dX - (double) m_sNextX;
			double dZ = m_dZ - (double) m_sNextZ;
			double dsq = (dX * dX) + (dZ * dZ);
			if (dsq < 300)
			{
				m_state = State_RunShootWait;
				m_lTimer = lThisTime + m_lGuardTimeout;
				// Make him face the other way.
				m_dAnimRot = m_dRot = FindAngleTo(m_pPylonEnd->GetX(), m_pPylonEnd->GetZ());
			}
		}
	}
	else
	{
		m_pPylonStart = NULL;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_RunShootWait - Wait at the endpoint before going again.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_RunShootWait(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();
	
	RunIdleAnimation();

	// If the waiting is over and its triggered
	if (lThisTime > m_lTimer && m_pPylonStart->Triggered())
	{
		CPylon* pPylonTemp = m_pPylonStart;
		m_pPylonStart = m_pPylonEnd;
		m_pPylonEnd = pPylonTemp;
		m_state = State_RunShoot;
		m_sNextX = m_pPylonStart->GetX();
		m_sNextZ = m_pPylonStart->GetZ();
		m_dVel = 0.0;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Retreat - Once you are low on health, you may choose this logic to
//						 run away from the Dude, taking shelter wherever you can.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Retreat(void)
{
	// Get your closest bouy, pick a random destination bouy, then
	// start traversing 3 away from your current one and set that
	// as the destination bouy, then switch to State_MoveNext

	m_eDestinationState = State_Guard;
	m_ucDestBouyID = SelectRandomBouy();
	m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
	if (m_ucNextBouyID > 0)
	{
		m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
		if (m_pNextBouy != NULL)
		{
			m_sNextX = m_pNextBouy->GetX();
			m_sNextZ = m_pNextBouy->GetZ();
			m_state = State_MoveNext;
			m_eCurrentAction = Action_Retreat;
		}
		else
		{
			// Couldn't find bouy so stay engaged
			m_state = State_Engage;
			m_eCurrentAction = Action_Engage;
		}
	}
	else
	{
		// Couldn't find a bouy so just stay in engage.
		m_state = State_Engage;
		m_eCurrentAction = Action_Engage;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PanicBegin - Pick a random bouy to run to and set animation
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PanicBegin(void)
{
	// See if dude is still alive
	SelectDude();
	// Switch to correct animation if not already.
	if (m_panimCur != &m_animRun)
	{
		m_panimCur = &m_animRun;
		m_lAnimTime = 0;
	}

	m_eDestinationState = State_PanicContinue;
	m_bPanic = true;
	m_ucDestBouyID = SelectRandomBouy();
	m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
	if (m_ucNextBouyID > 0)
	{
		m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
		if (m_pNextBouy != NULL)
		{
			m_sNextX = m_pNextBouy->GetX();
			m_sNextZ = m_pNextBouy->GetZ();
			m_state = State_MoveNext;
		}
		else
		{
			// Couldn't find bouy so stay engaged
			m_state = State_PanicBegin;
		}
	}
	else
	{
		// Couldn't find a bouy so just stay in engage.
		m_state = State_PanicBegin;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_PanicContinue - End of panic state - pick another bouy
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_PanicContinue(void)
{
	m_state = State_PanicBegin;
}

////////////////////////////////////////////////////////////////////////////////
// Logic_MarchBegin - Pick an endpoint and march to it.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_MarchBegin(void)
{
	// See if Dude is still alive
	SelectDude();

	// Switch to correct animation if not already.
	if (m_panimCur != &m_animWalk)
	{
		m_panimCur = &m_animWalk;
		m_lAnimTime = 0;
	}

	m_eDestinationState = State_March;
	m_eCurrentAction = Action_March;
	// Pick an endpoint that we are not already at.
	if (m_ucDestBouyID == m_ucSpecialBouy0ID)
		m_ucDestBouyID = m_ucSpecialBouy1ID;
	else
		m_ucDestBouyID = m_ucSpecialBouy0ID;

	m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
	if (m_ucNextBouyID > 0)
	{
		m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
		if (m_pNextBouy != NULL)
		{
			m_sNextX = m_pNextBouy->GetX();
			m_sNextZ = m_pNextBouy->GetZ();
			m_state = State_MarchNext;
		}
		// Couldn't find a bouy - try guard mode
		else
		{
			m_state = State_Guard;
			m_eCurrentAction = Action_Guard;
		}
	}
	// Couldn't find a bouy - try guard mode
	else
	{
		m_state = State_Guard;
		m_eCurrentAction = Action_Guard;
	}

}

////////////////////////////////////////////////////////////////////////////////
// Logic_WalkBegin - Pick a random bouy to run to and set animation
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_WalkBegin(void)
{
	// See if dude is still alive
	SelectDude();
	m_eDestinationState = State_WalkContinue;
	m_ucDestBouyID = SelectRandomBouy();
	m_ucNextBouyID = m_pNavNet->FindNearestBouy(m_dX, m_dZ);
	if (m_ucNextBouyID > 0)
	{
		m_pNextBouy = m_pNavNet->GetBouy(m_ucNextBouyID);
		if (m_pNextBouy != NULL)
		{
			m_sNextX = m_pNextBouy->GetX();
			m_sNextZ = m_pNextBouy->GetZ();
			m_state = State_WalkNext;
		}
		else
		{
			// Couldn't find bouy so stay engaged
			m_state = State_Walk;
		}
	}
	else
	{
		// Couldn't find a bouy so just stay in engage.
		m_state = State_Walk;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Logic_WalkContinue - End of walk state - pick another bouy
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_WalkContinue(void)
{
	m_state = State_WalkBegin;
}

////////////////////////////////////////////////////////////////////////////////
// Logic_Helping - Help out your buddies without moving around and screwing
//						 up your positioning
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_Helping(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();

	if (lThisTime > m_lTimer)
	{
		m_eCurrentAction = Action_Help;
		m_lTimer = lThisTime + ms_lHelpingTimeout;
		if (SelectDude() == SUCCESS && SQDistanceToDude() <= ms_lYellRadius)
		{	
			if (CDoofus::TryClearShot(m_dRot, 20) == true)
			{
				CWeapon*	pweapon	= PrepareWeapon();
				if (pweapon != NULL)
				{
					// Keep it hidden, for now.
					pweapon->GetSprite()->m_sInFlags |= CSprite::InHidden;
					pweapon->SetRangeToTarget(rspSqrt(SQDistanceToDude()));
				}
				m_panimCur = &m_animShoot;
				m_lAnimTime = 0;
				SelectDude();
				m_dShootAngle = m_dAnimRot = m_dRot = FindDirection();	
				m_state = State_Shoot;
				m_eNextState = State_Helping;
				m_lTimer = lThisTime + ms_lHelpingTimeout;
			}
			else
			{
				m_lTimer = lThisTime + ms_lHelpingTimeout;
			}
		}
	}
	else
		ReevaluateState();
}

////////////////////////////////////////////////////////////////////////////////
// Logic_AvoidFire - Wait for fire danger to pass before going back to your
//						   previous state.  This state is set by AvoidFire function
//							when there is a fire in your path.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::Logic_AvoidFire(void)
{
	if (AvoidFire())
	{
		// Check for a different state
		ReevaluateState();
	}
	else
	// Go back to your previous state
	{
		m_state = m_ePreviousState;
		m_panimCur = m_panimPrev;
	}
}

////////////////////////////////////////////////////////////////////////////////
// AvoidFire - checks for fire in your path, returns true if there is a fire
//					danger.  If you are not already in the fire avoidance state,
//					it will save your previous state info and change your state.
////////////////////////////////////////////////////////////////////////////////

bool CDoofus::AvoidFire(void)
{
	bool bFireDanger = false;

	CSmash* pSmashed = NULL;

	// Change this to quick check closest
	if (m_pRealm->m_smashatorium.QuickCheck(&m_smashAvoid, 
														 CSmash::Fire,	
														 CSmash::Good | CSmash::Bad, 
														 0, 
														 &pSmashed))
	{
		bFireDanger = true;

		// If its not already avoiding fire, switch to this safe state
		// and save the previous state
		if (m_state != State_AvoidFire)
		{
			m_ePreviousState = m_state;
			m_panimPrev = m_panimCur;
			m_state = State_AvoidFire;
			m_panimCur = &m_animStand;
		}
	}


	return bFireDanger;	
}

////////////////////////////////////////////////////////////////////////////////
// YellForHelp - Call this when you get shot and it will alert other enemies in
//					  the area within line of sight that you are in trouble.  Then 
//					  they can choose to react.
////////////////////////////////////////////////////////////////////////////////

void CDoofus::YellForHelp(void)
{
	CSmash* pSmashed = NULL;
	CSmash smashYell;
	double dSmashedX;
	double dSmashedZ;
	GameMessage msg;
	msg.msg_Help.eType = typeHelp;
	msg.msg_Help.sPriority = 0;

	// Set up the yell smash
	smashYell.m_sphere.sphere.X = m_dX;
	smashYell.m_sphere.sphere.Y = m_dY;
	smashYell.m_sphere.sphere.Z = m_dZ;
	smashYell.m_sphere.sphere.lRadius = ms_lYellRadius;
	smashYell.m_bits = 0;
	smashYell.m_pThing = this;

	m_pRealm->m_smashatorium.QuickCheckReset(&smashYell,
														  CSmash::Character | CSmash::Bad,
														  0,
														  CSmash::Good);
	while (m_pRealm->m_smashatorium.QuickCheckNext(&pSmashed))
	{
		ASSERT(pSmashed->m_pThing);
		if (pSmashed->m_pThing != this)
		{
			dSmashedX = pSmashed->m_sphere.sphere.X;
			dSmashedZ = pSmashed->m_sphere.sphere.Z;
			// Check IsPathClear to that thing
			if (m_pRealm->IsPathClear(	// Returns true, if the entire path is clear.                 
													// Returns false, if only a portion of the path is clear.     
													// (see *psX, *psY, *psZ).                                    
					(int16_t) m_dX, 				// In:  Starting X.                                           
					(int16_t) m_dY, 				// In:  Starting Y.                                           
					(int16_t) m_dZ, 				// In:  Starting Z.                                           
					3.0, 							// In:  Rate at which to scan ('crawl') path in pixels per    
													// iteration.                                                 
													// NOTE: Values less than 1.0 are inefficient.                
													// NOTE: We scan terrain using GetHeight()                    
													// at only one pixel.                                         
													// NOTE: We could change this to a speed in pixels per second 
													// where we'd assume a certain frame rate.                    
					(int16_t) dSmashedX,		// In:  Destination X.                                        
					(int16_t) dSmashedZ,		// In:  Destination Z.                                        
					0,								// In:  Max traverser can step up.                      
					NULL,							// Out: If not NULL, last clear point on path.                
					NULL,							// Out: If not NULL, last clear point on path.                
					NULL,							// Out: If not NULL, last clear point on path.                
					true) )						// In:  If true, will consider the edge of the realm a path
													// inhibitor.  If false, reaching the edge of the realm    
													// indicates a clear path. 
			{                                
				SendThingMessage(&msg, pSmashed->m_pThing);				
			}
		}
	}

}

////////////////////////////////////////////////////////////////////////////////
// ReevaluateState - Based on parameters, some randomness, current state etc,
//							come up with a new state.
//
//							Returns true if the state changed
////////////////////////////////////////////////////////////////////////////////

bool CDoofus::ReevaluateState(void)
{
	bool bChanged = false;

	// If its not already doing the suggested Action, then attempt to switch to it.
	// and if its not in one of the final death states
	if (m_eSuggestedAction != m_eCurrentAction &&
	    m_state != State_Burning &&
		 m_state != State_BlownUp &&
		 m_state != State_Die &&
		 m_state != State_Dead &&
		 m_state != State_Writhing)
	{
		switch (m_eSuggestedAction)
		{
			case Action_Guard:	
				if (m_panimCur != &m_animStand &&
				    m_panimCur != &m_animCrouch &&
					 m_panimCur != &m_animSearch)
				{
					m_panimCur = &m_animStand;
					m_lAnimTime = 0;
				}
				m_state = State_Guard;
				m_eCurrentAction = Action_Guard;
				bChanged = true;
				break;

			case Action_Advance:
				if (m_eCurrentAction != Action_AdvanceHold)
				{
					m_state = State_Hunt;
					m_eCurrentAction = Action_Advance;
					bChanged = true;
				}
				break;

			case Action_Retreat:
				m_state = State_Retreat;
				m_eCurrentAction = Action_Retreat;
				bChanged = true;
				break;

			case Action_Engage:
				m_state = State_Engage;
				m_eCurrentAction = Action_Engage;
				bChanged = true;
				break;

			case Action_Walk:
				m_state = State_WalkBegin;
				m_eCurrentAction = Action_Walk;
				bChanged = true;
				break;

			case Action_March:
				m_state = State_March;
				m_eCurrentAction = Action_March;
				bChanged = true;
				break;

			case Action_Panic:
				m_state = State_PanicBegin;
				m_eCurrentAction = Action_Panic;
				bChanged = true;
				break;

			case Action_Help:
				m_state = State_Helping;
				m_eCurrentAction = Action_Help;
				bChanged = true;
				// Force it to shoot right away.
				m_lTimer = 0;
				break;

			// In these cases, if a pylon of their type is detected, it
			// will switch them to the correct state, otherwise it will leave
			// the action and the state unchanged.
			case Action_Popout:
				Logic_PylonDetect();
				if (m_bPylonPopoutAvailable)
				{
					m_pPylonEnd = m_pPylonStart->GetPylon(m_pPylonStart->m_msg.msg_Popout.ucIDNext);
					ASSERT(m_pPylonEnd != NULL);
					m_sNextX = m_pPylonStart->GetX();
					m_sNextZ = m_pPylonStart->GetZ();
					m_state = State_PopBegin;								
					m_eCurrentAction = Action_Popout;
					bChanged = true;
				}
				break;

			case Action_RunShoot:
				Logic_PylonDetect();
				if (m_bPylonRunShootAvailable)
				{
					m_pPylonEnd = m_pPylonStart->GetPylon(m_pPylonStart->m_msg.msg_ShootCycle.ucIDNext);
					ASSERT(m_pPylonEnd != NULL);
					m_sNextX = m_pPylonStart->GetX();
					m_sNextZ = m_pPylonStart->GetZ();
					m_state = State_RunShootBegin;
					m_eCurrentAction = Action_RunShoot;
					bChanged = true;
				}
				break;

			case Action_Hide:
				Logic_PylonDetect();
				if (m_bPylonSafeAvailable)
				{
					m_sNextX = m_pPylonStart->GetX();
					m_sNextZ = m_pPylonStart->GetZ();
					m_state = State_HideBegin;
					m_eCurrentAction = Action_Hide;
					bChanged = true;
				}
				break;
		}
	}
	return bChanged;
}

////////////////////////////////////////////////////////////////////////////////
// Message handlers
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Shot Message
////////////////////////////////////////////////////////////////////////////////

void CDoofus::OnShotMsg(Shot_Message* pMessage)
{
	// If he is already shot, just deduct hit points for
	// the additional bullets
	m_stockpile.m_sHitPoints -= pMessage->sDamage;

	if (m_state != State_Burning	&& 
	    m_state != State_BlownUp	&&
		 m_state != State_Die		&& 
		 m_state != State_Dead)
	{
		// Alert other in the area that you are being attacked.
		YellForHelp();

		// Set panic so that victims will panic after being shot
		m_bPanic = true;

		// If he got shot while he was writhing, then he was executed
		// so switch to that animation.
		if (m_state == State_Writhing)
		{
			m_stockpile.m_sHitPoints = 0;
			m_panimCur = &m_animExecuted;
			m_lAnimTime = 0;
			AbortSample(m_siPlaying);
		}
		else
		{
			int32_t lThisTime = m_pRealm->m_time.GetGameTime();
			if (lThisTime > m_lShotTimeout)
			{
				m_lShotTimeout = lThisTime + m_lShotReactionTimeout;

				PlaySoundShot();

				if (	m_state != State_Shot		&&
						m_state != State_Writhing)
				{
					m_ePreviousState = m_state;
					m_panimPrev = m_panimCur;
					m_state = State_Shot;
					m_panimCur = &m_animShot;
					m_lAnimTime = 0;
				}
			}
			// Give him time to escape and move without starting the full 
			// shot animation again
			else
			{
				PlaySoundShot();
			}
		}
	}

	// Let's have some blood no matter what!
	CCharacter::OnShotMsg(pMessage);
}

////////////////////////////////////////////////////////////////////////////////
// Explosion message
////////////////////////////////////////////////////////////////////////////////

void CDoofus::OnExplosionMsg(Explosion_Message* pMessage)
{
	if (
	    m_state != State_BlownUp	&&
		 m_state != State_Die		&& 
		 m_state != State_Dead)
	{
		CCharacter::OnExplosionMsg(pMessage);
		
//		PlaySample(g_smidBlownupYell);
		PlaySoundBlownup();
		m_ePreviousState = m_state;
		m_state = State_BlownUp;
		m_panimPrev = m_panimCur;
		m_panimCur = &m_animDie;
		m_lAnimTime = 0;
		m_stockpile.m_sHitPoints = 0;
		m_lTimer = m_pRealm->m_time.GetGameTime() + 6000;
		GameMessage msg;
		msg.msg_Explosion.eType = typeExplosion;
		msg.msg_Explosion.sPriority = 0;
		CThing* pDemon = m_pRealm->m_aclassHeads[CThing::CDemonID].GetNext();
		if (pDemon)
			SendThingMessage(&msg, pDemon);				
		// If he has a weapon ready, either get rid of it or shoot it off randomly
		CWeapon* pweapon;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pweapon, m_u16IdWeapon) == 0)
		{
			// It should drop like a rock if its a throwing weapon or just delete it if it
			// is a launched weapon
			if (m_eWeaponType == CHeatseekerID || m_eWeaponType == CRocketID || m_eWeaponType == CNapalmID)
			{
				GameMessage msg;
				msg.msg_ObjectDelete.eType = typeObjectDelete;
				msg.msg_ObjectDelete.sPriority = 0;
				SendThingMessage(&msg, pweapon);
			}
			else
			{
				pweapon->m_dHorizVel = (GetRandom() % (int16_t) CGrenade::ms_dThrowHorizVel);
				m_dShootAngle = pweapon->m_dRot = GetRandom() % 360;
				ShootWeapon();
			}
		}

	}
}

////////////////////////////////////////////////////////////////////////////////
// Burning message
////////////////////////////////////////////////////////////////////////////////

void CDoofus::OnBurnMsg(Burn_Message* pMessage)
{
	CCharacter::OnBurnMsg(pMessage);
	m_stockpile.m_sHitPoints -= pMessage->sDamage;

	if (m_state != State_Burning	&& 
	    m_state != State_BlownUp	&&
		 m_state != State_Die		&& 
		 m_state != State_Dead)
	{
		PlaySoundBurning();

		if (m_state == State_Writhing)
		{
			m_sBrightness = BURNT_BRIGHTNESS;
			// May also have to create a small fire at this position
			m_stockpile.m_sHitPoints = 0;
			m_state = State_Dead;
		}
		else
		{
			m_ePreviousState = m_state;
			m_state = State_Burning;

			// If he's not on fire already, switch to on fire animation
			if (m_panimCur != &m_animOnfire)
			{
				m_panimPrev = m_panimCur;
				m_panimCur = &m_animOnfire;
				m_lAnimTime = 0;
				GameMessage msg;
				msg.msg_Burn.eType = typeBurn;
				msg.msg_Burn.sPriority = 0;
				CThing* pDemon = m_pRealm->m_aclassHeads[CThing::CDemonID].GetNext();
				if (pDemon)
					SendThingMessage(&msg, pDemon);				
			}
		}
		// If he has a weapon ready, either get rid of it or shoot it off randomly.
		CWeapon* pweapon;
		if (m_pRealm->m_idbank.GetThingByID((CThing**)&pweapon, m_u16IdWeapon) == 0)
		{
			// It should drop like a rock if its a throwing weapon or just delete it if it
			// is a launched weapon
			if (m_eWeaponType == CHeatseekerID || m_eWeaponType == CRocketID || m_eWeaponType == CNapalmID)
			{
				GameMessage msg;
				msg.msg_ObjectDelete.eType = typeObjectDelete;
				msg.msg_ObjectDelete.sPriority = 0;
				SendThingMessage(&msg, pweapon);
			}
			else
			{
				pweapon->m_dHorizVel = (GetRandom() % (int16_t) CGrenade::ms_dThrowHorizVel);
				m_dShootAngle = pweapon->m_dRot = GetRandom() % 360;
				ShootWeapon();
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Handles an ObjectDelete_Message.
// (virtual).
////////////////////////////////////////////////////////////////////////////////
void CDoofus::OnDeleteMsg(					// Returns nothing.
	ObjectDelete_Message* pdeletemsg)	// In:  Message to handle.
	{
	CCharacter::OnDeleteMsg(pdeletemsg);
	}

////////////////////////////////////////////////////////////////////////////////
// Handles a Help_Message
// (virtual)
////////////////////////////////////////////////////////////////////////////////
void CDoofus::OnHelpMsg(					// Returns nothing
	Help_Message* phelpmsg)					// In:  Message to handle
	{
	m_lLastHelpCallTime = m_pRealm->m_time.GetGameTime();
	// Victium take the yell for help as a indication to panic.
	m_bPanic = true;							
						
	}

////////////////////////////////////////////////////////////////////////////////
// OnDead - override of CCharacter version
////////////////////////////////////////////////////////////////////////////////

void CDoofus::OnDead(void)
{
	CCharacter::OnDead();
}

////////////////////////////////////////////////////////////////////////////////
// Prepare current weapon (ammo).
// This should be done when the character starts its shoot animation.
// (virtual (overriden here) ).
////////////////////////////////////////////////////////////////////////////////
CWeapon* CDoofus::PrepareWeapon(void)	// Returns the weapon ptr or NULL.
{
	// Play sound even if we have no weapon...seems like they're threatening him.
	PlaySoundShooting();

	CWeapon*	pweapon;
	// If we have a weapon . . .
	if (m_eWeaponType != TotalIDs)
	{
		pweapon	= CCharacter::PrepareWeapon();
	}
	else
	{
		pweapon	= NULL;
	}

	return pweapon;
};

////////////////////////////////////////////////////////////////////////////////
// ShootWeapon - Overloaded version to use the Shooting Angle
////////////////////////////////////////////////////////////////////////////////

CWeapon* CDoofus::ShootWeapon(CSmash::Bits bitsInclude, 
										CSmash::Bits bitsDontcare,
										CSmash::Bits bitsExclude)
{
	CWeapon* pWeapon = NULL;
	double dSaveDirection = m_dRot;

	// Don't adjust shooting angle if shooting on the run
	if (m_state != State_ShootRun)
	{
		// Tuned for difficulty level - if the game is in the harder
		// levels, the enemies will tune their aim at the last second
		// before shooting, and then also depending on the difficulty,
		// they will add different amounts of random misses
		// Easy levels   = 1, 2, 3
		// Medium levels = 4, 5, 6
		// Hard levels   = 7, 8, 9, 10, 11
		switch (m_pRealm->m_flags.sDifficulty)
		{
			case 0:
			case 1:
				m_dRot = rspMod360(m_dShootAngle - 8 + (GetRandom() % 17));
				break;

			case 2:
				m_dRot = rspMod360(m_dShootAngle - 7 + (GetRandom() % 15));
				break;

			case 3:
				m_dRot = rspMod360(m_dShootAngle - 6 + (GetRandom() % 13));
				break;

			case 4:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 6 + (GetRandom() % 13));
				break;

			case 5:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 5 + (GetRandom() % 11));
				break;

			case 6:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 4 + (GetRandom() % 9));
				break;

			case 7:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 6 + (GetRandom() % 13));
				break;

			case 8:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 5 + (GetRandom() % 11));
				break;

			case 9:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 4 + (GetRandom() % 9));
				break;

			case 10:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = rspMod360(FindDirection() - 3 + (GetRandom() % 7));
				break;

			case 11:
			default:
				m_dRot = m_dAnimRot = m_dShootAngle = dSaveDirection = FindDirection();
				break;
		}
	}
	else
	{
		m_dRot = m_dShootAngle;
	}
/*
	// Allow rockets to hit other enemies, but still not the special barrel type
	if (m_eWeaponType == CHeatseekerID || m_eWeaponType == CRocketID)
	{
		bitsExclude &= ~CSmash::Bad;
	}
*/
	pWeapon = CCharacter::ShootWeapon(bitsInclude, bitsDontcare, bitsExclude);
	if (pWeapon)
		pWeapon->SetDetectionBits(CSmash::Character | CSmash::Fire,
									  0,
									  CSmash::Bad | CSmash::Ducking | CSmash::AlmostDead);

	m_dRot = dSaveDirection;

	return pWeapon;
}

////////////////////////////////////////////////////////////////////////////////
// RunIdleAnimation - Check the idle timer and pick an idle animation to run
////////////////////////////////////////////////////////////////////////////////

void CDoofus::RunIdleAnimation(void)
{
	int32_t lThisTime = m_pRealm->m_time.GetGameTime();

	if (m_panimCur == &m_animStand)
	{
		if (lThisTime > m_lIdleTimer)
		{
			if (GetRandom() % 3 == 0)
			{
				// Stay with current animation
				m_lIdleTimer = lThisTime + 2000 + GetRandom() % 2000;
			}
			else
			{
				// Go to the Crouch animaiton
				m_panimCur = &m_animCrouch;
				m_lAnimTime = 0;
				m_bAnimUp = true;
				m_lIdleTimer = lThisTime + 3000 + GetRandom() % 2000;
			}
		}
	}
	else
	{
		if (m_panimCur == &m_animCrouch)
		{
			// Animate forward or backward depending on if he is standing up or
			if (m_bAnimUp)
			{
				m_lAnimTime += lThisTime - m_lPrevTime;
				// See if it is time to switch yet
				if (lThisTime > m_lIdleTimer)
				{
					if ((GetRandom() % 3 ) == 0)
					// Start standing up to use the stand animation
					{
						// Start to stand up - run the animation backwards
						m_lAnimTime = m_panimCur->m_psops->TotalTime();
						m_bAnimUp = false;
					}
					else
					{
						// Pick either crouch still or search
						if (GetRandom() % 2)
						{
							// Start search animation
							m_panimCur = &m_animSearch;
							m_lAnimTime = 0;
							m_lIdleTimer = lThisTime + 1000 + GetRandom() % 1500;
						}
						else
						{
							// Stay with still crouch animation
							m_lIdleTimer = lThisTime + 2000 + GetRandom() % 2000;
						}
					}
				}
			}
			else
			{
				m_lAnimTime -= lThisTime - m_lPrevTime;
				// See if it is done standing yet.  If so, you have
				// already previously decided to end the crouch animation
				// so now pick the stand animation
				if (m_lAnimTime < 0)
				{
					m_panimCur = &m_animStand;
					m_lAnimTime = 0;
					m_lIdleTimer = lThisTime + 3000 + GetRandom() % 2000;
				}
			}
		}
		else
		{
			if (m_panimCur == &m_animSearch)
			{
				// Animate the search 
				m_lAnimTime += lThisTime - m_lPrevTime;
				// See if its time to switch yet
				if (lThisTime > m_lIdleTimer)
				{
					switch (GetRandom() % 3)
					{
						case 0:	// Stay with current animation
							m_lIdleTimer = lThisTime + 1000 + GetRandom() % 1000;
							break;

						case 1:	// Go to Crouch animation
							m_panimCur = &m_animCrouch;
							m_bAnimUp = true;
							m_lIdleTimer = lThisTime + 3000 + GetRandom() % 2000;
							break;

						case 2:	// Go to stand - use Crouch backwards to get up
							m_panimCur = &m_animCrouch;
							m_bAnimUp = false;
							m_lAnimTime = m_panimCur->m_psops->TotalTime();
							m_lIdleTimer = lThisTime + 3000 + GetRandom() % 2500;
							break;
					}					
				}
			}
			// Start the stand animation since it isn't currently using any idle animations.
			else
			{
				m_panimCur = &m_animStand;
				m_lIdleTimer = lThisTime + 3000;
				m_lAnimTime = 0;			
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Position our smash approriately.
// (virtual).
////////////////////////////////////////////////////////////////////////////////
void CDoofus::PositionSmash(void)
	{
	// If not in writhing state . . .
	if (m_state != State_Writhing)
		{
		// Update sphere.
		m_smash.m_sphere.sphere.X			= m_dX;
		m_smash.m_sphere.sphere.Y			= m_dY + m_sprite.m_sRadius;
		m_smash.m_sphere.sphere.Z			= m_dZ;
		m_smash.m_sphere.sphere.lRadius	= m_sprite.m_sRadius;
		}
	else
		{
		// If we have the execution points . . .
		if (m_ptransExecutionTarget)
			{
			// Compute link point for execution target.
			double	dVitalOrganX;
			double	dVitalOrganY;
			double	dVitalOrganZ;
			GetLinkPoint(														// Returns nothing.
				m_ptransExecutionTarget->GetAtTime(m_lAnimTime),	// In:  Transform specifying point.
				&dVitalOrganX,													// Out: Point speicfied.
				&dVitalOrganY,													// Out: Point speicfied.
				&dVitalOrganZ);												// Out: Point speicfied.			// Update execution point via link point.

			// Offset from hotspot to set collision sphere position.
			m_smash.m_sphere.sphere.X			= m_dX + dVitalOrganX;              
			m_smash.m_sphere.sphere.Y			= m_dY + dVitalOrganY;
			m_smash.m_sphere.sphere.Z			= m_dZ + dVitalOrganZ;
			m_smash.m_sphere.sphere.lRadius	= m_sprite.m_sRadius;
			}
		else
			{
			ASSERT(m_dRot >= 0);
			ASSERT(m_dRot < 360);
			// Try to find center.
			// Let's go a radius up their torso.  Say... .
			// This only looks decent if m_dRot is the direction they fell which is
			// not always the case.
			int16_t	sPseudoCenter	= m_sprite.m_sRadius;
			m_smash.m_sphere.sphere.X			= m_dX + COSQ[int16_t(m_dRot)] * sPseudoCenter;
			m_smash.m_sphere.sphere.Y			= m_dY + m_sprite.m_sRadius;              
			m_smash.m_sphere.sphere.Z			= m_dZ - SINQ[int16_t(m_dRot)] * sPseudoCenter;              
			m_smash.m_sphere.sphere.lRadius	= m_sprite.m_sRadius;
			}
		}
	}

////////////////////////////////////////////////////////////////////////////////
//	WhileHoldingWeapon
//
// Override for the character version which will just re-aim the guy during the
// shoot-prepare frames.  Otherwise, guys like the rocketman which has a long
// prepare animation, quickly flip around in ShootWeapon if the target has moved
// between PrepareWeapon and ShootWeapon.
//
////////////////////////////////////////////////////////////////////////////////

bool CDoofus::WhileHoldingWeapon(	// Returns true when weapon is released.
				U32 u32BitsInclude,		// In:  Collision bits passed to ShootWeapon
				U32 u32BitsDontcare,		// In:  Collision bits passed to ShootWeapon
				U32 u32BitsExclude)		// In:  Collision bits passed to ShootWeapon
{
	bool bResult = true;

	// If they haven't shot the weapon yet, adjust their aiming if the difficulty
	// level allows them to re-aim after preparing the weapon
	if (!(CCharacter::WhileHoldingWeapon(u32BitsInclude, u32BitsDontcare, u32BitsExclude)))
	{
		bResult = false;
		// Don't adjust shooting angle if shooting on the run
		if (m_state != State_ShootRun)
		{
			// Tuned for difficulty level - if the game is in the harder
			// levels, the enemies will tune their aim at the last second
			// before shooting, and then also depending on the difficulty,
			// they will add different amounts of random misses
			// Easy levels   = 1, 2, 3
			// Medium levels = 4, 5, 6
			// Hard levels   = 7, 8, 9, 10, 11
			switch (m_pRealm->m_flags.sDifficulty)
			{
				// Easy levels don't re-aim after preparing weapon, so leve it alone
				case 0:
				case 1:
				case 2:
				case 3:
				case 4:
				case 5:
				case 6:
					break;

				// More difficult levels allow constant re-aiming.
				case 7:
				case 8:
				case 9:
				case 10:
				case 11:
				default:
					m_dRot = m_dAnimRot = m_dShootAngle = rspMod360(FindDirection());
					break;
			}
		}
	}
	return bResult;
}


////////////////////////////////////////////////////////////////////////////////
// A way for the base class to get resources.  If you are going to use
// any of this class's resources (e.g., ms_aanimWeapons[]), call this
// when getting your resources.
////////////////////////////////////////////////////////////////////////////////
int16_t CDoofus::GetResources(void)
	{
	int16_t	sResult	= 0;

	// If the ref count was 0 . . .
	if (ms_lWeaponResRefCount++ == 0)
		{
		// Get the actual resources.
		int16_t	i;
		int16_t	sLoadResult;
		for (i = 0; i < NumWeaponTypes; i++)
			{
			// If this weapon has a visible resource . . .
			if (ms_awdWeapons[i].pszResName)
				{
				sLoadResult	= ms_aanimWeapons[i].Get(
					ms_awdWeapons[i].pszResName, 
					NULL, 
					NULL, 
					NULL, 
					RChannel_LoopAtStart | RChannel_LoopAtEnd);

				if (sLoadResult != 0)
					{
					TRACE("GetResources(): Failed to load weapon resource \"%s\".\n",
						ms_awdWeapons[i].pszResName);
					sResult	= -1;
					}
				}
			}
		}

	return sResult;
	}

////////////////////////////////////////////////////////////////////////////////
// A way for the base class to release resources.  If you are going to use
// any of this class's resources (e.g., ms_aanimWeapons[]), call this
// when releasing your resources.
////////////////////////////////////////////////////////////////////////////////
void CDoofus::ReleaseResources(void)
	{
	ASSERT(ms_lWeaponResRefCount > 0);

	// If the ref count hits zero with this release . . .
	if (--ms_lWeaponResRefCount == 0)
		{
		// Release the actual resources.
		int16_t	i;
		for (i = 0; i < NumWeaponTypes; i++)
			{
			if (ms_aanimWeapons[i].m_pmeshes)
				{
				ms_aanimWeapons[i].Release();
				}
			}
		}
	}

////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////