File: spl-cast.cc

package info (click to toggle)
crawl 2%3A0.34.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 100,188 kB
  • sloc: cpp: 363,709; ansic: 27,765; javascript: 9,516; python: 8,463; perl: 3,293; java: 3,132; xml: 2,380; makefile: 1,835; sh: 611; objc: 250; cs: 15; sed: 9; lisp: 3
file content (3541 lines) | stat: -rw-r--r-- 116,576 bytes parent folder | download | duplicates (2)
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
/**
 * @file
 * @brief Spell casting and miscast functions.
**/

#include "AppHdr.h"

#include "spl-cast.h"

#include <iomanip>
#include <sstream>
#include <cmath>

#include "act-iter.h"
#include "areas.h"
#include "art-enum.h"
#include "beam.h"
#include "chardump.h"
#include "cloud.h"
#include "colour.h"
#include "coordit.h"
#include "database.h"
#include "describe.h"
#include "directn.h"
#include "english.h"
#include "env.h"
#include "evoke.h"
#include "exercise.h"
#include "format.h"
#include "god-abil.h"
#include "god-conduct.h"
#include "god-item.h"
#include "god-passive.h" // passive_t::shadow_spells
#include "hints.h"
#include "items.h"
#include "item-prop.h"
#include "item-use.h"
#include "libutil.h"
#include "macro.h"
#include "menu.h"
#include "melee-attack.h"
#include "message.h"
#include "misc.h"
#include "mon-behv.h"
#include "mon-cast.h"
#include "mon-explode.h"
#include "mon-place.h"
#include "mon-project.h"
#include "mon-util.h"
#include "mutation.h"
#include "options.h"
#include "ouch.h"
#include "output.h"
#include "player.h"
#include "player-notices.h"
#include "player-stats.h"
#include "prompt.h"
#include "religion.h"
#include "shout.h"
#include "skills.h"
#include "spl-book.h"
#include "spl-clouds.h"
#include "spl-damage.h"
#include "spl-goditem.h"
#include "spl-miscast.h"
#include "spl-monench.h"
#include "spl-other.h"
#include "spl-selfench.h"
#include "spl-summoning.h"
#include "spl-transloc.h"
#include "spl-zap.h"
#include "state.h"
#include "stepdown.h"
#include "stringutil.h"
#include "tag-version.h"
#include "target.h"
#include "teleport.h"
#include "terrain.h"
#include "tilepick.h"
#include "timed-effects.h"
#include "transform.h"
#include "unicode.h"
#include "unwind.h"
#include "view.h"
#include "viewchar.h" // stringize_glyph

static int _spell_enhancement(spell_type spell);
static int _apply_enhancement(const int initial_power,
                              const int enhancer_levels);
static string _spell_failure_rate_description(spell_type spell);

void surge_power(const int enhanced)
{
    if (enhanced)               // one way or the other {dlb}
    {
        const string modifier = (enhanced  < -2) ? "extraordinarily" :
                                (enhanced == -2) ? "extremely" :
                                (enhanced ==  2) ? "strong" :
                                (enhanced  >  2) ? "huge"
                                                 : "";
        mprf("You feel %s %s",
             !modifier.length() ? "a"
                                : article_a(modifier).c_str(),
             (enhanced < 0) ? "numb sensation."
                            : "surge of power!");
    }
}

void surge_power_wand(const int mp_cost)
{
    if (mp_cost)
    {
        const bool slight = mp_cost < 3;
        mprf("You feel a %ssurge of power%s",
             slight ? "slight " : "",
             slight ? "."      : "!");
    }
}

static string _spell_base_description(spell_type spell, bool transient)
{
    ostringstream desc;

    int highlight =  spell_highlight_by_utility(spell, COL_UNKNOWN, transient);
    if (you.duration[DUR_ENKINDLED] && highlight == COL_UNKNOWN
        && spell_can_be_enkindled(spell))
    {
        highlight = LIGHTCYAN;
    }

    desc << "<" << colour_to_str(highlight) << ">" << left;

    // spell name
    desc << chop_string(spell_title(spell), 32);

    // spell schools
    desc << spell_schools_string(spell);

    const int so_far = strwidth(desc.str()) - (strwidth(colour_to_str(highlight))+2);
    if (so_far < 58)
        desc << string(58 - so_far, ' ');

    // spell fail rate, level
    const string failure_rate = spell_failure_rate_string(spell, false);
    const int width = strwidth(formatted_string::parse_string(failure_rate).tostring());
    const bool show_enkindle = you.has_mutation(MUT_MNEMOPHAGE);

    // Revenants have spell level right-justified instead of left-justified to make
    // room to show enkindled spell success rates.
    desc << failure_rate << string((show_enkindle ? 13 : 9)-width, ' ');
    desc << spell_difficulty(spell);
    // XXX: This exact padding is needed to make the webtiles spell menu not re-align
    //      itself whenever we toggle display modes. For some reason, this doesn't
    //      seem to matter for local tiles. Who know why?
    desc << string(show_enkindle ? 2 : 6, ' ');
    desc << "</" << colour_to_str(highlight) <<">";

    return desc.str();
}

static string _spell_extra_description(spell_type spell, bool transient)
{
    ostringstream desc;

    int highlight =  spell_highlight_by_utility(spell, COL_UNKNOWN, transient);
    if (you.duration[DUR_ENKINDLED] && spell_can_be_enkindled(spell) && highlight == COL_UNKNOWN)
        highlight = LIGHTCYAN;

    desc << "<" << colour_to_str(highlight) << ">" << left;

    // spell name
    desc << chop_string(spell_title(spell), 32);

    // spell power, spell range, noise
    const string rangestring = spell_range_string(spell);
    const string damagestring = spell_damage_string(spell, false, -1, true);

    desc << chop_string(spell_power_string(spell), 10)
         << chop_string(damagestring.length() ? damagestring : "N/A", 10)
         << chop_string(rangestring, 8)
         << chop_string(spell_noise_string(spell, 10), 14);

    desc << "</" << colour_to_str(highlight) <<">";

    return desc.str();
}

class SpellMenuEntry : public ToggleableMenuEntry
{
public:
    SpellMenuEntry(const string &txt,
                   const string &alt_txt,
                   MenuEntryLevel lev,
                   int qty, int hotk)
        : ToggleableMenuEntry(txt, alt_txt, lev, qty, hotk)
    {
    }

    bool preselected = false;
protected:
    virtual string _get_text_preface() const override
    {
        if (preselected)
            return make_stringf(" %s + ", keycode_to_name(hotkeys[0]).c_str());
        return ToggleableMenuEntry::_get_text_preface();
    }
};

class SpellMenu : public ToggleableMenu
{
public:
    SpellMenu()
        : ToggleableMenu(MF_SINGLESELECT | MF_ANYPRINTABLE
            | MF_NO_WRAP_ROWS | MF_ALLOW_FORMATTING
            | MF_ARROWS_SELECT | MF_INIT_HOVER) {}
protected:
    command_type get_command(int keyin) override
    {
        if (keyin == '?')
            return CMD_MENU_HELP;
        return ToggleableMenu::get_command(keyin);
    }

    bool process_command(command_type cmd) override
    {
        if (cmd == CMD_MENU_HELP)
        {
            int idx = last_hovered;
            if (idx >= 0 && idx < static_cast<int>(items.size()))
            {
                examine_index(idx);
                return true;
            }
        }

        get_selected(&sel);
        // if there's a preselected item, and no current selection, select it.
        // for arrow selection, the hover starts on the preselected item so no
        // special handling is needed.
        if (menu_action == ACT_EXECUTE && cmd == CMD_MENU_SELECT
            && !(flags & MF_ARROWS_SELECT) && sel.empty())
        {
            for (size_t i = 0; i < items.size(); ++i)
            {
                if (static_cast<SpellMenuEntry*>(items[i])->preselected)
                {
                    select_index(i, 1);
                    break;
                }
            }
        }
        return ToggleableMenu::process_command(cmd);
    }

    bool examine_index(int i) override
    {
        ASSERT(i >= 0 && i < static_cast<int>(items.size()));
        if (items[i]->hotkeys.size())
            describe_spell(get_spell_by_letter(items[i]->hotkeys[0]), nullptr);
        return true;
    }
};

// selector is a boolean function that filters spells according
// to certain criteria. Currently used for Tiles to distinguish
// spells targeted on player vs. spells targeted on monsters.
int list_spells(bool toggle_with_I, bool transient, bool viewing,
                bool allow_preselect, const string &action)
{
    if (toggle_with_I && get_spell_by_letter('I') != SPELL_NO_SPELL)
        toggle_with_I = false;

    const string real_action = viewing ? "describe" : action;

    SpellMenu spell_menu;
    const string titlestring = make_stringf("%-25.25s",
            make_stringf("Your spells (%s)", real_action.c_str()).c_str());

    {
        ToggleableMenuEntry* me =
            new ToggleableMenuEntry(
                titlestring + "           Type                      Failure  Level  ",
                titlestring + "           Power     Damage    Range   Noise         ",
                MEL_TITLE);
        spell_menu.set_title(me, true, true);
    }
    spell_menu.set_highlighter(nullptr);
    spell_menu.set_tag("spell");
    // TODO: add toggling to describe mode with `?`, add help string, etc...
    spell_menu.add_toggle_from_command(CMD_MENU_CYCLE_MODE);
    spell_menu.add_toggle_from_command(CMD_MENU_CYCLE_MODE_REVERSE);

    string more_str = make_stringf("<lightgrey>Select a spell to %s</lightgrey>",
        real_action.c_str());
    string help_desc = make_stringf("   [<w>?</w>] help    ");
    string toggle_desc = menu_keyhelp_cmd(CMD_MENU_CYCLE_MODE);
    if (toggle_with_I)
    {
        // why `I`?
        spell_menu.add_toggle_key('I');
        toggle_desc += "/[<w>I</w>]";
    }
    toggle_desc += " toggle spell headers";
    more_str = pad_more_with_esc(more_str + help_desc + toggle_desc);
    spell_menu.set_more(formatted_string::parse_string(more_str));
    // TODO: should allow toggling between execute and examine
    spell_menu.menu_action = viewing ? Menu::ACT_EXAMINE : Menu::ACT_EXECUTE;

    int initial_hover = 0;
    for (int i = 0; i < 52; ++i)
    {
        const char letter = index_to_letter(i);
        const spell_type spell = get_spell_by_letter(letter);

        if (!is_valid_spell(spell))
            continue;

        SpellMenuEntry* me =
            new SpellMenuEntry(_spell_base_description(spell, transient),
                               _spell_extra_description(spell, transient),
                               MEL_ITEM, 1, letter);
        me->colour = spell_highlight_by_utility(spell, COL_UNKNOWN, transient);
        // TODO: maybe fill this from the quiver if there's a quivered spell and
        // no last cast one?
        if (allow_preselect && you.last_cast_spell == spell)
        {
            initial_hover = i;
            me->preselected = true;
        }

        me->add_tile(tile_def(tileidx_spell(spell)));
        spell_menu.add_entry(me);
    }
    spell_menu.set_hovered(initial_hover);

    int choice = 0;
    spell_menu.on_single_selection = [&choice](const MenuEntry& item)
    {
        ASSERT(item.hotkeys.size() == 1);
        choice = item.hotkeys[0];
        return false;
    };

    spell_menu.show();
    if (!crawl_state.doing_prev_cmd_again)
    {
        redraw_screen();
        update_screen();
    }
    return choice;
}

// Effects that happen after spells which are otherwise simple zaps.
static void _apply_post_zap_effect(spell_type spell, coord_def target)
{
    switch (spell)
    {
    case SPELL_SANDBLAST:
        you.time_taken = you.time_taken * 3 / 2;
        break;
    case SPELL_KISS_OF_DEATH:
        drain_player(100, true, true);
        break;
    case SPELL_BOMBARD:
        if (coinflip())
            you.stumble_away_from(target, "the blast");
        break;
    default:
        break;
    }
}

static int _apply_spellcasting_success_boosts(spell_type spell, int chance)
{
    int fail_reduce = 100;

    if (have_passive(passive_t::spells_success) && vehumet_supports_spell(spell))
    {
        // [dshaligram] Fail rate multiplier used to be .5, scaled
        // back to 67%.
        fail_reduce = fail_reduce * 2 / 3;
    }

    if (you.form == transformation::rime_yak && spell_typematch(spell, spschool::ice))
        fail_reduce = fail_reduce * 2 / 3;
    if (you.form == transformation::sphinx && spell_typematch(spell, spschool::hexes))
        fail_reduce = fail_reduce * 2 / 3;

    if (you.form == transformation::sun_scarab && spell_typematch(spell, spschool::fire))
        fail_reduce = fail_reduce * 2 / 3;

    if (you.wearing_ego(OBJ_ARMOUR, SPARM_COMMAND) && spell_typematch(spell, spschool::summoning))
        fail_reduce = fail_reduce * 180 / (180 + you.skill(SK_ARMOUR, 10));

    if (you.wearing_ego(OBJ_ARMOUR, SPARM_DEATH) && spell_typematch(spell, spschool::necromancy))
        fail_reduce = fail_reduce / 2;

    if (you.wearing_ego(OBJ_ARMOUR, SPARM_RESONANCE) && spell_typematch(spell, spschool::forgecraft))
        fail_reduce = fail_reduce * 2 / 3;

    const int wizardry = player_wizardry();

    if (wizardry > 0)
      fail_reduce = fail_reduce * 6 / (7 + wizardry);

    return chance * fail_reduce / 100;
}



/*
 * Given some spellpower in centis, do a stepdown at around 50 (5000 in centis)
 * and return a rescaled value.
 *
 * @param power the input spellpower in centis.
 * @param scale a value to scale the result by, between 1 and 1000. Default is
 *        1, which returns a regular spellpower. 1000 gives you millis, 100
 *        centis.
 */
static int _stepdown_spellpower(int power)
{
    const int divisor = 1000;
    int result = stepdown_value(power * 10, 50000, 50000, 150000, 200000)
                    / divisor;
    return result;
}

static int _skill_power(spell_type spell)
{
    int power = 0;
    const spschools_type disciplines = get_spell_disciplines(spell);
    const int skillcount = count_bits(disciplines);
    if (skillcount)
    {
        for (const auto bit : spschools_type::range())
            if (disciplines & bit)
                power += you.skill(spell_type2skill(bit), 200);
        power /= skillcount;
    }
    return power + you.skill(SK_SPELLCASTING, 50);
}


/**
 * Calculate the player's failure rate with the given spell, including all
 * modifiers. (Armour, mutations, statuses effects, etc.)
 *
 * @param spell     The spell in question.
 * @param enkindled Whether to calculate the failure rate as if the player were
 *                  currently enkindled (even if they aren't). Defaults to
 *                  false.
 * @return          A failure rate. This is *not* a percentage - for a human-
 *                  readable version, call _get_true_fail_rate().
 */
int raw_spell_fail(spell_type spell, bool enkindled)
{
    if (spell == SPELL_NO_SPELL)
        return 10000;

    enkindled = (enkindled || (you.duration[DUR_ENKINDLED])
                    && spell_can_be_enkindled(spell));

    int chance = 60;

    // Don't cap power for failure rate purposes.
    // scale by 6, which I guess was chosen because it seems to work.
    // realistic range for spellpower: -6 to -366 (before scale -1 to -61)
    chance -= _skill_power(spell) * 6 / 100;
    chance -= (you.intel() * 2); // realistic range: -2 to -70

    const int armour_shield_penalty = player_armour_shield_spell_penalty();

    if (!enkindled)
    {
        chance += armour_shield_penalty; // range: 0 to 500 in extreme cases.
                                         // A midlevel melee character in plate
                                         // might have 40 or 50, and a caster in a
                                         // robe would usually have 0.
    }

    static const int difficulty_by_level[] =
    {
        0,
        3,
        15,
        35,

        70,
        100,
        150,

        200,
        260,
        340,
    };
    const int spell_level = spell_difficulty(spell);
    ASSERT_RANGE(spell_level, 0, (int) ARRAYSZ(difficulty_by_level));
    chance += difficulty_by_level[spell_level]; // between 0 and 330

    // since chance is passed through a 3rd degree polynomial, cap the
    // value to avoid any overflow issues. I choose 400 as a value that will
    // remain above 100 no matter how much wizardry the player stacks (so that
    // we don't get weird effects of the visible success chance being non-0 at
    // low skill and not improving as skill is gained.)
    chance = min(chance, 400);

    // This polynomial is a smoother approximation of a breakpoint-based
    // calculation that originates pre-DCSS, mapping `chance` at this point to
    // values from around 0 to around 45. (see
    // https://crawl.develz.org/tavern/viewtopic.php?f=8&t=23414 for some of
    // the history.)  It was calculated by |amethyst (based on one from minmay
    // in that thread) and converted to integer values using 262144 as a
    // convenient power of 2 denominator, then converted to its current form
    // by Horner's rule, and then tweaked slightly.
    //
    // The regular (integer) polynomial form before Horner's rule is:
    //          (x*x*x + 426*x*x + 82670*x + 7245398) / 262144
    //
    // https://www.wolframalpha.com/input/?i=graph+of+y%3D(((x+%2B+426)*x+%2B+82670)*x+%2B+7245398)+%2F+262144+and+y%3D100+and+x%3D125.1+with+x+from+-192+to+126.1
    //
    // If you think this is weird, you should see what was here before.
    int chance2 = max((((chance + 426) * chance + 82670) * chance + 7245398)
                      / 262144, 0);

    chance2 -= 2 * you.get_mutation_level(MUT_SUBDUED_MAGIC);
    chance2 += 4 * you.get_mutation_level(MUT_WILD_MAGIC);
    chance2 += 4 * you.get_mutation_level(MUT_ANTI_WIZARDRY);
    if (you.wearing_ego(OBJ_ARMOUR, SPARM_ENERGY))
        chance2 += 10;

    chance2 += you.duration[DUR_VERTIGO] ? 7 : 0;

    // Apply the effects of Vehumet and items of wizardry.
    chance2 = _apply_spellcasting_success_boosts(spell, chance2);

    if (enkindled)
        chance2 = chance2 * 3 / 4 - 5;

    return min(max(chance2, 0), 100);
}


/*
 * Calculate spell power.
 *
 * @param spell         the spell to check
 *
 * @return the resulting spell power.
 */
int calc_spell_power(spell_type spell)
{
    int power = _skill_power(spell);

    if (you.divine_exegesis)
        power += you.skill(SK_INVOCATIONS, 300);

    power = (power * you.intel()) / 10;

    // [dshaligram] Enhancers don't affect fail rates any more, only spell
    // power. Note that this does not affect Vehumet's boost in castability.
    power = _apply_enhancement(power, _spell_enhancement(spell));

    // Wild magic boosts spell power but decreases success rate.
    power *= (10 + 3 * you.get_mutation_level(MUT_WILD_MAGIC));
    power /= (10 + 3 * you.get_mutation_level(MUT_SUBDUED_MAGIC));

    // Augmentation boosts spell power at high HP.
    power *= 10 + 4 * augmentation_amount();
    power /= 10;

    // Each level of horror reduces spellpower by 10%
    if (you.duration[DUR_HORROR])
    {
        power *= 10;
        power /= 10 + (you.props[HORROR_PENALTY_KEY].get_int() * 3) / 2;
    }

    if (you.duration[DUR_ENKINDLED] && spell_can_be_enkindled(spell))
        power = (power + (you.experience_level * 300)) * 3 / 2;

    if (you.wearing_ego(OBJ_ARMOUR, SPARM_COMMAND) && spell_typematch(spell, spschool::summoning))
        power = power * (270 + you.skill(SK_ARMOUR, 10)) / 270;

    // at this point, `power` is assumed to be basically in centis.
    // apply a stepdown, and scale.
    power = _stepdown_spellpower(power);

    const int cap = spell_power_cap(spell);
    if (cap > 0)
        power = min(power, cap);

    // Post step-down and post-cap, so the result is more predictable to the player.
    if (you.duration[DUR_DIMINISHED_SPELLS])
        power = power / 2;

    // Claustrophobia reduces power by 10% per wall.
    if (you.has_bane(BANE_CLAUSTROPHOBIA))
        power = power * (100 - you.props[CLAUSTROPHOBIA_KEY].get_int() * 5) / 100;

    return power;
}

static int _spell_enhancement(spell_type spell)
{
    const spschools_type typeflags = get_spell_disciplines(spell);
    int enhanced = 0;

    if (typeflags & spschool::conjuration)
        enhanced += player_spec_conj();

    if (typeflags & spschool::hexes)
        enhanced += player_spec_hex();

    if (typeflags & spschool::summoning)
        enhanced += player_spec_summ();

    if (typeflags & spschool::forgecraft)
        enhanced += player_spec_forgecraft();

    if (typeflags & spschool::alchemy)
        enhanced += player_spec_alchemy();

    if (typeflags & spschool::necromancy)
        enhanced += player_spec_death();

    if (typeflags & spschool::translocation)
        enhanced += player_spec_tloc();

    if (typeflags & spschool::fire)
        enhanced += player_spec_fire();

    if (typeflags & spschool::ice)
        enhanced += player_spec_cold();

    if (typeflags & spschool::earth)
        enhanced += player_spec_earth();

    if (typeflags & spschool::air)
        enhanced += player_spec_air();

    if (you.form == transformation::jelly)
        enhanced -= 2;

    if (you.unrand_equipped(UNRAND_BATTLE))
    {
        if (vehumet_supports_spell(spell))
            enhanced++;
        else
            enhanced--;
    }

    enhanced += you.archmagi();
    enhanced += you.duration[DUR_BRILLIANCE] > 0
                || you.unrand_equipped(UNRAND_FOLLY);

    // These are used in an exponential way, so we'll limit them a bit. -- bwr
    if (enhanced > 3)
        enhanced = 3;
    else if (enhanced < -3)
        enhanced = -3;

    return enhanced;
}

/**
 * Apply the effects of spell enhancers (and de-enhancers) on spellpower.
 *
 * @param initial_power     The power of the spell before enhancers are added.
 * @param enhancer_levels   The number of enhancements levels to apply.
 * @return                  The power of the spell with enhancers considered.
 */
static int _apply_enhancement(const int initial_power,
                              const int enhancer_levels)
{
    int power = initial_power;

    if (enhancer_levels > 0)
    {
        for (int i = 0; i < enhancer_levels; i++)
        {
            power *= 15;
            power /= 10;
        }
    }
    else if (enhancer_levels < 0)
    {
        for (int i = enhancer_levels; i < 0; i++)
            power /= 2;
    }

    return power;
}

void inspect_spells()
{
    if (!you.spell_no)
    {
        canned_msg(MSG_NO_SPELLS);
        return;
    }

    list_spells(true, false, true);
}

/**
 * Can the player cast any spell at all? Checks for things that limit
 * spellcasting regardless of the specific spell we want to cast.
 *
 * @param quiet    If true, don't print a reason why no spell can be cast.
 * @return True if we could cast a spell, false otherwise.
*/
bool can_cast_spells(bool quiet)
{
    if (!get_form()->can_cast)
    {
        if (!quiet)
            canned_msg(MSG_PRESENT_FORM);
        return false;
    }

    if (you.duration[DUR_NO_CAST])
    {
        if (!quiet)
            mpr("You are unable to access your magic!");
        return false;
    }

    // Randart weapons.
    if (you.no_cast())
    {
        if (!quiet)
            mpr("Something interferes with your magic!");
        return false;
    }

    if (you.berserk())
    {
        if (!quiet)
            canned_msg(MSG_TOO_BERSERK);
        return false;
    }

    if (you.confused())
    {
        if (!quiet)
            mpr("You're too confused to cast spells.");
        return false;
    }

    if (you.is_silenced())
    {
        if (!quiet)
        {
            mprf("You cannot cast spells while %s!", player_silenced_reason());
            // included in default force_more_message
        }
        return false;
    }

    return true;
}

void do_cast_spell_cmd(bool force)
{
    if (cast_a_spell(!force) == spret::abort)
        flush_input_buffer(FLUSH_ON_FAILURE);
}

static void _handle_energy_orb(int cost, spret cast_result)
{
    if (cast_result == spret::abort || !you.wearing_ego(OBJ_ARMOUR, SPARM_ENERGY))
        return;

    const int chance = player_channelling_chance();
    if (chance <= 0)
        return;

    // Miscasts always get refunded, successes only sometimes do.
    if (cast_result != spret::fail && !x_chance_in_y(chance, 100))
        return;

    if (you.unrand_equipped(UNRAND_WUCAD_MU) && cast_result == spret::success)
    {
        vector<monster*> targs;
        for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
        {
            if (mi->antimagic_susceptible() && !mi->has_ench(ENCH_ANTIMAGIC)
                && !mi->wont_attack() && x_chance_in_y(cost, 9))
            {
                targs.push_back(*mi);
                mi->add_ench(mon_enchant(ENCH_ANTIMAGIC, &you, random_range(20, 50)));
            }
        }

        int drain = !targs.empty() ? random_range(1, 3) + targs.size() / 2 : 0;

        if (targs.empty())
            mpr("Magical energy flows into your mind!");
        else
            mprf("Magical energy flows from %s into your mind!",
                 describe_monsters_condensed(targs).c_str());
        inc_mp(cost + drain);
    }
    else
    {
        mpr("Magical energy flows into your mind!");
        inc_mp(cost, true);
    }
    did_god_conduct(DID_WIZARDLY_ITEM, 10);
}

/**
 * Let the Majin-Bo congratulate you on casting a spell while using it.
 *
 * @param spell     The spell just successfully cast.
 */
static void _majin_speak(spell_type spell)
{
    // since this isn't obviously mental communication, let it be silenced
    if (silenced(you.pos()))
        return;

    const int level = spell_difficulty(spell);
    const bool weak = level <= 4;
    const string lookup = weak ? "majin-bo cast weak" : "majin-bo cast";
    const string msg = "A voice whispers, \"" + getSpeakString(lookup) + "\"";
    mprf(MSGCH_TALK, "%s", msg.c_str());
}

static bool _majin_charge_hp()
{
    return you.unrand_equipped(UNRAND_MAJIN) && !you.duration[DUR_DEATHS_DOOR];
}

static bool _death_ego_charge_hp(spell_type spell)
{
    return you.wearing_ego(OBJ_ARMOUR, SPARM_DEATH)
            && !spell_typematch(spell, spschool::necromancy)
            && !you.duration[DUR_DEATHS_DOOR];
}


static int _spell_addition_hp_cost(spell_type spell)
{
    const int spell_cost = spell_mana(spell);
    int hp_cost = 0;
    if (_majin_charge_hp())
        hp_cost += spell_cost;
    if (_death_ego_charge_hp(spell))
        hp_cost += spell_cost;
    // The cost shouldn't ever kill you
    hp_cost = min(hp_cost, you.hp - 1);
    return hp_cost;
}

/**
 * Cast a spell.
 *
 * Handles general preconditions & costs.
 *
 * @param check_range   If true, abort if no targets are in range. (z vs Z)
 * @param spell         The type of spell to be cast.
 * @param force_failure True if the spell's failure has already been determined
 *                      in advance (for spells being cast via Divine Exegesis).
 * @return              Whether the spell was successfully cast.
 **/
spret cast_a_spell(bool check_range, spell_type spell, dist *_target,
                   bool force_failure)
{
    // If you don't have any spells memorized (and aren't using exegesis),
    // you can't cast any spells. Simple as.
    if (!you.spell_no && !you.divine_exegesis)
    {
        canned_msg(MSG_NO_SPELLS);
        return spret::abort;
    }

    if (!can_cast_spells())
    {
        crawl_state.zero_turns_taken();
        return spret::abort;
    }

    if (crawl_state.game_is_hints())
        Hints.hints_spell_counter++;

    if (spell == SPELL_NO_SPELL)
    {
        int keyin = 0;

        string luachoice;
        if (!clua.callfn("c_choose_spell", ">s", &luachoice))
        {
            if (!clua.error.empty())
                mprf(MSGCH_ERROR, "Lua error: %s", clua.error.c_str());
        }
        else if (!luachoice.empty() && isalpha(luachoice[0]))
        {
            keyin = luachoice[0];
            const spell_type spl = get_spell_by_letter(keyin);

            // Bad entry from lua, defer to the user
            if (!is_valid_spell(spl))
                keyin = 0;
        }

        while (true)
        {
            if (keyin == 0 && !Options.spell_menu)
            {
                if (you.spell_no == 1)
                {
                    // Set last_cast_spell to the current only spell.
                    for (int i = 0; i < 52; ++i)
                    {
                        const char letter = index_to_letter(i);
                        const spell_type spl = get_spell_by_letter(letter);

                        if (!is_valid_spell(spl))
                            continue;

                        you.last_cast_spell = spl;
                        break;
                    }
                }

                // We allow setting last cast spell by Divine Exegesis, but we
                // don't allow recasting it with the UI unless we actually have
                // the spell memorized.
                if (you.last_cast_spell != SPELL_NO_SPELL
                    && !you.has_spell(you.last_cast_spell))
                {
                    you.last_cast_spell = SPELL_NO_SPELL;
                }

                if (you.last_cast_spell == SPELL_NO_SPELL
                    || !Options.enable_recast_spell)
                {
                    mprf(MSGCH_PROMPT, "Cast which spell? (? or * to list) ");
                }
                else
                {
                    mprf(MSGCH_PROMPT, "Casting: <w>%s</w> <lightgrey>(%s)</lightgrey>",
                                       spell_title(you.last_cast_spell),
                                       _spell_failure_rate_description(you.last_cast_spell).c_str());
                    mprf(MSGCH_PROMPT, "Confirm with . or Enter, or press "
                                       "? or * to list all spells.");
                }

                keyin = numpad_to_regular(get_ch());
            }

            if (keyin == '?' || keyin == '*' || Options.spell_menu)
            {
                keyin = list_spells(true, true, false);
                if (!keyin)
                    keyin = ESCAPE;

                if (!crawl_state.doing_prev_cmd_again)
                {
                    redraw_screen();
                    update_screen();
                }

                if (isaalpha(keyin) || key_is_escape(keyin))
                    break;
                else
                    clear_messages();

                keyin = 0;
            }
            else
                break;
        }

        if (key_is_escape(keyin))
        {
            canned_msg(MSG_OK);
            crawl_state.zero_turns_taken();
            return spret::abort;
        }
        else if (Options.enable_recast_spell
                 && (keyin == '.' || keyin == CK_ENTER))
        {
            spell = you.last_cast_spell;
        }
        else if (!isaalpha(keyin))
        {
            mpr("You don't know that spell.");
            crawl_state.zero_turns_taken();
            return spret::abort;
        }
        else
            spell = get_spell_by_letter(keyin);
    }

    if (spell == SPELL_NO_SPELL)
    {
        mpr("You don't know that spell.");
        crawl_state.zero_turns_taken();
        return spret::abort;
    }

    // MP, confusion, Ru sacs
    const auto reason = casting_uselessness_reason(spell, true);
    if (!reason.empty())
    {
        mpr(reason);
        crawl_state.zero_turns_taken();
        return spret::abort;
    }

    if (check_range && spell_no_hostile_in_range(spell))
    {
        // Abort if there are no hostiles within range, but flash the range
        // markers for a short while.
        mpr("You can't see any susceptible monsters within range! "
            "(Use <w>Z</w> to cast anyway.)");

        if ((Options.use_animations & UA_RANGE) && Options.darken_beyond_range)
        {
            targeter_smite range(&you, spell_range(spell, &you), 0, 0, false, true);
            range_view_annotator show_range(&range);
            delay(50);
        }
        crawl_state.zero_turns_taken();
        return spret::abort;
    }

    if (god_punishes_spell(spell, you.religion)
        && !crawl_state.disables[DIS_CONFIRMATIONS])
    {
        // None currently dock just piety, right?
        if (!yesno("Casting this spell will place you under penance. "
                   "Really cast?", true, 'n'))
        {
            canned_msg(MSG_OK);
            crawl_state.zero_turns_taken();
            return spret::abort;
        }
    }

    you.last_cast_spell = spell;
    // Silently take MP before the spell.
    const int cost = spell_mana(spell);
    pay_mp(cost);

    // Needs to happen after hp costs from HP casting
    const int hp_cost = _spell_addition_hp_cost(spell);
    if (hp_cost)
        pay_hp(hp_cost);

    const spret cast_result = your_spells(spell, 0, !you.divine_exegesis,
                                          nullptr, _target, force_failure);
    if (cast_result == spret::abort
        || you.divine_exegesis && cast_result == spret::fail)
    {
        if (cast_result == spret::abort)
            crawl_state.zero_turns_taken();
        // Return the MP since the spell is aborted.
        refund_mp(cost);
        if (_majin_charge_hp())
            refund_hp(hp_cost);
        if (_death_ego_charge_hp(spell))
            refund_hp(hp_cost);

        redraw_screen();
        update_screen();
        return cast_result;
    }

    practise_casting(spell, cast_result == spret::success);
    _handle_energy_orb(cost, cast_result);
    if (cast_result == spret::success)
    {
        stardust_orb_trigger(cost);
        if (you.unrand_equipped(UNRAND_MAJIN) && one_chance_in(500))
            _majin_speak(spell);
        did_god_conduct(DID_SPELL_CASTING, 1 + random2(5));
        count_action(CACT_CAST, spell);
    }

    finalize_mp_cost(hp_cost > 0);
    // Check if an HP payment brought us low enough
    // to trigger Celebrant or time-warped blood.
    makhleb_celebrant_bloodrite();
    _maybe_blood_hastes_allies();
    you.turn_is_over = true;

    return cast_result;
}

/**
 * Handles divine response to spellcasting.
 *
 * @param spell         The type of spell just cast.
 */
static void _spellcasting_god_conduct(spell_type spell)
{
    // If you are casting while a god is acting, then don't do conducts.
    // (Presumably Xom is forcing you to cast a spell.)
    if (crawl_state.is_god_acting())
        return;

    const int conduct_level = 10 + spell_difficulty(spell);

    if (is_evil_spell(spell) || you.spellcasting_unholy())
        did_god_conduct(DID_EVIL, conduct_level);

    if (is_unclean_spell(spell))
        did_god_conduct(DID_UNCLEAN, conduct_level);

    if (is_chaotic_spell(spell))
        did_god_conduct(DID_CHAOS, conduct_level);

    // not is_hasty_spell since the other ones handle the conduct themselves.
    if (spell == SPELL_SWIFTNESS)
        did_god_conduct(DID_HASTY, conduct_level);
}

/**
 * Handles side effects of successfully casting a spell.
 *
 * Spell noise, magic 'sap' effects, and god conducts.
 *
 * @param spell         The type of spell just cast.
 * @param god           Which god is casting the spell; NO_GOD if it's you.
 * @param fake_spell    true if the spell is evoked or from an innate or divine ability
 *                      false if it is a spell being cast normally.
 */
static void _spellcasting_side_effects(spell_type spell, god_type god,
                                       bool fake_spell)
{
    _spellcasting_god_conduct(spell);

    if (god == GOD_NO_GOD)
    {
        if (you.duration[DUR_SAP_MAGIC] && !fake_spell)
        {
            mprf(MSGCH_WARN, "You lose access to your magic!");
            you.increase_duration(DUR_NO_CAST, 3 + random2(3));
        }

        // Make some noise if it's actually the player casting.
        noisy(spell_noise(spell), you.pos());
    }
}

#ifdef WIZARD
static void _try_monster_cast(spell_type spell, int /*powc*/,
                              dist &spd, bolt &beam)
{
    if (monster_at(you.pos()))
    {
        mpr("Couldn't try casting monster spell because you're "
            "on top of a monster.");
        return;
    }

    monster* mon = get_free_monster();
    if (!mon)
    {
        mpr("Couldn't try casting monster spell because there is "
            "no empty monster slot.");
        return;
    }

    mpr("Invalid player spell, attempting to cast it as monster spell.");

    mon->mname      = "Dummy Monster";
    mon->type       = MONS_HUMAN;
    mon->behaviour  = BEH_SEEK;
    mon->attitude   = ATT_FRIENDLY;
    mon->flags      = (MF_NO_REWARD | MF_JUST_SUMMONED | MF_SEEN
                       | MF_WAS_IN_VIEW | MF_HARD_RESET);
    mon->hit_points = you.hp;
    mon->set_hit_dice(you.experience_level);
    mon->set_position(you.pos());
    mon->target     = spd.target;
    mon->mid        = MID_PLAYER;

    if (!spd.isTarget)
        mon->foe = MHITNOT;
    else if (!monster_at(spd.target))
    {
        if (spd.isMe())
            mon->foe = MHITYOU;
        else
            mon->foe = MHITNOT;
    }
    else
        mon->foe = env.mgrid(spd.target);

    env.mgrid(you.pos()) = mon->mindex();

    mons_cast(mon, beam, spell, MON_SPELL_NO_FLAGS);

    mon->reset();
}
#endif // WIZARD

static spret _do_cast(spell_type spell, int powc, const dist& spd,
                           bolt& beam, god_type god, bool fail,
                           bool actual_spell);

/**
 * Should this spell be aborted before casting properly starts, either because
 * it can't legally be cast in this circumstance, or because the player opts
 * to cancel it in response to a prompt?
 *
 * @param spell         The spell to be checked
 * @param fake_spell    true if the spell is evoked or from an innate or divine ability
 *                      false if it is a spell being cast normally.
 * @return              Whether the spellcasting should be aborted.
 */
static bool _spellcasting_aborted(spell_type spell, bool fake_spell)
{
    string msg;

    // casting-general checks (MP etc) are not carried out here
    msg = spell_uselessness_reason(spell, true, true, true);

    if (!msg.empty())
    {
        mpr(msg);
        return true;
    }

    vector<text_pattern> &actions = Options.confirm_action;
    if (!actions.empty())
    {
        const char* name = spell_title(spell);
        for (const text_pattern &action : actions)
        {
            if (!action.matches(name))
                continue;

            string prompt = "Really cast " + string(name) + "?";
            if (!yesno(prompt.c_str(), false, 'n'))
            {
                canned_msg(MSG_OK);
                return true;
            }
            break;
        }
    }

    const int severity = fail_severity(spell);
    const string failure_rate = spell_failure_rate_string(spell, true);
    if (Options.fail_severity_to_confirm > 0
        && Options.fail_severity_to_confirm <= severity
        && !crawl_state.disables[DIS_CONFIRMATIONS]
        && !fake_spell)
    {
        if (failure_rate_to_int(raw_spell_fail(spell)) == 100)
        {
            mprf(MSGCH_WARN, "It is impossible to cast this spell "
                    "(100%% risk of failure)!");
            return true;
        }

        string prompt = make_stringf("The spell is %s to miscast "
                                     "(%s risk of failure)%s",
                                     fail_severity_adjs[severity],
                                     failure_rate.c_str(),
                                     severity > 1 ? "!" : ".");

        prompt = make_stringf("%s Continue anyway?", prompt.c_str());
        if (!yesno(prompt.c_str(), false, 'n'))
        {
            canned_msg(MSG_OK);
            return true;
        }
    }

    return false;
}

// this is a crude approximation used for the convenience UI targeter of
// Dragon's call and Manifold Assault
static vector<coord_def> _simple_find_all_hostiles()
{
    vector<coord_def> result;
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (!mons_aligned(&you, *mi)
            && mons_is_threatening(**mi)
            && you.can_see(**mi))
        {
            result.push_back((*mi)->pos());
        }
    }

    return result;
}

// TODO: refactor into target.cc, move custom classes out of target.h
unique_ptr<targeter> find_spell_targeter(spell_type spell, int pow, int range)
{
    switch (spell)
    {
    case SPELL_FIREBALL:
    case SPELL_ICEBLAST:
    case SPELL_FASTROOT:
    case SPELL_WARP_SPACE:
        return make_unique<targeter_beam>(&you, range, spell_to_zap(spell), pow,
                                          1, 1);
    case SPELL_HURL_DAMNATION:
        return make_unique<targeter_beam>(&you, range, ZAP_HURL_DAMNATION, pow,
                                          1, 1);
    case SPELL_HURL_TORCHLIGHT:
        return make_unique<targeter_beam>(&you, range, ZAP_HURL_TORCHLIGHT, pow,
                                          1, 1);
    case SPELL_MEPHITIC_CLOUD:
        return make_unique<targeter_beam>(&you, range, ZAP_MEPHITIC, pow,
                                          pow >= 100 ? 1 : 0, 1);
    case SPELL_RUST_BREATH:
        return make_unique<targeter_beam>(&you, 4, ZAP_RUST_BREATH, pow,
                                          pow >= 25 ? 2 : 1, 2);
    case SPELL_FIRE_STORM:
        return make_unique<targeter_smite>(&you, range, 2, pow > 76 ? 3 : 2);
    case SPELL_FREEZING_CLOUD:
        return make_unique<targeter_cloud>(&you, CLOUD_COLD, range);
    case SPELL_THUNDERBOLT:
        return make_unique<targeter_thunderbolt>(&you, range,
                   get_thunderbolt_last_aim(&you));
    case SPELL_LRD:
        return make_unique<targeter_fragment>(&you, pow, range);
    case SPELL_AIRSTRIKE:
        return make_unique<targeter_airstrike>();
    case SPELL_MOMENTUM_STRIKE:
    case SPELL_DIMENSIONAL_BULLSEYE:
        return make_unique<targeter_smite>(&you, range);
    case SPELL_FULMINANT_PRISM:
        return make_unique<targeter_smite>(&you, range, 0, 2);
    case SPELL_GRAVITAS:
        return make_unique<targeter_smite>(&you, range, gravitas_radius(pow),
                                                        gravitas_radius(pow));
    case SPELL_VIOLENT_UNRAVELLING:
        return make_unique<targeter_unravelling>();
    case SPELL_INFESTATION:
        return make_unique<targeter_smite>(&you, range, 2, 2, true, false, true,
                                           [](const coord_def& p) -> bool {
                                              return you.pos() != p; });
    case SPELL_PASSWALL:
        return make_unique<targeter_passwall>(range);
    case SPELL_DIG:
        return make_unique<targeter_dig>(range);
    case SPELL_ELECTRIC_CHARGE:
        return make_unique<targeter_charge>(&you, range);

    // untargeted spells -- everything beyond here is a static targeter
    case SPELL_HAILSTORM:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS, range, 0, 2);
    case SPELL_ISKENDERUNS_MYSTIC_BLAST:
        return make_unique<targeter_radius>(&you, LOS_SOLID_SEE, range, 0, 1);
    case SPELL_STARBURST:
        return make_unique<targeter_starburst>(&you, range, pow);
    case SPELL_IRRADIATE:
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 1, 0, 1);
    case SPELL_DISCHARGE: // not entirely accurate...maybe should highlight
                          // all potentially affected monsters?
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 1);
    case SPELL_ARCJOLT:
        return make_unique<targeter_multiposition>(&you,
                                                   arcjolt_targets(you, false));
    case SPELL_PLASMA_BEAM:
    {
        auto plasma_targets = plasma_beam_targets(you, pow, false);
        auto plasma_paths = plasma_beam_paths(you.pos(), plasma_targets);
        const aff_type a = plasma_targets.size() == 1 ? AFF_YES : AFF_MAYBE;
        return make_unique<targeter_multiposition>(&you, plasma_paths, a);
    }
    case SPELL_PILEDRIVER:
        return make_unique<targeter_piledriver>();
    case SPELL_CHAIN_LIGHTNING:
        return make_unique<targeter_chain_lightning>();
    case SPELL_MAXWELLS_COUPLING:
        return make_unique<targeter_maxwells_coupling>();
    case SPELL_FROZEN_RAMPARTS:
        return make_unique<targeter_walls>(&you, find_ramparts_walls());
    case SPELL_DISPERSAL:
    case SPELL_DISJUNCTION:
    case SPELL_GLOOM:
        return make_unique<targeter_maybe_radius>(&you, LOS_SOLID_SEE, range,
                                                  0, 1);
    case SPELL_INNER_FLAME:
        return make_unique<targeter_inner_flame>(&you, range);
    case SPELL_TELEPORT_OTHER:
        return make_unique<targeter_teleport_other>(&you, range);
    case SPELL_SOUL_SPLINTER:
        return make_unique<targeter_soul_splinter>(&you, range);
    case SPELL_SIMULACRUM:
        return make_unique<targeter_simulacrum>(&you, range);
    case SPELL_LEDAS_LIQUEFACTION:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS,
                                            liquefaction_max_range(pow),
                                            0, 0, 1);
    case SPELL_SILENCE:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS,
                                            silence_max_range(pow),
                                            0, 0,
                                            silence_min_range(pow));
    case SPELL_POISONOUS_VAPOURS:
        return make_unique<targeter_poisonous_vapours>(&you, range);
    case SPELL_MERCURY_ARROW:
        return make_unique<targeter_explosive_beam>(&you, ZAP_MERCURY_ARROW, pow,
                                                    range, true, false);
    case SPELL_GRAVE_CLAW:
        return make_unique<targeter_smite>(&you, range);

    // at player's position only but not a selfench
    case SPELL_SUBLIMATION_OF_BLOOD:
    case SPELL_BORGNJORS_REVIVIFICATION:
    case SPELL_BLASTMOTE:
        return make_unique<targeter_radius>(&you, LOS_SOLID_SEE, 0);

    // LOS radius:
    case SPELL_OZOCUBUS_REFRIGERATION:
        return make_unique<targeter_refrig>(&you);
    case SPELL_OLGREBS_TOXIC_RADIANCE:
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS,
                                                  LOS_RADIUS, 0, 1);
    case SPELL_POLAR_VORTEX:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS,
                                            POLAR_VORTEX_RADIUS, 0, 1);
    case SPELL_SHATTER:
        return make_unique<targeter_shatter>(&you); // special version that
                                                    // affects walls
    case SPELL_IGNITE_POISON: // many cases
        return make_unique<targeter_ignite_poison>(&you);
    case SPELL_CAUSE_FEAR: // for these, we just mark the eligible monsters
        return make_unique<targeter_fear>();
    case SPELL_ANGUISH:
        return make_unique<targeter_anguish>();
    case SPELL_INTOXICATE:
        return make_unique<targeter_intoxicate>();
    case SPELL_ENGLACIATION:
        return make_unique<targeter_englaciate>();
    case SPELL_DRAIN_LIFE:
        return make_unique<targeter_drain_life>();
    case SPELL_DISCORD:
        return make_unique<targeter_discord>();
    case SPELL_IGNITION:
        return make_unique<targeter_multifireball>(&you,
                   get_ignition_blast_sources(&you, true));

    // Summons. Most summons have a simple range 2 radius, see
    // find_newmons_square
    case SPELL_SUMMON_SMALL_MAMMAL:
    case SPELL_AWAKEN_ARMOUR:
    case SPELL_SUMMON_ICE_BEAST:
    case SPELL_SPHINX_SISTERS:
    case SPELL_SUMMON_CACTUS:
    case SPELL_SUMMON_HYDRA:
    case SPELL_SUMMON_MANA_VIPER:
    case SPELL_CONJURE_BALL_LIGHTNING:
    case SPELL_SHADOW_CREATURES: // used for ?summoning
    case SPELL_FORGE_BLAZEHEART_GOLEM:
    case SPELL_CALL_IMP:
    case SPELL_SUMMON_HORRIBLE_THINGS:
    case SPELL_SPELLSPARK_SERVITOR:
    case SPELL_FORGE_LIGHTNING_SPIRE:
    case SPELL_BATTLESPHERE:
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 2, 0, 1);
    case SPELL_SUMMON_SEISMOSAURUS_EGG:
    case SPELL_HOARFROST_CANNONADE:
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 3, 0, 2);
    case SPELL_CALL_CANINE_FAMILIAR:
    {
        const monster* dog = find_canine_familiar();
        if (!dog)
            return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 2, 0, 1);
        vector<coord_def> targ = { dog->pos() };
        return make_unique<targeter_multiposition>(&you, targ);
    }
    case SPELL_SURPRISING_CROCODILE:
        return make_unique<targeter_surprising_crocodile>(&you);
    case SPELL_PLATINUM_PARAGON:
    {
        const monster* paragon = find_player_paragon();
        if (!paragon)
            return make_unique<targeter_paragon_deploy>(range);
        else if (paragon_charge_level(*paragon) == 2)
            return make_unique<targeter_smite>(paragon, 3, 3, 3, true, false, false);
        else
            return make_unique<targeter_smite>(paragon, 3, 2, 2, true, false, false);
    }
    case SPELL_MONARCH_BOMB:
    {
        if (count_summons(&you, SPELL_MONARCH_BOMB) > 1)
            return make_unique<targeter_multiposition>(&you, get_monarch_detonation_spots(you), AFF_YES);
        else
            return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 2, 0, 1);
    }
    case SPELL_FOXFIRE:
        return make_unique<targeter_maybe_radius>(&you, LOS_NO_TRANS, 1, 0, 1);

    case SPELL_MALIGN_GATEWAY:
        return make_unique<targeter_malign_gateway>(you);

    // TODO: this actually has pretty wtf positioning that uses compass
    // directions, so this targeter is not entirely accurate.
    case SPELL_SUMMON_FOREST:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS, LOS_RADIUS,
                                            0, 2);

    case SPELL_BLINK:
        return make_unique<targeter_multiposition>(&you, find_blink_targets());
    case SPELL_MANIFOLD_ASSAULT:
        return make_unique<targeter_multiposition>(&you,
                                                   _simple_find_all_hostiles());
    case SPELL_SCORCH:
        return make_unique<targeter_scorch>(you, range, false);
    case SPELL_DRAGON_CALL: // this is just convenience: you can start the spell
                            // with no enemies in sight
        return make_unique<targeter_multifireball>(&you,
                                                   _simple_find_all_hostiles());
    case SPELL_NOXIOUS_BOG:
        return make_unique<targeter_bog>(&you);
    case SPELL_FLAME_WAVE:
        return make_unique<targeter_flame_wave>(range);
    case SPELL_GOLUBRIAS_PASSAGE:
        return make_unique<targeter_passage>(range);
    case SPELL_SIGIL_OF_BINDING:
        return make_unique<targeter_multiposition>(&you,
                                                   find_sigil_locations(true));
    case SPELL_BOULDER:
        return make_unique<targeter_boulder>(&you, barrelling_boulder_hp(pow));
    case SPELL_PERMAFROST_ERUPTION:
        return make_unique<targeter_permafrost>(you);
    case SPELL_PETRIFY:
        return make_unique<targeter_chain>(&you, range, ZAP_PETRIFY);
    case SPELL_RIMEBLIGHT:
        return make_unique<targeter_chain>(&you, range, ZAP_RIMEBLIGHT);
    case SPELL_COMBUSTION_BREATH:
        return make_unique<targeter_explosive_beam>(&you, ZAP_COMBUSTION_BREATH, pow, range);
    case SPELL_NOXIOUS_BREATH:
        // Note the threshold where it becomes possible to make clouds off the main beam
        return make_unique<targeter_explosive_beam>(&you, ZAP_NOXIOUS_BREATH,
                                                    pow, range, false, pow > 10);
    case SPELL_GALVANIC_BREATH:
        return make_unique<targeter_galvanic>(&you, pow, range);
    case SPELL_NULLIFYING_BREATH:
        return make_unique<targeter_beam>(&you, range, ZAP_NULLIFYING_BREATH, pow,
                                          2, 2);
    case SPELL_GELLS_GAVOTTE:
        return make_unique<targeter_gavotte>(&you);

    case SPELL_MAGNAVOLT:
        return make_unique<targeter_magnavolt>(&you, range);

    case SPELL_HELLFIRE_MORTAR:
        return make_unique<targeter_mortar>(&you, range);

    case SPELL_PUTREFACTION:
        return make_unique<targeter_putrefaction>(range);

    case SPELL_DIAMOND_SAWBLADES:
        return make_unique<targeter_multiposition>(&you,
                                                   diamond_sawblade_spots(false));

    case SPELL_SPLINTERFROST_SHELL:
        return make_unique<targeter_wall_arc>(&you, 4);

    case SPELL_PERCUSSIVE_TEMPERING:
        return make_unique<targeter_tempering>();

    case SPELL_FORTRESS_BLAST:
        return make_unique<targeter_radius>(&you, LOS_NO_TRANS, range);

    case SPELL_SPIKE_LAUNCHER:
    {
        vector<coord_def> walls = find_spike_launcher_walls();
        return make_unique<targeter_multiposition>(&you, walls, walls.size() > 1
                                                                    ? AFF_MAYBE
                                                                    : AFF_YES);
    }

    default:
        break;
    }

    if (spell_to_zap(spell) != NUM_ZAPS)
    {
        return make_unique<targeter_beam>(&you, range, spell_to_zap(spell),
                                          pow, 0, 0);
    }

    // selfench is used mainly for monster AI, so it is a bit over-applied in
    // the spell data
    if (get_spell_flags(spell) & spflag::selfench
        && !spell_typematch(spell, spschool::translocation)) // blink, passage
    {
        return make_unique<targeter_radius>(&you, LOS_SOLID_SEE, 0);
    }

    return nullptr;
}

bool spell_has_targeter(spell_type spell)
{
    return bool(find_spell_targeter(spell, 1, 1));
}

// Returns the nth triangular number.
static int _triangular_number(int n)
{
    return n * (n+1) / 2;
}

// _tetrahedral_number: returns the nth tetrahedral number.
// This is the number of triples of nonnegative integers with sum < n.
static int _tetrahedral_number(int n)
{
    return n * (n+1) * (n+2) / 6;
}

/**
 * Compute success chance for WL-checking spells and abilities.
 *
 * @param wl The willpower of the target.
 * @param powc The enchantment power.
 * @param scale The denominator of the result.
 * @param round_up Should the resulting chance be rounded up (true) or
 *        down (false, the default)?
 *
 * @return The chance, out of scale, that the enchantment affects the target.
 */
int hex_success_chance(const int wl, int powc, int scale, bool round_up)
{
    const int pow = ench_power_stepdown(powc);
    const int target = wl + 100 - pow;
    const int denom = 101 * 100;
    const int adjust = round_up ? denom - 1 : 0;

    if (target <= 0)
        return scale;
    if (target > 200)
        return 0;
    if (target <= 100)
        return (scale * (denom - _triangular_number(target)) + adjust) / denom;
    return (scale * _triangular_number(201 - target) + adjust) / denom;
}

// approximates _test_beam_hit in a deterministic fashion.
static int _to_hit_pct(const monster_info& mi, int acc)
{
    if (acc == AUTOMATIC_HIT)
        return 100;

    acc += mi.lighting_modifiers();
    if (acc <= 1)
        return mi.ev <= 2 ? 100 : 0;

    const int base_ev = mi.ev + (mi.is(MB_DEFLECT_MSL) ? DEFLECT_MISSILES_EV_BONUS : 0);

    int hits = 0;
    int iters = 0;
    for (int outer_ev_roll = 0; outer_ev_roll < base_ev; outer_ev_roll++)
    {
        for (int inner_ev_roll_a = 0; inner_ev_roll_a < outer_ev_roll; inner_ev_roll_a++)
        {
            for (int inner_ev_roll_b = 0; inner_ev_roll_b < outer_ev_roll; inner_ev_roll_b++)
            {
                const int ev = (inner_ev_roll_a + inner_ev_roll_b) / 2; // not right but close
                for (int rolled_mhit = 0; rolled_mhit < acc; rolled_mhit++)
                {
                    iters++;
                    if (iters >= 1000000)
                        return -1; // sanity breakout to not kill servers
                    if (rolled_mhit >= ev)
                        hits++;
                }
            }
        }
    }

    int base_chance = 0;
    if (iters <= 0) // probably low monster ev?
        base_chance = 100;
    else
        base_chance = hits * 100 / iters;

    base_chance = base_chance * (100 - player_blind_miss_chance(you.pos().distance_from(mi.pos))) / 100;
    return base_chance;
}

static vector<string> _desc_hit_chance(const monster_info& mi, int acc)
{
    if (!acc)
        return vector<string>{};
    const int hit_pct = _to_hit_pct(mi, acc);
    if (hit_pct == -1)
        return vector<string>{};

    ostringstream result;
    describe_hit_chance(hit_pct, result, nullptr, false,
                        you.pos().distance_from(mi.pos));
    return vector<string>{result.str()};
}

vector<string> desc_beam_hit_chance(const monster_info& mi, targeter* hitfunc)
{
    targeter_beam* beam_hitf = dynamic_cast<targeter_beam*>(hitfunc);
    if (!beam_hitf)
        return vector<string>{};
    return _desc_hit_chance(mi, beam_hitf->beam.hit);
}

static vector<string> _desc_plasma_hit_chance(const monster_info& mi, int powc)
{
    bolt beam;
    zappy(spell_to_zap(SPELL_PLASMA_BEAM), powc, false, beam);
    const int hit_pct = _to_hit_pct(mi, beam.hit);
    if (hit_pct == -1)
        return vector<string>{};

    ostringstream result;
    describe_hit_chance(hit_pct, result, nullptr, false,
                        you.pos().distance_from(mi.pos));
    return vector<string>{make_stringf("2x%s", result.str().c_str())};
}

static vector<string> _desc_intoxicate_chance(const monster_info& mi,
                                              targeter* hitfunc, int pow)
{
    if (hitfunc && !hitfunc->affects_monster(mi))
        return vector<string>{"not susceptible"};

    int conf_pct = 40 + pow / 3;

    if (get_resist(mi.resists(), MR_RES_POISON) >= 1)
        conf_pct =  conf_pct / 3;

    return vector<string>{make_stringf("chance to confuse: %d%%", conf_pct)};
}

static vector<string> _desc_englaciate_chance(const monster_info& mi,
                                              targeter* hitfunc, int pow)
{
    if (hitfunc && !hitfunc->affects_monster(mi))
        return vector<string>{"not susceptible"};

    const int outcomes = pow * pow * pow;
    const int target   = 3 * mi.hd - 2;
    int fail_pct;

    // Tetrahedral number calculation to find the chance
    // 3 d pow < 3 * mi . hd + 1
    if (target <= pow)
        fail_pct = 100 * _tetrahedral_number(target) / outcomes;
    else if (target <= 2 * pow)
    {
        fail_pct = 100 * (_tetrahedral_number(target)
                       - 3 * _tetrahedral_number(target - pow)) / outcomes;
    }
    else if (target <= 3 * pow)
    {
        fail_pct = 100 * (outcomes
                       - _tetrahedral_number(3 * pow - target)) / outcomes;
    }
    else
        fail_pct = 100;

    return vector<string>{make_stringf("chance to slow: %d%%", 100 - fail_pct)};
}

static vector<string> _desc_gloom_chance(const monster_info& mi, int pow)
{
    if (mons_res_blind(mi.type))
        return vector<string>{"not susceptible"};

    return vector<string>{make_stringf("chance to dazzle: %d%%", gloom_success_chance(pow, mi.hd))};
}

static vector<string> _desc_airstrike_bonus(const monster_info& mi)
{
    const int empty_spaces = airstrike_space_around(mi.pos, false);
    return vector<string>{make_stringf("empty space bonus: %d/8", empty_spaces)};
}

static vector<string> _desc_mercury_weak_chance(const monster_info& mi)
{
    if (mi.is(MB_NO_ATTACKS))
        return vector<string>{};

    return vector<string>{make_stringf("chance to weaken: %d%%",
                            get_mercury_weaken_chance(mi.hd))};
}

static vector<string> _desc_warp_space_chance(int pow)
{
    return vector<string>{make_stringf("chance to blink: %d%%",
                            get_warp_space_chance(pow))};
}

static vector<string> _desc_meph_chance(const monster_info& mi)
{
    if (get_resist(mi.resists(), MR_RES_POISON) >= 1 || mi.is(MB_CLARITY))
        return vector<string>{"not susceptible"};

    int pct_chance = 2;
    if (mi.hd < MEPH_HD_CAP)
        pct_chance = 100 - (100 * mi.hd / MEPH_HD_CAP);
    return vector<string>{make_stringf("chance to affect: %d%%", pct_chance)};
}

static vector<string> _desc_hailstorm_hit_chance(const monster_info& mi, int pow)
{
    bolt beam;
    zappy(ZAP_HAILSTORM, pow, false, beam);
    return _desc_hit_chance(mi, beam.hit);
}

static vector<string> _desc_momentum_strike_hit_chance(const monster_info& mi, int pow)
{
    bolt beam;
    zappy(ZAP_MOMENTUM_STRIKE, pow, false, beam);
    return _desc_hit_chance(mi, beam.hit);
}

static vector<string> _desc_electric_charge_hit_chance(const monster_info& mi)
{
    melee_attack attk(&you, nullptr);
    attk.charge_pow = 1; // to give the accuracy bonus

    vector<string> desc;
    ostringstream result;
    // Pass in our own attack and specify distance 1 so we get correct to-hit
    // for where the attack *will* be from
    describe_to_hit(mi, result, nullptr, false, &attk, 1);
    desc.emplace_back(result.str());
    return desc;
}

static vector<string> _desc_insubstantial(const monster_info& mi, string desc)
{
    if (mons_class_flag(mi.type, M_INSUBSTANTIAL))
        return vector<string>{desc};

    return vector<string>{};
}

static vector<string> _desc_vampiric_draining_valid(const monster_info& mi)
{
    if (mi.mb.get(MB_CANT_DRAIN))
        return vector<string>{"not susceptible"};

    return vector<string>{};
}

static vector<string> _desc_rimeblight_valid(const monster_info& mi)
{
    if (mi.is(MB_RIMEBLIGHT))
        return vector<string>{"already infected"};
    else if (mons_class_is_peripheral(mi.type))
        return vector<string>{"not susceptible"};

    return vector<string>{};
}

static vector<string> _desc_dispersal_chance(const monster_info& mi, int pow)
{
    const int wl = mi.willpower();
    if (mons_class_is_stationary(mi.type))
        return vector<string>{"stationary"};

    if (wl == WILL_INVULN)
        return vector<string>{"will blink"};

    const int success = hex_success_chance(wl, pow, 100);
    return vector<string>{make_stringf("chance to teleport: %d%%", success)};
}

static vector<string> _desc_enfeeble_chance(const monster_info& mi, int pow)
{
    vector<string> base_effects;
    vector<string> all_effects;
    const int wl = mi.willpower();

    if (!mi.is(MB_NO_ATTACKS))
        base_effects.push_back("inflict weakness");
    if (mi.antimagic_susceptible())
        base_effects.push_back("diminish spells");
    if (!base_effects.empty())
    {
        all_effects.push_back("will " +
            comma_separated_line(base_effects.begin(), base_effects.end()));
    }
    if (wl != WILL_INVULN)
    {
        const int success = hex_success_chance(wl, pow, 100);
        all_effects.push_back(make_stringf("chance to daze and blind: %d%%", success));
    }

    if (all_effects.empty())
        return vector<string>{"not susceptible"};

    return all_effects;
}

static string _mon_threat_string(const CrawlStoreValue &mon_store)
{
    monster dummy;
    dummy.type = static_cast<monster_type>(mon_store.get_int());
    define_monster(dummy);

    int col;
    string desc;
    monster_info(&dummy).to_string(1, desc, col, true, nullptr, false);

    // Ghost demons need their underlying monster name. Without this,
    // we'll get e.g. a specific ugly thing colour based on what the
    // dummy monster rolled, which may not match what the actual monster
    // rolls.
    if (mons_is_ghost_demon(dummy.type))
        desc = get_monster_data(dummy.type)->name;

    const string col_name = colour_to_str(col);

    return "<" + col_name + ">" + article_a(desc) + "</" + col_name + ">";
}

// Include success chance in targeter for spells checking monster WL.
vector<string> desc_wl_success_chance(const monster_info& mi, int pow,
                                      targeter* hitfunc)
{
    targeter_beam* beam_hitf = dynamic_cast<targeter_beam*>(hitfunc);
    int wl = mi.willpower();
    if (wl == WILL_INVULN)
        return vector<string>{"infinite will"};
    if (hitfunc && !hitfunc->affects_monster(mi))
        return vector<string>{"not susceptible"};
    wl = apply_willpower_bypass(you, wl);
    vector<string> descs;
    if (beam_hitf && beam_hitf->beam.flavour == BEAM_POLYMORPH)
    {
        // Polymorph has a special effect on ugly things and shapeshifters that
        // does not require passing an WL check.
        if (mi.type == MONS_UGLY_THING || mi.type == MONS_VERY_UGLY_THING)
            return vector<string>{"will change colour"};
        if (mi.is(MB_SHAPESHIFTER))
            return vector<string>{"will change shape"};
        if (mi.type == MONS_SLIME_CREATURE && mi.slime_size > 1)
            descs.push_back("will probably split");

        // list out the normal poly set
        if (!mi.props.exists(POLY_SET_KEY))
            return vector<string>{"not susceptible"};
        const CrawlVector &set = mi.props[POLY_SET_KEY].get_vector();
        if (set.size() <= 0)
            return vector<string>{"not susceptible"};
        descs.push_back("will become "
                        + comma_separated_fn(set.begin(), set.end(),
                                             _mon_threat_string, ", or "));
    }

    const int success = hex_success_chance(wl, pow, 100);
    descs.push_back(make_stringf("chance to affect: %d%%", success));

    return descs;
}

static vector<string> _desc_beckoning_valid(const monster_info& mi)
{
    if (!can_beckon(mi))
        return vector<string>{"not susceptible"};

    return vector<string>{};
}

class spell_targeting_behaviour : public targeting_behaviour
{
public:
    spell_targeting_behaviour(spell_type _spell)
        : targeting_behaviour(false), spell(_spell),
          err(spell_uselessness_reason(spell, true, false, true))
    {
    }

    bool targeted() override
    {
        return !!(get_spell_flags(spell) & spflag::targeting_mask);
    }

    string get_error() override
    {
        return err;
    }

    // TODO: provide useful errors for specific targets via get_monster_desc?

private:
    spell_type spell;
    string err;
};

// TODO: is there a way for this to be part of targeter objects, or
// direction_chooser itself?
desc_filter targeter_addl_desc(spell_type spell, int powc, spell_flags flags,
                                       targeter *hitfunc)
{
    // Add success chance to targeted spells checking monster WL
    const bool wl_check = testbits(flags, spflag::WL_check)
                          && !testbits(flags, spflag::helpful);
    if (wl_check && spell != SPELL_DISPERSAL)
    {
        const zap_type zap = spell_to_zap(spell);
        const int eff_pow = zap != NUM_ZAPS ? zap_ench_power(zap, powc,
                                                             false)
                                            :
              //XXX: deduplicate this with mass_enchantment?
              spell == SPELL_CAUSE_FEAR
              || spell == SPELL_ANGUISH
              || spell == SPELL_DISCORD ? min(200, ( powc * 3 ) / 2)
                                                  : powc;

        if (spell == SPELL_ENFEEBLE)
            return bind(_desc_enfeeble_chance, placeholders::_1, eff_pow);
        else
            return bind(desc_wl_success_chance, placeholders::_1, eff_pow,
                        hitfunc);
    }
    switch (spell)
    {
        case SPELL_INTOXICATE:
            return bind(_desc_intoxicate_chance, placeholders::_1,
                        hitfunc, powc);
        case SPELL_ENGLACIATION:
            return bind(_desc_englaciate_chance, placeholders::_1,
                        hitfunc, powc);
        case SPELL_GLOOM:
            return bind(_desc_gloom_chance, placeholders::_1, powc);
        case SPELL_MEPHITIC_CLOUD:
        case SPELL_NOXIOUS_BREATH:
            return bind(_desc_meph_chance, placeholders::_1);
        case SPELL_VAMPIRIC_DRAINING:
            return bind(_desc_vampiric_draining_valid, placeholders::_1);
        case SPELL_RIMEBLIGHT:
            return bind(_desc_rimeblight_valid, placeholders::_1);
        case SPELL_STARBURST:
        {
            targeter_starburst* burst_hitf =
                dynamic_cast<targeter_starburst*>(hitfunc);
            if (!burst_hitf)
                break;
            targeter_starburst_beam* beam_hitf = &burst_hitf->beams[0];
            return bind(desc_beam_hit_chance, placeholders::_1, beam_hitf);
        }
        case SPELL_DISPERSAL:
            return bind(_desc_dispersal_chance, placeholders::_1, powc);
        case SPELL_AIRSTRIKE:
            return bind(_desc_airstrike_bonus, placeholders::_1);
        case SPELL_HAILSTORM:
            return bind(_desc_hailstorm_hit_chance, placeholders::_1, powc);
        case SPELL_MOMENTUM_STRIKE:
            return bind(_desc_momentum_strike_hit_chance, placeholders::_1, powc);
        case SPELL_ELECTRIC_CHARGE:
            return bind(_desc_electric_charge_hit_chance, placeholders::_1);
        case SPELL_FASTROOT:
            return bind(_desc_insubstantial, placeholders::_1, "immune to roots");
        case SPELL_STICKY_FLAME:
            return bind(_desc_insubstantial, placeholders::_1, "unstickable");
        case SPELL_PLASMA_BEAM:
            return bind(_desc_plasma_hit_chance, placeholders::_1, powc);
        case SPELL_MERCURY_ARROW:
            return _desc_mercury_weak_chance;
        case SPELL_WARP_SPACE:
            return bind(_desc_warp_space_chance, powc);
        case SPELL_BECKONING:
            return bind(_desc_beckoning_valid, placeholders::_1);
        default:
            break;
    }
    targeter_beam* beam_hitf = dynamic_cast<targeter_beam*>(hitfunc);
    if (beam_hitf && beam_hitf->beam.hit > 0 && !beam_hitf->beam.is_explosion)
        return bind(desc_beam_hit_chance, placeholders::_1, hitfunc);
    return nullptr;
}

/**
 * For the clua api, return the description displayed if targeting a monster
 * with a spell.
 *
 * @param mi     The targeted monster.
 * @param spell  The spell being cast.
 * @return       The displayed string.
 **/
string target_spell_desc(const monster_info& mi, spell_type spell)
{
    int powc = calc_spell_power(spell);
    const int range = spell_range(spell, &you);

    unique_ptr<targeter> hitfunc = find_spell_targeter(spell, powc, range);
    if (!hitfunc)
        return "";

    desc_filter addl_desc = targeter_addl_desc(spell, powc,
                                get_spell_flags(spell), hitfunc.get());
    if (!addl_desc)
        return "";

    vector<string> d = addl_desc(mi);
    return comma_separated_line(d.begin(), d.end());
}

/**
 * Targets and fires player-cast spells & spell-like effects.
 *
 * Not all of these are actually real spells; invocations, decks or misc.
 * effects might also land us here.
 * Others are currently unused or unimplemented.
 *
 * @param spell         The type of spell being cast.
 * @param powc          Spellpower.
 * @param actual_spell  true if it is a spell being cast normally.
 *                      false if the spell is evoked or from an innate or
 *                      divine ability.
 * @param evoked_wand   The wand the spell was evoked from if applicable, or
 *                      nullptr.
 * @param force_failure True if the spell's failure has already been determined
 *                      in advance (for spells being cast via an innate or
 *                      divine ability).
 * @return spret::success if spell is successfully cast for purposes of
 * exercising, spret::fail otherwise, or spret::abort if the player cancelled
 * the casting.
 **/
spret your_spells(spell_type spell, int powc, bool actual_spell,
                  const item_def* const evoked_wand, dist *target,
                  bool force_failure)
{
    ASSERT(!crawl_state.game_is_arena());
    ASSERT(!(actual_spell && evoked_wand));
    ASSERT(!evoked_wand || evoked_wand->base_type == OBJ_WANDS);
    ASSERT(!force_failure || !actual_spell && !evoked_wand);

    const bool wiz_cast = (crawl_state.prev_cmd == CMD_WIZARD && !actual_spell);
    const bool can_enkindle = actual_spell && spell_can_be_enkindled(spell);
    const bool enkindled = can_enkindle && you.duration[DUR_ENKINDLED];

    dist target_local;
    if (!target)
        target = &target_local;
    bolt beam;
    beam.origin_spell = spell;

    // [dshaligram] Any action that depends on the spellcasting attempt to have
    // succeeded must be performed after the switch.
    if (!wiz_cast && _spellcasting_aborted(spell, !actual_spell))
        return spret::abort;

    const spell_flags flags = get_spell_flags(spell);

    if (!powc)
        powc = calc_spell_power(spell);

    const int range = calc_spell_range(spell, powc, actual_spell);
    beam.range = range;

    unique_ptr<targeter> hitfunc = find_spell_targeter(spell, powc, range);
    const bool is_targeted = !!(flags & spflag::targeting_mask);

    const god_type god =
        (crawl_state.is_god_acting()) ? crawl_state.which_god_acting()
                                      : GOD_NO_GOD;

    // XXX: This handles only some of the cases where spells need
    // targeting. There are others that do their own that will be
    // missed by this (and thus will not properly ESC without cost
    // because of it). Hopefully, those will eventually be fixed. - bwr
    // TODO: what's the status of the above comment in 2020+?
    const bool use_targeter = is_targeted
        || !god // Don't allow targeting spells cast by Xom
           && hitfunc
           && (target->fire_context // force static targeters when called in
                                    // "fire" mode
               || Options.always_use_static_spell_targeters
               || Options.force_spell_targeter.count(spell) > 0);

    if (use_targeter)
    {
        const targ_mode_type targ =
              spell == SPELL_PLATINUM_PARAGON           ? TARG_HOSTILE_OR_EMPTY :
              testbits(flags, spflag::aim_at_space)     ? TARG_NON_ACTOR :
              testbits(flags, spflag::helpful)          ? TARG_FRIEND :
              testbits(flags, spflag::obj)              ? TARG_MOVABLE_OBJECT :
                                                          TARG_HOSTILE;

        // TODO: if any other spells ever need this, add an spflag
        // (right now otherwise used only on god abilities)
        const targeting_type dir =
            spell == SPELL_BLINKBOLT ? DIR_ENFORCE_RANGE
            : testbits(flags, spflag::target) ? DIR_ENFORCE_RANGE : DIR_NONE;

        // TODO: it's extremely inconsistent when this prompt shows up, not
        // sure why
        const char *prompt = get_spell_target_prompt(spell);

        const bool needs_path = !testbits(flags, spflag::target)
                                // Apportation must be spflag::target, since a
                                // shift-direction makes no sense for it, but
                                // it nevertheless requires line-of-fire.
                                || spell == SPELL_APPORTATION;

        desc_filter additional_desc
            = targeter_addl_desc(spell, powc, flags, hitfunc.get());

        // `true` on fourth param skips MP check and a few others that have
        // already been carried out
        const bool useless = spell_is_useless(spell, true, false, true);
        const char *spell_title_color = useless ? "darkgrey" : "w";
        const string verb = channelled_spell_active(spell)
            ? "<lightred>Restarting spell</lightred>"
            : is_targeted ? "Aiming" : "Casting";
        string title = make_stringf("%s: <%s>%s</%s>", verb.c_str(),
                    spell_title_color, spell_title(spell), spell_title_color);
        if (actual_spell)
        {
            title += make_stringf(" <lightgrey>(%s)</lightgrey>",
                _spell_failure_rate_description(spell).c_str());
        }

        if (spell == SPELL_GRAVE_CLAW)
        {
            title += make_stringf("<lightgrey> (%d/%d uses available)</lightgrey>",
                                  you.props[GRAVE_CLAW_CHARGES_KEY].get_int(),
                                  GRAVE_CLAW_MAX_CHARGES);
        }

        spell_targeting_behaviour beh(spell);

        direction_chooser_args args;
        args.hitfunc = hitfunc.get();
        args.restricts = dir;
        args.mode = targ;
        args.range = range;
        args.needs_path = needs_path;
        args.target_prefix = prompt;
        args.top_prompt = title;
        args.behaviour = &beh;

        if (testbits(flags, spflag::prefer_farthest))
            args.prefer_farthest = true;

        if (spell == SPELL_SHOCK)
            args.try_multizap = true;

        // if the spell is useless and we have somehow gotten this far, it's
        // a forced cast. Setting this prevents the direction chooser from
        // looking for selecting a default target (which doesn't factor in
        // the spell's capabilities).
        // Also ensure we don't look for a target for static targeters. It might
        // be better to move to an affected position if any?
        if (useless || !is_targeted)
            args.default_place = you.pos();
        if (hitfunc && hitfunc->can_affect_walls())
        {
            args.show_floor_desc = true;
            args.show_boring_feats = false; // don't show "The floor."
        }
        if (testbits(flags, spflag::not_self))
            args.self = confirm_prompt_type::cancel;
        else
            args.self = confirm_prompt_type::none;
        args.get_desc_func = additional_desc;
        if (!spell_direction(*target, beam, &args))
            return spret::abort;

        if (testbits(flags, spflag::not_self) && target->isMe())
        {
            if (spell == SPELL_TELEPORT_OTHER)
                mpr("Sorry, this spell works on others only.");
            else
                canned_msg(MSG_UNTHINKING_ACT);

            return spret::abort;
        }

        if (spell == SPELL_BOMBARD)
        {
            const coord_def back = you.stumble_pos(target->target);
            if (!back.origin()
                && back != you.pos()
                && !check_moveto(back, "potentially stumble back", false))
            {
                return spret::abort;
            }
        }
    }

    if (evoked_wand)
        surge_power_wand(wand_mp_cost());
    else if (actual_spell)
        surge_power(_spell_enhancement(spell));

    int fail = 0;
    if (actual_spell)
    {
        int spfl = random2avg(100, 3);

        if (!you_worship(GOD_SIF_MUNA)
            && you.penance[GOD_SIF_MUNA] && one_chance_in(20))
        {
            god_speaks(GOD_SIF_MUNA, "You feel a surge of divine spite.");

            // This will cause failure and increase the miscast effect.
            spfl = -you.penance[GOD_SIF_MUNA];
        }
        else if (spell_typematch(spell, spschool::necromancy)
                 && !you_worship(GOD_KIKUBAAQUDGHA)
                 && you.penance[GOD_KIKUBAAQUDGHA]
                 && one_chance_in(20))
        {
            // And you thought you'd Haunt your way out of penance...
            simple_god_message(" does not allow the disloyal to dabble in "
                               "death!", false, GOD_KIKUBAAQUDGHA);

            // The spell still goes through, but you get a miscast anyway.
            miscast_effect(you, nullptr,
                           {miscast_source::god, GOD_KIKUBAAQUDGHA},
                           spschool::necromancy,
                           spell_difficulty(spell),
                           you.experience_level,
                           "the malice of Kikubaaqudgha");
        }
        else if (vehumet_supports_spell(spell)
                 && !you_worship(GOD_VEHUMET)
                 && you.penance[GOD_VEHUMET]
                 && one_chance_in(20))
        {
            // And you thought you'd Fire Storm your way out of penance...
            simple_god_message(" does not allow the disloyal to dabble in "
                               "destruction!", false, GOD_VEHUMET);

            // The spell still goes through, but you get a miscast anyway.
            miscast_effect(you, nullptr, {miscast_source::god, GOD_VEHUMET},
                           spschool::conjuration,
                           spell_difficulty(spell),
                           you.experience_level,
                           "the malice of Vehumet");
        }

        const int spfail_chance = raw_spell_fail(spell);

        if (spfl < spfail_chance)
            fail = spfail_chance - spfl;
    }

    dprf("Spell #%d, power=%d", spell, powc);

    const coord_def orig_target_pos = beam.target;

    spret cast_result = _do_cast(spell, powc, *target, beam, god,
                                 force_failure || fail, actual_spell);

    switch (cast_result)
    {
    case spret::success:
    {
        _apply_post_zap_effect(spell, orig_target_pos);

        const int demonic_magic = you.get_mutation_level(MUT_DEMONIC_MAGIC);
        const bool ephemeral_shield = you.get_mutation_level(MUT_EPHEMERAL_SHIELD);

        if ((demonic_magic == 3 && evoked_wand)
            || (demonic_magic > 0 && (actual_spell || you.divine_exegesis)))
        {
            do_demonic_magic(spell_difficulty(spell) * 6, demonic_magic);
        }

        if (ephemeral_shield && (actual_spell || you.divine_exegesis))
        {
            you.set_duration(DUR_EPHEMERAL_SHIELD, 2);
            you.redraw_armour_class = true;
        }

        if (you.props.exists(BATTLESPHERE_KEY)
            && (actual_spell || you.divine_exegesis)
            && battlesphere_can_mirror(spell))
        {
            trigger_battlesphere(&you);
        }

        if (will_have_passive(passive_t::shadow_spells) && actual_spell)
            dithmenos_shadow_spell(spell);
        _spellcasting_side_effects(spell, god, !actual_spell);

        if (you.wearing_ego(OBJ_GIZMOS, SPGIZMO_SPELLMOTOR) && actual_spell)
            coglin_spellmotor_attack();

        // Handle revenant passives
        if (can_enkindle && you.has_mutation(MUT_SPELLCLAWS))
            spellclaws_attack(spell_difficulty(spell));

        if (enkindled && --you.props[ENKINDLE_CHARGES_KEY].get_int() == 0)
            end_enkindled_status();

        return spret::success;
    }
    case spret::fail:
    {
        if (actual_spell)
        {
            mprf("You miscast %s.", spell_title(spell));
            flush_input_buffer(FLUSH_ON_FAILURE);
            learned_something_new(HINT_SPELL_MISCAST);
            miscast_effect(spell, fail);
        }

        return spret::fail;
    }

    case spret::abort:
        return spret::abort;

    case spret::none:
#ifdef WIZARD
        if (you.wizard && !actual_spell && is_valid_spell(spell)
            && (flags & spflag::monster))
        {
            _try_monster_cast(spell, powc, *target, beam);
            return spret::success;
        }
#endif

        if (is_valid_spell(spell))
        {
            mprf(MSGCH_ERROR, "Spell '%s' is not a player castable spell.",
                 spell_title(spell));
        }
        else
            mprf(MSGCH_ERROR, "Invalid spell!");

        return spret::abort;
    }

    return spret::success;
}

// Returns spret::success, spret::abort, spret::fail
// or spret::none (not a player spell).
static spret _do_cast(spell_type spell, int powc, const dist& spd,
                           bolt& beam, god_type god, bool fail,
                           bool actual_spell)
{
    if (actual_spell && !you.wizard
        && (get_spell_flags(spell) & (spflag::monster | spflag::testing)))
    {
        return spret::none;
    }

    const coord_def target = spd.isTarget ? beam.target : you.pos() + spd.delta;
    if (spell == SPELL_FREEZE)
    {
        if (!adjacent(you.pos(), target))
            return spret::abort;
    }

    switch (spell)
    {
    case SPELL_FREEZE:
        return cast_freeze(powc, monster_at(target), fail);

    case SPELL_IOOD:
        return cast_iood(&you, powc, &beam, 0, 0, MHITNOT, fail);

    // Clouds and explosions.
    case SPELL_FREEZING_CLOUD:
        return cast_freezing_cloud(powc, beam, fail);

    case SPELL_FIRE_STORM:
        return cast_fire_storm(powc, beam, fail);

    // Demonspawn ability, no failure.
    case SPELL_CALL_DOWN_DAMNATION:
        return cast_smitey_damnation(powc, beam) ? spret::success : spret::abort;

    // LOS spells
    case SPELL_SMITING:
        return cast_smiting(powc, monster_at(target), fail);

    case SPELL_AIRSTRIKE:
        return cast_airstrike(powc, spd.target, fail);

    case SPELL_MOMENTUM_STRIKE:
        return cast_momentum_strike(powc, spd.target, fail);

    case SPELL_LRD:
        return cast_fragmentation(powc, &you, spd.target, fail);

    case SPELL_GRAVITAS:
        return cast_gravitas(powc, beam.target, fail);

    case SPELL_VIOLENT_UNRAVELLING:
        return cast_unravelling(spd.target, powc, fail);

    // other effects
    case SPELL_DISCHARGE:
        return cast_discharge(powc, you, fail);

    case SPELL_ARCJOLT:
        return cast_arcjolt(powc, you, fail);

    case SPELL_PLASMA_BEAM:
        return cast_plasma_beam(powc, you, fail);

    case SPELL_CHAIN_LIGHTNING:
        return cast_chain_lightning(powc, you, fail);

    case SPELL_DISPERSAL:
        return cast_dispersal(powc, fail);

    case SPELL_SHATTER:
        return cast_shatter(powc, fail);

    case SPELL_SCORCH:
        return cast_scorch(you, powc, fail);

    case SPELL_POISONOUS_VAPOURS:
        return cast_poisonous_vapours(you, powc, target, fail);

    case SPELL_IRRADIATE:
        return cast_irradiate(powc, you, fail);

    case SPELL_LEDAS_LIQUEFACTION:
        return cast_liquefaction(powc, fail);

    case SPELL_OZOCUBUS_REFRIGERATION:
        return fire_los_attack_spell(spell, powc, &you, fail);

    case SPELL_OLGREBS_TOXIC_RADIANCE:
        return cast_toxic_radiance(&you, powc, fail);

    case SPELL_IGNITE_POISON:
        return cast_ignite_poison(&you, powc, fail);

    case SPELL_POLAR_VORTEX:
        return cast_polar_vortex(powc, fail);

    case SPELL_THUNDERBOLT:
        return cast_thunderbolt(&you, powc, target, fail);

    case SPELL_GLOOM:
        return cast_gloom(&you, powc, fail);

    case SPELL_CHAIN_OF_CHAOS:
        return cast_chain_spell(SPELL_CHAIN_OF_CHAOS, powc, &you, fail);

    case SPELL_IGNITION:
        return cast_ignition(&you, powc, fail);

    case SPELL_FROZEN_RAMPARTS:
        return cast_frozen_ramparts(powc, fail);

    // Summoning spells, and other spells that create new monsters.
    case SPELL_SUMMON_SMALL_MAMMAL:
        return cast_summon_small_mammal(powc, fail);

    case SPELL_CALL_CANINE_FAMILIAR:
        return cast_call_canine_familiar(powc, fail);

    case SPELL_AWAKEN_ARMOUR:
        return cast_awaken_armour(powc, fail);

    case SPELL_SUMMON_ICE_BEAST:
        return cast_summon_ice_beast(powc, fail);

    case SPELL_SUMMON_CACTUS:
        return cast_summon_cactus(powc, fail);

    case SPELL_SPHINX_SISTERS:
        return cast_sphinx_sisters(you, powc, fail);;

    case SPELL_SUMMON_DRAGON:
        return cast_summon_dragon(&you, powc, fail);

    case SPELL_DRAGON_CALL:
        return cast_dragon_call(powc, fail);

    case SPELL_SUMMON_HYDRA:
        return cast_summon_hydra(&you, powc, fail);

    case SPELL_SUMMON_MANA_VIPER:
        return cast_summon_mana_viper(powc, fail);

    case SPELL_SUMMON_SEISMOSAURUS_EGG:
        return cast_summon_seismosaurus_egg(you, powc, fail);

    case SPELL_CONJURE_BALL_LIGHTNING:
        return cast_conjure_ball_lightning(powc, fail);

    case SPELL_FORGE_LIGHTNING_SPIRE:
        return cast_forge_lightning_spire(powc, fail);

    case SPELL_FORGE_BLAZEHEART_GOLEM:
        return cast_forge_blazeheart_golem(powc, fail);

    case SPELL_CALL_IMP:
        return cast_call_imp(powc, fail);

    case SPELL_SUMMON_HORRIBLE_THINGS:
        return cast_summon_horrible_things(powc, fail);

    case SPELL_MALIGN_GATEWAY:
        return cast_malign_gateway(&you, powc, fail);

    case SPELL_SUMMON_FOREST:
        return cast_summon_forest(&you, powc, fail);

    case SPELL_ANIMATE_DEAD:
        return cast_animate_dead(powc, fail);

    case SPELL_MARTYRS_KNELL:
        return cast_martyrs_knell(&you, powc, fail);

    case SPELL_HAUNT:
        return cast_haunt(powc, beam.target, fail);

    case SPELL_DEATH_CHANNEL:
        return cast_death_channel(powc, god, fail);

    case SPELL_SPELLSPARK_SERVITOR:
        return cast_spellspark_servitor(powc, fail);

    case SPELL_BATTLESPHERE:
        return cast_battlesphere(&you, powc, fail);

    case SPELL_INFESTATION:
        return cast_infestation(powc, beam, fail);

    case SPELL_FOXFIRE:
        return cast_foxfire(you, powc, fail);

    case SPELL_NOXIOUS_BOG:
        return cast_noxious_bog(powc, fail);

    case SPELL_CLOCKWORK_BEE:
        return cast_clockwork_bee(beam.target, fail);

    case SPELL_SPIKE_LAUNCHER:
        return cast_spike_launcher(powc, fail);

    case SPELL_DIAMOND_SAWBLADES:
        return cast_diamond_sawblades(powc, fail);

    case SPELL_SURPRISING_CROCODILE:
        return cast_surprising_crocodile(you, beam.target, powc, fail);

    case SPELL_PLATINUM_PARAGON:
        return cast_platinum_paragon(beam.target, powc, fail);

    case SPELL_WALKING_ALEMBIC:
        return cast_walking_alembic(you, powc, fail);

    case SPELL_MONARCH_BOMB:
        return cast_monarch_bomb(you, powc, fail);

    case SPELL_SPLINTERFROST_SHELL:
        return cast_splinterfrost_shell(you, beam.target, powc, fail);

    case SPELL_PERCUSSIVE_TEMPERING:
        return cast_percussive_tempering(you, *monster_at(beam.target), powc, fail);

    case SPELL_FORTRESS_BLAST:
        return cast_fortress_blast(you, powc, fail);

    case SPELL_PHALANX_BEETLE:
        return cast_phalanx_beetle(you, powc, fail);

    case SPELL_RENDING_BLADE:
        return cast_rending_blade(powc, fail);

    // Enchantments.
    case SPELL_CONFUSING_TOUCH:
        return cast_confusing_touch(powc, fail);

    case SPELL_CAUSE_FEAR:
        return mass_enchantment(ENCH_FEAR, powc, fail);

    case SPELL_ANGUISH:
        return mass_enchantment(ENCH_ANGUISH, powc, fail);

    case SPELL_INTOXICATE:
        return cast_intoxicate(powc, fail);

    case SPELL_DISCORD:
        return mass_enchantment(ENCH_FRENZIED, powc, fail);

    case SPELL_ENGLACIATION:
        return cast_englaciation(powc, fail);

    case SPELL_BORGNJORS_VILE_CLUTCH:
        return cast_vile_clutch(powc, beam, fail);

    case SPELL_PUTREFACTION:
        return cast_putrefaction(monster_at(target), powc, fail);

    // Our few remaining self-enchantments.
    case SPELL_SWIFTNESS:
        return cast_swiftness(powc, fail);

    case SPELL_OZOCUBUS_ARMOUR:
        return ice_armour(powc, fail);

    case SPELL_SILENCE:
        return cast_silence(powc, fail);

    case SPELL_FUGUE_OF_THE_FALLEN:
        return cast_fugue_of_the_fallen(powc, fail);

    case SPELL_DIMENSIONAL_BULLSEYE:
        return cast_dimensional_bullseye(powc, monster_at(target), fail);

    case SPELL_DETONATION_CATALYST:
        return cast_detonation_catalyst(fail);

    // other
    case SPELL_BORGNJORS_REVIVIFICATION:
        return cast_revivification(powc, fail);

    case SPELL_SUBLIMATION_OF_BLOOD:
        return cast_sublimation_of_blood(powc, fail);

    case SPELL_DEATHS_DOOR:
        return cast_deaths_door(powc, fail);

    // Escape spells.
    case SPELL_BLINK:
        return cast_blink(powc, fail);

    case SPELL_BLASTMOTE:
        return kindle_blastmotes(powc, fail);

    case SPELL_PASSWALL:
        return cast_passwall(beam.target, powc, fail);

    case SPELL_APPORTATION:
        return cast_apportation(powc, beam, fail);

    case SPELL_DISJUNCTION:
        return cast_disjunction(powc, fail);

    case SPELL_MANIFOLD_ASSAULT:
        return cast_manifold_assault(you, powc, fail);

    case SPELL_GOLUBRIAS_PASSAGE:
        return cast_golubrias_passage(powc, beam.target, fail);

    case SPELL_FULMINANT_PRISM:
        return cast_fulminating_prism(&you, powc, beam.target, fail);

    case SPELL_SEARING_RAY:
        return cast_searing_ray(you, powc, beam, fail);

    case SPELL_FLAME_WAVE:
        return cast_flame_wave(powc, fail);

    case SPELL_INNER_FLAME:
        return cast_inner_flame(spd.target, powc, fail);

    case SPELL_TELEPORT_OTHER:
        return cast_teleport_other(spd.target, powc, fail);

    case SPELL_SIMULACRUM:
        return cast_simulacrum(spd.target, powc, fail);

    case SPELL_GRAVE_CLAW:
        return cast_grave_claw(you, spd.target, powc, fail);

    case SPELL_BLINKBOLT:
        return blinkbolt(powc, beam, fail);

    case SPELL_ELECTRIC_CHARGE:
        return electric_charge(you, powc, fail, beam.target);

    case SPELL_STARBURST:
        return cast_starburst(powc, fail);

    case SPELL_HAILSTORM:
        return cast_hailstorm(powc, fail);

    case SPELL_MAXWELLS_COUPLING:
        return cast_maxwells_coupling(powc, fail);

    case SPELL_ISKENDERUNS_MYSTIC_BLAST:
        return cast_imb(powc, fail);

    case SPELL_JINXBITE:
        return cast_jinxbite(powc, fail);

    case SPELL_SIGIL_OF_BINDING:
        return cast_sigil_of_binding(powc, fail, false);

    case SPELL_BOULDER:
        return cast_broms_barrelling_boulder(you, beam.target, powc, fail);

    case SPELL_PERMAFROST_ERUPTION:
        return cast_permafrost_eruption(you, powc, fail);

    case SPELL_PILEDRIVER:
        return cast_piledriver(beam.target, powc, fail);

    // Just to do extra messaging; spell is handled by default zapping
    case SPELL_COMBUSTION_BREATH:
    case SPELL_GLACIAL_BREATH:
    case SPELL_STEAM_BREATH:
    case SPELL_CAUSTIC_BREATH:
    case SPELL_MUD_BREATH:
    case SPELL_NULLIFYING_BREATH:
    case SPELL_NOXIOUS_BREATH:
    {
        static map<spell_type, string> breath_message =
        {
            { SPELL_COMBUSTION_BREATH, "You breathe a blast of explosive embers." },
            { SPELL_GLACIAL_BREATH, "You exhale a wave of glacial cold." },
            { SPELL_STEAM_BREATH, "You exhale a blast of scalding steam." },
            { SPELL_NULLIFYING_BREATH, "You breathe a sphere of nullifying energy." },
            { SPELL_NOXIOUS_BREATH, "You exhale a blast of noxious fumes." },
            { SPELL_CAUSTIC_BREATH, "You breathe a spray of caustic vapour." },
            { SPELL_MUD_BREATH, "You spew a torrent of mud." },
            { SPELL_GALVANIC_BREATH, "You breathe wild lightning."}
        };

        if (!fail)
            mpr(breath_message[spell].c_str());
    }
    break;

    case SPELL_GOLDEN_BREATH:
        return cast_golden_breath(beam, powc, fail);

    case SPELL_GELLS_GAVOTTE:
        return cast_gavotte(powc, beam.target - you.pos(), fail);

    case SPELL_MAGNAVOLT:
        return cast_magnavolt(beam.target, powc, fail);

    case SPELL_FULSOME_FUSILLADE:
        return cast_fulsome_fusillade(powc, fail);

    case SPELL_HOARFROST_CANNONADE:
        return cast_hoarfrost_cannonade(you, powc, fail);

    case SPELL_HELLFIRE_MORTAR:
        return cast_hellfire_mortar(you, beam, powc, fail);

    default:
        if (spell_removed(spell))
        {
            mprf("Sorry, the spell '%s' is gone!", spell_title(spell));
            return spret::abort;
        }
        break;
    }

    // Finally, try zaps.
    zap_type zap = spell_to_zap(spell);
    if (zap != NUM_ZAPS)
        return zapping(zap, powc,  beam, true, nullptr, fail);

    return spret::none;
}

// get_true_fail_rate: Takes the raw failure to-beat number
// and converts it to the actual chance of failure:
// the probability that random2avg(100,3) < raw_fail.
// Should probably use more constants, though I doubt the spell
// success algorithms will really change *that* much.
// Called only by failure_rate_to_int
static double _get_true_fail_rate(int raw_fail)
{
    // Need 3*random2avg(100,3) = random2(101) + random2(101) + random2(100)
    // to be (strictly) less than 3*raw_fail. Fun with tetrahedral numbers!

    // How many possible outcomes, considering all three dice?
    const int outcomes = 101 * 101 * 100;
    const int target = raw_fail * 3;

    if (target <= 100)
    {
        // The failures are exactly the triples of nonnegative integers
        // that sum to < target.
        return double(_tetrahedral_number(target)) / outcomes;
    }
    if (target <= 200)
    {
        // Some of the triples that sum to < target would have numbers
        // greater than 100, or a last number greater than 99, so aren't
        // possible outcomes. Apply the principle of inclusion-exclusion
        // by subtracting out these cases. The set of triples with first
        // number > 100 is isomorphic to the set of triples that sum to
        // 101 less; likewise for the second and third numbers (100 less
        // in the last case). Two or more out-of-range numbers would have
        // resulted in a sum of at least 201, so there is no overlap
        // among the three cases we are subtracting.
        return double(_tetrahedral_number(target)
                      - 2 * _tetrahedral_number(target - 101)
                      - _tetrahedral_number(target - 100)) / outcomes;
    }
    // The random2avg distribution is symmetric, so the last interval is
    // essentially the same as the first interval.
    return double(outcomes - _tetrahedral_number(300 - target)) / outcomes;
}

const double fail_hp_fraction[] =
{
    .10,
    .30,
    .50,
    .70,
};
/**
 * Compute the maximum miscast damage from the given spell
 *
 * The miscast code uses
 *     dam = div_rand_round(roll_dice(level, level + raw_fail), MISCAST_DIVISOR)
 */
int max_miscast_damage(spell_type spell)
{
    int raw_fail = raw_spell_fail(spell);
    int level = spell_difficulty(spell);

    // Impossible to get a damaging miscast
    if (level * level * raw_fail <= MISCAST_THRESHOLD)
        return 0;

    return div_round_up(level * (raw_fail + level), MISCAST_DIVISOR);
}


/**
 * Compute the tier of maximum severity of a miscast
 * @param spell     The spell to be checked.
 *
 * Tiers are defined by the relation between the maximum miscast damage
 * (given a miscast occurs):
 *
 * - safe, no chance of dangerous effect
 * - slightly dangerous, mdam <= 10% mhp
 * - dangerous, mdam <= 30% mhp
 * - quite dangerous, mdam <= 50% mhp
 * - extremely dangerous, mdam <= 70% mhp
 * - potentially lethal, higher mdam
 */
int fail_severity(spell_type spell)
{
    const int raw_fail = raw_spell_fail(spell);
    const int level = spell_difficulty(spell);

    // Impossible to get a damaging miscast
    if (level * level * raw_fail <= MISCAST_THRESHOLD)
        return 0;

    const int max_damage = max_miscast_damage(spell);

    for (int i = 0; i < 4; ++i)
        if (max_damage <= fail_hp_fraction[i] * get_real_hp(true))
            return i + 1;

    return 5;
}

const char *fail_severity_adjs[] =
{
    "safe",
    "mildly dangerous",
    "dangerous",
    "quite dangerous",
    "extremely dangerous",
    "astonishingly dangerous",
};
COMPILE_CHECK(ARRAYSZ(fail_severity_adjs) > 3);

// Chooses a colour for the failure rate display for a spell. The colour is
// based on the chance of getting a severity >= 2 miscast.
int failure_rate_colour(spell_type spell)
{
    const int severity = fail_severity(spell);
    return severity == 0 ? LIGHTGREY :
           severity == 1 ? WHITE :
           severity == 2 ? YELLOW :
           severity == 3 ? LIGHTRED :
           severity == 4 ? RED
                         : MAGENTA;
}

//Converts the raw failure rate into a number to be displayed.
int failure_rate_to_int(int fail)
{
    if (fail <= 0)
        return 0;
    else if (fail >= 100)
        return (fail + 100)/2;
    else
        return max(1, (int) (100 * _get_true_fail_rate(fail)));
}

/**
 * Convert the given failure rate into a percent, and return it as a string.
 *
 * @param fail      A raw failure rate (not a percent!)
 * @return          E.g. "79%".
 */
string failure_rate_to_string(int fail)
{
    return make_stringf("%d%%", failure_rate_to_int(fail));
}

string spell_failure_rate_string(spell_type spell, bool terse)
{
    const bool enkindled = you.duration[DUR_ENKINDLED] && spell_can_be_enkindled(spell);
    const string colour = colour_to_str(failure_rate_colour(spell));

    if (terse || !you.has_mutation(MUT_MNEMOPHAGE) || !spell_can_be_enkindled(spell))
    {
        const string failure = failure_rate_to_string(raw_spell_fail(spell));
        return make_stringf("<%s>%s</%s>",
                colour.c_str(), failure.c_str(), colour.c_str());
    }

    const int normal_fail = failure_rate_to_int(raw_spell_fail(spell));
    const int enkindled_fail = failure_rate_to_int(raw_spell_fail(spell, true));

    if (enkindled)
    {
        return make_stringf("<lightcyan>*</lightcyan><%s>%d%%</%s><lightcyan>*</lightcyan>",
                                colour.c_str(), enkindled_fail, colour.c_str());
    }
    else
    {
        return make_stringf("<%s>%d%%</%s><darkgrey> (%d%%)</darkgrey>",
            colour.c_str(), normal_fail, colour.c_str(), enkindled_fail);
    }
}

static string _spell_failure_rate_description(spell_type spell)
{
    const string failure = failure_rate_to_string(raw_spell_fail(spell));
    const char *severity_adj = fail_severity_adjs[fail_severity(spell)];
    const string colour = colour_to_str(failure_rate_colour(spell));
    const char *col = colour.c_str();

    return make_stringf("<%s>%s</%s>; <%s>%s</%s> risk of failure",
            col, severity_adj, col, col, failure.c_str(), col);
}

string spell_noise_string(spell_type spell, int chop_wiz_display_width)
{
    const int casting_noise = spell_noise(spell);
    int effect_noise = spell_effect_noise(spell);

    // A typical amount of noise.
    if (spell == SPELL_POLAR_VORTEX)
        effect_noise = 15;

    const int noise = max(casting_noise, effect_noise);

    const char* noise_descriptions[] =
    {
        "Silent", "Almost silent", "Quiet", "A bit loud", "Loud", "Very loud",
        "Extremely loud", "Deafening"
    };

    const int breakpoints[] = { 1, 2, 4, 8, 15, 20, 30 };
    COMPILE_CHECK(ARRAYSZ(noise_descriptions) == 1 + ARRAYSZ(breakpoints));

    const char* desc = noise_descriptions[breakpoint_rank(noise, breakpoints,
                                                ARRAYSZ(breakpoints))];

#ifdef WIZARD
    if (you.wizard)
    {
        if (chop_wiz_display_width > 0)
        {
            ostringstream shortdesc;
            shortdesc << chop_string(desc, chop_wiz_display_width)
                      << "(" << to_string(noise) << ")";
            return shortdesc.str();
        }
        else
            return make_stringf("%s (%d)", desc, noise);
    }
    else
#endif
        return desc;
}

int power_to_barcount(int power)
{
    if (power == -1)
        return -1;

    const int breakpoints[] = { 10, 15, 25, 35, 50, 75, 100, 150, 200 };
    return breakpoint_rank(power, breakpoints, ARRAYSZ(breakpoints)) + 1;
}

#ifdef WIZARD
static string _wizard_spell_power_numeric_string(spell_type spell)
{
    const int cap = spell_power_cap(spell);
    if (cap == 0)
        return "N/A";
    const int power = min(calc_spell_power(spell), cap);
    return make_stringf("%d (%d)", power, cap);
}
#endif

// TODO: deduplicate with the same-named function in describe-spells.cc
static dice_def _spell_damage(spell_type spell, int power)
{
    if (power < 0)
        return dice_def(0,0);
    switch (spell)
    {
        case SPELL_FULMINANT_PRISM:
            return prism_damage(prism_hd(power, false), true);
        case SPELL_CONJURE_BALL_LIGHTNING:
            return ball_lightning_damage(ball_lightning_hd(power, false), false);
        case SPELL_IOOD:
            return iood_damage(power, INFINITE_DISTANCE, false);
        case SPELL_IRRADIATE:
            return irradiate_damage(power, false);
        case SPELL_SHATTER:
            return shatter_damage(power);
        case SPELL_SCORCH:
            return scorch_damage(power, false);
        case SPELL_BATTLESPHERE:
            return battlesphere_damage_from_power(power);
        case SPELL_FROZEN_RAMPARTS:
            return ramparts_damage(power, false);
        case SPELL_LRD:
            return base_fragmentation_damage(power, false);
        case SPELL_ARCJOLT:
            return arcjolt_damage(power, false);
        case SPELL_POLAR_VORTEX:
            return polar_vortex_dice(power, false);
        case SPELL_NOXIOUS_BOG:
            return toxic_bog_damage();
        case SPELL_BOULDER:
            return boulder_damage(power, false);
        case SPELL_THUNDERBOLT:
            return thunderbolt_damage(power, 1);
        case SPELL_HELLFIRE_MORTAR:
            return hellfire_mortar_damage(power);
        case SPELL_FORGE_LIGHTNING_SPIRE:
            return lightning_spire_damage(power);
        case SPELL_DIAMOND_SAWBLADES:
            return diamond_sawblade_damage(power);
        case SPELL_FORTRESS_BLAST:
            return fortress_blast_damage(you.armour_class_scaled(1), false);
        case SPELL_POISONOUS_VAPOURS:
            return poisonous_vapours_damage(power, false);
        case SPELL_DETONATION_CATALYST:
            return detonation_catalyst_damage(power, false);
        case SPELL_JINXBITE:
            return jinxbite_damage(power,false);
        default:
            break;
    }
    const zap_type zap = spell_to_zap(spell);
    if (zap == NUM_ZAPS)
        return dice_def(0,0);
    return zap_damage(zap, power, false, false);
}

string spell_max_damage_string(spell_type spell)
{
    switch (spell)
    {
    case SPELL_MAXWELLS_COUPLING:
    case SPELL_FREEZING_CLOUD:
        // These have damage strings, but don't scale with power.
        return "";
    case SPELL_FORTRESS_BLAST:
    {
        // Fortress Blast's damage scales with AC, not spellpower, and thus
        // exceeds the normal spellpower cap.
        dice_def dmg = zap_damage(ZAP_FORTRESS_BLAST, 200, false);
        return make_stringf("%dd%d", dmg.num, dmg.size);
    }
    default:
        break;
    }
    // Only show a distinct max damage string if we're not at max power
    // already. Otherwise, it's redundant!
    const int pow = calc_spell_power(spell);
    const int max_pow = spell_power_cap(spell);
    if (pow >= max_pow)
        return "";
    return spell_damage_string(spell, false, max_pow);
}

string spell_damage_string(spell_type spell, bool evoked, int pow, bool terse)
{
    if (pow == -1)
        pow = evoked ? wand_power(spell) : calc_spell_power(spell);
    switch (spell)
    {
        case SPELL_MAXWELLS_COUPLING:
            return Options.char_set == CSET_ASCII ? "death" : "\u221e"; //"∞"
        case SPELL_FREEZING_CLOUD:
            return desc_cloud_damage(CLOUD_COLD, false);
        case SPELL_DISCHARGE:
        {
            const int max = discharge_max_damage(pow);
            return make_stringf("%d-%d/arc", FLAT_DISCHARGE_ARC_DAMAGE, max);
        }
        case SPELL_AIRSTRIKE:
            return describe_player_airstrike_dam(base_airstrike_damage(pow));
        case SPELL_PILEDRIVER:
            return make_stringf("(3-9)d%d", piledriver_collision_damage(pow, 1, false).size);
        case SPELL_GELLS_GAVOTTE:
            return make_stringf("2d(%d-%d)", gavotte_impact_damage(pow, 1, false).size,
                                             gavotte_impact_damage(pow, 4, false).size);

        case SPELL_FULSOME_FUSILLADE:
            return make_stringf("(3-5)d%d", _spell_damage(spell, pow).size);
        case SPELL_RIMEBLIGHT:
            return describe_rimeblight_damage(pow, terse);
        case SPELL_HOARFROST_CANNONADE:
        {
            dice_def shot_dam = hoarfrost_cannonade_damage(pow, false);
            dice_def finale_dam = hoarfrost_cannonade_damage(pow, true);

            return make_stringf("%dd%d/%dd%d",
                shot_dam.num, shot_dam.size, finale_dam.num, finale_dam.size);
        }
        case SPELL_RENDING_BLADE:
        {
            dice_def dmg_mp = rending_blade_damage(pow, true);
            dice_def dmg = rending_blade_damage(pow, false);
            const int bonus = dmg_mp.size - dmg.size;
            if (bonus > 0)
                return make_stringf("%dd(%d+%d*)", dmg.num, dmg.size, bonus);
            else
                return make_stringf("%dd%d", dmg.num, dmg.size);
        }
        default:
            break;
    }
    const dice_def dam = _spell_damage(spell, pow);
    if (dam.num == 0 || dam.size == 0)
        return "";
    string mult = "";
    switch (spell)
    {
        case SPELL_FOXFIRE:
        case SPELL_PLASMA_BEAM:
        case SPELL_PERMAFROST_ERUPTION:
            mult = "2x";
            break;
        case SPELL_CONJURE_BALL_LIGHTNING:
            mult = "3x";
            break;
        case SPELL_TREMORSTONE:
            mult = make_stringf("%dx", tremorstone_count(pow));
        default:
            break;
    }
    const string dam_str = make_stringf("%s%dd%d", mult.c_str(), dam.num,
            dam.size);

    if (spell == SPELL_ISKENDERUNS_MYSTIC_BLAST)
    {
        if (terse)
            return dam_str + "+";
        else
            return make_stringf("%s (+%s)",
                dam_str.c_str(),
                describe_collision_dam(default_collision_damage(pow, false)).c_str());
    }

    if (spell == SPELL_LRD
        || spell == SPELL_SHATTER
        || spell == SPELL_POLAR_VORTEX)
    {
        return dam_str + "*"; // many special cases of more/less damage
    }
    return dam_str;
}

int spell_acc(spell_type spell)
{
    const zap_type zap = spell_to_zap(spell);
    if (zap == NUM_ZAPS)
        return -1;
    if (zap_explodes(zap) || zap_is_enchantment(zap))
        return -1;
    const int power = calc_spell_power(spell);
    if (power < 0)
        return -1;
    const int acc = zap_to_hit(zap, power, false);
    if (acc == AUTOMATIC_HIT)
        return -1;
    return acc;
}

int spell_power_percent(spell_type spell)
{
    const int pow = calc_spell_power(spell);
    const int max_pow = spell_power_cap(spell);
    if (max_pow == 0)
        return -1; // should never happen for player spells
    return pow * 100 / max_pow;
}

string spell_power_string(spell_type spell)
{
#ifdef WIZARD
    if (you.wizard)
        return _wizard_spell_power_numeric_string(spell);
#endif

    const int percent = spell_power_percent(spell);
    if (percent < 0)
        return "N/A";
    else
        return make_stringf("%d%%", percent);
}

/**
 * Give a string describing a given spell's range, as cast by the player.
 *
 * @param spell     The spell in question.
 * @return          See above.
 */
string spell_range_string(spell_type spell)
{
    const int range    = spell_range(spell, &you, -1, true);
    const int maxrange = spell_has_variable_range(spell)
                            ? calc_spell_range(spell, spell_power_cap(spell), true, true)
                            : -1;

    return range_string(range, maxrange, spell == SPELL_HAILSTORM ? 2 : 0);
}

/**
 * Give a string describing a given spell's range.
 *
 * For spells with variable range, will be written in the form of 'X/Y' where X
 * is the current range and Y is the maximum range.
 *
 * For spells with a minimum range (ie: Call Down Lightning), will be written in
 * the form of 'X-Y' where X is the minimal effective range.
 *
 * @param range         The current range of the spell.
 * @param maxrange      The range the spell would have at max power.
 *                      -1 if the spell does not have variable range.
 * @param minrange      The minimal range at which the spell is castable.
 * @return              See above.
 */
string range_string(int range, int maxrange, int minrange)
{
    if (range <= 0)
        return "N/A";

    string ret = to_string(range);
    if (maxrange > -1)
        ret += "/" + to_string(maxrange);
    if (minrange > 0)
        ret = to_string(minrange) + "-" + ret;

    return ret;
}

string spell_schools_string(spell_type spell)
{
    string desc;

    bool already = false;
    for (const auto bit : spschools_type::range())
    {
        if (spell_typematch(spell, bit))
        {
            if (already)
                desc += "/";
            desc += spelltype_long_name(bit);
            already = true;
        }
    }

    return desc;
}

void spell_skills(spell_type spell, set<skill_type> &skills)
{
    const spschools_type disciplines = get_spell_disciplines(spell);
    for (const auto bit : spschools_type::range())
        if (disciplines & bit)
            skills.insert(spell_type2skill(bit));
}

void do_demonic_magic(int pow, int rank)
{
    if (rank < 1)
        return;

    mpr("Malevolent energies surge around you.");

    for (radius_iterator ri(you.pos(), rank, C_SQUARE, LOS_NO_TRANS, true); ri; ++ri)
    {
        monster *mons = monster_at(*ri);

        if (!mons || mons->wont_attack() || !mons_is_threatening(*mons))
            continue;

        if (mons->check_willpower(&you, pow) <= 0)
            mons->paralyse(&you, random_range(2, 5));
    }
}

bool channelled_spell_active(spell_type spell)
{
    return you.attribute[ATTR_CHANNELLED_SPELL] == spell;
}

void start_channelling_spell(spell_type spell, string reminder_msg, bool do_effect)
{
    you.attribute[ATTR_CHANNELLED_SPELL] = spell;
    you.attribute[ATTR_CHANNEL_DURATION] = -1;

    if (do_effect)
        handle_channelled_spell();
    else
        you.attribute[ATTR_CHANNEL_DURATION] = 0;

    if (!reminder_msg.empty())
    {
        string msg = "(Press <w>%</w> to " + reminder_msg + ".)";
        insert_commands(msg, { CMD_WAIT });
        mpr(msg);
    }
}

void handle_channelled_spell()
{
    if (you.attribute[ATTR_CHANNELLED_SPELL] == SPELL_NO_SPELL)
        return;

    // Skip processing at the end of the turn this is cast (since that already
    // happened *as* it was cast and shouldn't happen a second time.)
    if (++you.attribute[ATTR_CHANNEL_DURATION] == 1)
        return;

    const spell_type spell = (spell_type)you.attribute[ATTR_CHANNELLED_SPELL];

    // This value is -1 at the moment the spell is started. 0 is 'skipped' as
    // the end of the turn it is started. 1+ represents subsequent turns.
    const int turn = (you.attribute[ATTR_CHANNEL_DURATION] == 0 ? 1
                        : you.attribute[ATTR_CHANNEL_DURATION]);

    // Don't stop on non-wait for the first turn of a channelled spell, since
    // that was the turn we cast it on.
    if (turn > 1 && crawl_state.prev_cmd != CMD_WAIT || !can_cast_spells(true))
    {
        stop_channelling_spells();
        return;
    }

    if ((spell == SPELL_FLAME_WAVE || spell == SPELL_SEARING_RAY)
        && turn > 1 && !enough_mp(1, true))
    {
        mprf("Without enough magic to sustain it, your %s dissipates.",
             spell_title(spell));
        stop_channelling_spells(true);
        return;
    }

    switch (you.attribute[ATTR_CHANNELLED_SPELL])
    {
        case SPELL_MAXWELLS_COUPLING:
            handle_maxwells_coupling();
            return;

        case SPELL_FLAME_WAVE:
            handle_flame_wave(turn);
            return;

        case SPELL_SEARING_RAY:
            handle_searing_ray(you, turn);
            return;

        case SPELL_CLOCKWORK_BEE:
            handle_clockwork_bee_spell(turn);
            return;

        default:
            mprf(MSGCH_WARN, "Attempting to channel buggy spell: %s", spell_title(spell));
    }
}

void stop_channelling_spells(bool quiet)
{
    const spell_type spell = (spell_type)you.attribute[ATTR_CHANNELLED_SPELL];

    you.attribute[ATTR_CHANNELLED_SPELL] = 0;
    you.attribute[ATTR_CHANNEL_DURATION] = 0;

    if (quiet)
        return;

    switch (spell)
    {
        case SPELL_FLAME_WAVE:
            mpr("You stop channelling waves of flame.");
            break;

        case SPELL_SEARING_RAY:
            mpr("You stop channelling your searing ray.");
            break;

        case SPELL_MAXWELLS_COUPLING:
            mpr("The insufficient charge dissipates harmlessly.");
            break;

        case SPELL_CLOCKWORK_BEE:
            mpr("You stop assembling your clockwork bee.");
            break;

        default:
            break;
    }
}

// Prompts the player when casting a spell like Irradiate, while having enough
// contam that it could push them into yellow.
//
// Returns true if we should abort.
bool warn_about_contam_cost(int max_contam)
{
    if (!Options.warn_contam_cost || you.magic_contamination >= 1000)
        return false;

    const int mul = you.has_mutation(MUT_CONTAMINATION_SUSCEPTIBLE) ? 2 : 1;

    if (you.magic_contamination + (max_contam * mul) >= 1000)
        return !yesno("Casting this now could dangerously contaminate you. Continue?", true, 'n');

    return false;
}