1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
#![allow(non_local_definitions)] // because of WidgetCommon derive
mod animation;
mod bag;
mod buffs;
mod buttons;
mod change_notification;
mod chat;
mod crafting;
mod diary;
mod esc_menu;
mod group;
mod hotbar;
mod loot_scroller;
mod map;
mod minimap;
mod overhead;
mod overitem;
mod popup;
mod prompt_dialog;
mod quest;
mod settings_window;
mod skillbar;
mod slots;
mod social;
mod subtitles;
mod trade;

pub mod img_ids;
pub mod item_imgs;
pub mod util;

pub use crafting::CraftingTab;
pub use hotbar::{SlotContents as HotbarSlotContents, State as HotbarState};
pub use item_imgs::animate_by_pulse;
pub use loot_scroller::LootMessage;
pub use settings_window::ScaleChange;
pub use subtitles::Subtitle;

use bag::Bag;
use buffs::BuffsBar;
use buttons::Buttons;
use change_notification::{ChangeNotification, NotificationReason};
use chat::Chat;
use chrono::NaiveTime;
use crafting::Crafting;
use diary::{Diary, SelectedSkillTree};
use esc_menu::EscMenu;
use group::Group;
use img_ids::Imgs;
use item_imgs::ItemImgs;
use loot_scroller::LootScroller;
use map::Map;
use minimap::{MiniMap, VoxelMinimap};
use popup::Popup;
use prompt_dialog::PromptDialog;
use quest::Quest;
use serde::{Deserialize, Serialize};
use settings_window::{SettingsTab, SettingsWindow};
use skillbar::Skillbar;
use social::Social;
use subtitles::Subtitles;
use trade::Trade;

use crate::{
    audio::ActiveChannels,
    cmd::get_player_uuid,
    ecs::comp::{self as vcomp, HpFloater, HpFloaterList},
    game_input::GameInput,
    hud::{img_ids::ImgsRot, prompt_dialog::DialogOutcomeEvent},
    render::UiDrawer,
    scene::camera::{self, Camera},
    session::{
        interactable::{BlockInteraction, Interactable},
        settings_change::{
            Audio, Chat as ChatChange, Interface as InterfaceChange, SettingsChange,
        },
    },
    settings::chat::ChatFilter,
    ui::{
        fonts::Fonts,
        img_ids::Rotations,
        slot::{self, SlotKey},
        Graphic, Ingameable, ScaleMode, Ui,
    },
    window::Event as WinEvent,
    GlobalState,
};
use client::Client;
use common::{
    combat,
    comp::{
        self,
        ability::{AuxiliaryAbility, Stance},
        fluid_dynamics,
        inventory::{
            slot::{InvSlotId, Slot},
            trade_pricing::TradePricing,
            CollectFailedReason,
        },
        item::{
            tool::{AbilityContext, ToolKind},
            ItemDefinitionIdOwned, ItemDesc, ItemI18n, MaterialStatManifest, Quality,
        },
        loot_owner::LootOwnerKind,
        pet::is_mountable,
        skillset::{skills::Skill, SkillGroupKind, SkillsPersistenceError},
        BuffData, BuffKind, Content, Health, Item, MapMarkerChange, PickupItem, PresenceKind,
    },
    consts::MAX_PICKUP_RANGE,
    link::Is,
    mounting::{Mount, Rider, VolumePos},
    outcome::Outcome,
    recipe::RecipeBookManifest,
    resources::{ProgramTime, Secs, Time},
    slowjob::SlowJobPool,
    terrain::{SpriteKind, TerrainChunk, UnlockKind},
    trade::{ReducedInventory, TradeAction},
    uid::Uid,
    util::{srgba_to_linear, Dir},
    vol::RectRasterableVol,
};
use common_base::{prof_span, span};
use common_net::{
    msg::{world_msg::SiteId, Notification},
    sync::WorldSyncExt,
};
use conrod_core::{
    text::cursor::Index,
    widget::{self, Button, Image, Rectangle, Text},
    widget_ids, Color, Colorable, Labelable, Positionable, Sizeable, Widget,
};
use hashbrown::{HashMap, HashSet};
use i18n::Localization;
use rand::Rng;
use specs::{Entity as EcsEntity, Join, LendJoin, WorldExt};
use std::{
    borrow::Cow,
    cmp::Ordering,
    collections::VecDeque,
    sync::Arc,
    time::{Duration, Instant},
};
use tracing::warn;
use vek::*;

const TEXT_COLOR: Color = Color::Rgba(1.0, 1.0, 1.0, 1.0);
const TEXT_VELORITE: Color = Color::Rgba(0.0, 0.66, 0.66, 1.0);
const TEXT_BLUE_COLOR: Color = Color::Rgba(0.8, 0.9, 1.0, 1.0);
const TEXT_GRAY_COLOR: Color = Color::Rgba(0.5, 0.5, 0.5, 1.0);
const TEXT_DULL_RED_COLOR: Color = Color::Rgba(0.56, 0.2, 0.2, 1.0);
const TEXT_BG: Color = Color::Rgba(0.0, 0.0, 0.0, 1.0);
const TEXT_COLOR_GREY: Color = Color::Rgba(1.0, 1.0, 1.0, 0.5);
//const TEXT_COLOR_2: Color = Color::Rgba(0.0, 0.0, 0.0, 1.0);
const TEXT_COLOR_3: Color = Color::Rgba(1.0, 1.0, 1.0, 0.1);
const TEXT_BIND_CONFLICT_COLOR: Color = Color::Rgba(1.0, 0.0, 0.0, 1.0);
const BLACK: Color = Color::Rgba(0.0, 0.0, 0.0, 1.0);
//const BG_COLOR: Color = Color::Rgba(1.0, 1.0, 1.0, 0.8);
const HP_COLOR: Color = Color::Rgba(0.33, 0.63, 0.0, 1.0);
const LOW_HP_COLOR: Color = Color::Rgba(0.93, 0.59, 0.03, 1.0);
const CRITICAL_HP_COLOR: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0);
const STAMINA_COLOR: Color = Color::Rgba(0.29, 0.62, 0.75, 0.9);
const ENEMY_HP_COLOR: Color = Color::Rgba(0.93, 0.1, 0.29, 1.0);
const XP_COLOR: Color = Color::Rgba(0.59, 0.41, 0.67, 1.0);
const POISE_COLOR: Color = Color::Rgba(0.70, 0.0, 0.60, 1.0);
const POISEBAR_TICK_COLOR: Color = Color::Rgba(0.70, 0.90, 0.0, 1.0);
//const TRANSPARENT: Color = Color::Rgba(0.0, 0.0, 0.0, 0.0);
//const FOCUS_COLOR: Color = Color::Rgba(1.0, 0.56, 0.04, 1.0);
//const RAGE_COLOR: Color = Color::Rgba(0.5, 0.04, 0.13, 1.0);
const BUFF_COLOR: Color = Color::Rgba(0.06, 0.69, 0.12, 1.0);
const DEBUFF_COLOR: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0);

// Item Quality Colors
const QUALITY_LOW: Color = Color::Rgba(0.60, 0.60, 0.60, 1.0); // Grey - Trash, can be sold to vendors
const QUALITY_COMMON: Color = Color::Rgba(0.79, 1.00, 1.00, 1.0); // Light blue - Crafting mats, food, starting equipment, quest items (like keys), rewards for easy quests
const QUALITY_MODERATE: Color = Color::Rgba(0.06, 0.69, 0.12, 1.0); // Green - Quest Rewards, commonly looted items from NPCs
const QUALITY_HIGH: Color = Color::Rgba(0.18, 0.32, 0.9, 1.0); // Blue - Dungeon rewards, boss loot, rewards for hard quests
const QUALITY_EPIC: Color = Color::Rgba(0.58, 0.29, 0.93, 1.0); // Purple - Rewards for epic quests and very hard bosses
const QUALITY_LEGENDARY: Color = Color::Rgba(0.92, 0.76, 0.0, 1.0); // Gold - Legendary items that require a big effort to acquire
const QUALITY_ARTIFACT: Color = Color::Rgba(0.74, 0.24, 0.11, 1.0); // Orange - Not obtainable by normal means, "artifacts"
const QUALITY_DEBUG: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0); // Red - Admin and debug items

// Chat Colors
/// Color for chat command errors (yellow !)
const ERROR_COLOR: Color = Color::Rgba(1.0, 1.0, 0.0, 1.0);
/// Color for chat command info (blue i)
const INFO_COLOR: Color = Color::Rgba(0.28, 0.83, 0.71, 1.0);
/// Online color
const ONLINE_COLOR: Color = Color::Rgba(0.3, 1.0, 0.3, 1.0);
/// Offline color
const OFFLINE_COLOR: Color = Color::Rgba(1.0, 0.3, 0.3, 1.0);
/// Color for a private message from another player
const TELL_COLOR: Color = Color::Rgba(0.98, 0.71, 1.0, 1.0);
/// Color for local chat
const SAY_COLOR: Color = Color::Rgba(1.0, 0.8, 0.8, 1.0);
/// Color for group chat
const GROUP_COLOR: Color = Color::Rgba(0.47, 0.84, 1.0, 1.0);
/// Color for factional chat
const FACTION_COLOR: Color = Color::Rgba(0.24, 1.0, 0.48, 1.0);
/// Color for regional chat
const REGION_COLOR: Color = Color::Rgba(0.8, 1.0, 0.8, 1.0);
/// Color for death messagesw
const KILL_COLOR: Color = Color::Rgba(1.0, 0.17, 0.17, 1.0);
/// Color for global messages
const WORLD_COLOR: Color = Color::Rgba(0.95, 1.0, 0.95, 1.0);

//Nametags
const GROUP_MEMBER: Color = Color::Rgba(0.47, 0.84, 1.0, 1.0);
const DEFAULT_NPC: Color = Color::Rgba(1.0, 1.0, 1.0, 1.0);

// UI Color-Theme
const UI_MAIN: Color = Color::Rgba(0.61, 0.70, 0.70, 1.0); // Greenish Blue
const UI_SUBTLE: Color = Color::Rgba(0.2, 0.24, 0.24, 1.0); // Dark Greenish Blue
//const UI_MAIN: Color = Color::Rgba(0.1, 0.1, 0.1, 0.97); // Dark
const UI_HIGHLIGHT_0: Color = Color::Rgba(0.79, 1.09, 1.09, 1.0);
// Pull-Down menu BG color
const MENU_BG: Color = Color::Rgba(0.1, 0.12, 0.12, 1.0);
//const UI_DARK_0: Color = Color::Rgba(0.25, 0.37, 0.37, 1.0);

/// Distance at which nametags are visible for group members
const NAMETAG_GROUP_RANGE: f32 = 1000.0;
/// Distance at which nametags are visible
const NAMETAG_RANGE: f32 = 40.0;
/// Time nametags stay visible after doing damage even if they are out of range
/// in seconds
const NAMETAG_DMG_TIME: f32 = 60.0;
/// Range damaged triggered nametags can be seen
const NAMETAG_DMG_RANGE: f32 = 120.0;
/// Range to display speech-bubbles at
const SPEECH_BUBBLE_RANGE: f32 = NAMETAG_RANGE;
const EXP_FLOATER_LIFETIME: f32 = 2.0;
const EXP_ACCUMULATION_DURATION: f32 = 0.5;

// TODO: Don't hard code this
pub fn default_water_color() -> Rgba<f32> { srgba_to_linear(Rgba::new(0.0, 0.18, 0.37, 1.0)) }

widget_ids! {
    struct Ids {
        // Crosshair
        crosshair_inner,
        crosshair_outer,

        // SCT
        player_scts[],
        player_sct_bgs[],
        player_rank_up,
        player_rank_up_txt_number,
        player_rank_up_txt_0,
        player_rank_up_txt_0_bg,
        player_rank_up_txt_1,
        player_rank_up_txt_1_bg,
        player_rank_up_icon,
        sct_exp_bgs[],
        sct_exps[],
        sct_exp_icons[],
        sct_lvl_bg,
        sct_lvl,
        hurt_bg,
        death_bg,
        sct_bgs[],
        scts[],

        overheads[],
        overitems[],

        // Alpha Disclaimer
        alpha_text,

        // Debug
        debug_bg,
        fps_counter,
        ping,
        coordinates,
        velocity,
        glide_ratio,
        glide_aoe,
        air_vel,
        orientation,
        look_direction,
        loaded_distance,
        time,
        entity_count,
        num_chunks,
        num_lights,
        num_figures,
        num_particles,
        current_biome,
        current_site,
        graphics_backend,
        gpu_timings[],
        weather,
        song_info,
        active_channels,

        // Game Version
        version,

        // Help
        help,
        help_info,
        debug_info,
        lantern_info,

        // Window Frames
        window_frame_0,
        window_frame_1,
        window_frame_2,
        window_frame_3,
        window_frame_4,
        window_frame_5,

        button_help2,
        button_help3,

        // External
        chat,
        loot_scroller,
        map,
        world_map,
        character_window,
        popup,
        minimap,
        prompt_dialog,
        bag,
        trade,
        social,
        quest,
        diary,
        skillbar,
        buttons,
        buffs,
        esc_menu,
        small_window,
        social_window,
        quest_window,
        crafting_window,
        settings_window,
        group_window,
        item_info,
        subtitles,

        // Free look indicator
        free_look_txt,
        free_look_bg,

        // Auto walk indicator
        auto_walk_txt,
        auto_walk_bg,

        // Walking speed indicator
        walking_speed_txt,
        walking_speed_bg,

        // Temporal (fading) camera zoom lock indicator
        zoom_lock_txt,
        zoom_lock_bg,

        // Camera clamp indicator
        camera_clamp_txt,
        camera_clamp_bg,

        // Tutorial
        quest_bg,
        q_headline_bg,
        q_headline,
        q_text_bg,
        q_text,
        accept_button,
        intro_button,
        tut_arrow,
        tut_arrow_txt_bg,
        tut_arrow_txt,
    }
}

/// Specifier to use with `Position::position`
/// Read its documentation for more
// TODO: extend as you need it
#[derive(Clone, Copy)]
pub enum PositionSpecifier {
    // Place the widget near other widget with the given margins
    TopLeftWithMarginsOn(widget::Id, f64, f64),
    TopRightWithMarginsOn(widget::Id, f64, f64),
    MidBottomWithMarginOn(widget::Id, f64),
    BottomLeftWithMarginsOn(widget::Id, f64, f64),
    BottomRightWithMarginsOn(widget::Id, f64, f64),
    // Place the widget near other widget with given margin
    MidTopWithMarginOn(widget::Id, f64),
    // Place the widget near other widget at given distance
    MiddleOf(widget::Id),
    UpFrom(widget::Id, f64),
    DownFrom(widget::Id, f64),
    LeftFrom(widget::Id, f64),
    RightFrom(widget::Id, f64),
}

/// Trait which enables you to declare widget position
/// to use later on widget creation.
/// It is implemented for all widgets which are implement Positionable,
/// so you can easily change your code to use this method.
///
/// Consider this example:
/// ```text
///     let slot1 = slot_maker
///         .fabricate(hotbar::Slot::One, [40.0; 2])
///         .filled_slot(self.imgs.skillbar_slot)
///         .bottom_left_with_margins_on(state.ids.frame, 0.0, 0.0);
///     if condition {
///         call_slot1(slot1);
///     } else {
///         call_slot2(slot1);
///     }
///     let slot2 = slot_maker
///         .fabricate(hotbar::Slot::Two, [40.0; 2])
///         .filled_slot(self.imgs.skillbar_slot)
///         .right_from(state.ids.slot1, slot_offset);
///     if condition {
///         call_slot1(slot2);
///     } else {
///         call_slot2(slot2);
///     }
/// ```
/// Despite being identical, you can't easily deduplicate code
/// which uses slot1 and slot2 as they are calling methods to position itself.
/// This can be solved if you declare position and use it later like so
/// ```text
/// let slots = [
///     (hotbar::Slot::One, BottomLeftWithMarginsOn(state.ids.frame, 0.0, 0.0)),
///     (hotbar::Slot::Two, RightFrom(state.ids.slot1, slot_offset)),
/// ];
/// for (slot, pos) in slots {
///     let slot = slot_maker
///         .fabricate(slot, [40.0; 2])
///         .filled_slot(self.imgs.skillbar_slot)
///         .position(pos);
///     if condition {
///         call_slot1(slot);
///     } else {
///         call_slot2(slot);
///     }
/// }
/// ```
pub trait Position {
    #[must_use]
    fn position(self, request: PositionSpecifier) -> Self;
}

impl<W: Positionable> Position for W {
    fn position(self, request: PositionSpecifier) -> Self {
        match request {
            // Place the widget near other widget with the given margins
            PositionSpecifier::TopLeftWithMarginsOn(other, top, left) => {
                self.top_left_with_margins_on(other, top, left)
            },
            PositionSpecifier::TopRightWithMarginsOn(other, top, right) => {
                self.top_right_with_margins_on(other, top, right)
            },
            PositionSpecifier::MidBottomWithMarginOn(other, margin) => {
                self.mid_bottom_with_margin_on(other, margin)
            },
            PositionSpecifier::BottomRightWithMarginsOn(other, bottom, right) => {
                self.bottom_right_with_margins_on(other, bottom, right)
            },
            PositionSpecifier::BottomLeftWithMarginsOn(other, bottom, left) => {
                self.bottom_left_with_margins_on(other, bottom, left)
            },
            // Place the widget near other widget with given margin
            PositionSpecifier::MidTopWithMarginOn(other, margin) => {
                self.mid_top_with_margin_on(other, margin)
            },
            // Place the widget near other widget at given distance
            PositionSpecifier::MiddleOf(other) => self.middle_of(other),
            PositionSpecifier::UpFrom(other, offset) => self.up_from(other, offset),
            PositionSpecifier::DownFrom(other, offset) => self.down_from(other, offset),
            PositionSpecifier::LeftFrom(other, offset) => self.left_from(other, offset),
            PositionSpecifier::RightFrom(other, offset) => self.right_from(other, offset),
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum BuffIconKind {
    Buff {
        kind: BuffKind,
        data: BuffData,
        multiplicity: usize,
    },
    Stance(Stance),
}

impl BuffIconKind {
    pub fn image(&self, imgs: &Imgs) -> conrod_core::image::Id {
        match self {
            Self::Buff { kind, .. } => get_buff_image(*kind, imgs),
            Self::Stance(stance) => util::ability_image(imgs, stance.pseudo_ability_id()),
        }
    }

    pub fn max_duration(&self) -> Option<Secs> {
        match self {
            Self::Buff { data, .. } => data.duration,
            Self::Stance(_) => None,
        }
    }

    pub fn title_description<'b>(
        &self,
        localized_strings: &'b Localization,
    ) -> (Cow<'b, str>, Cow<'b, str>) {
        match self {
            Self::Buff {
                kind,
                data,
                multiplicity: _,
            } => (
                util::get_buff_title(*kind, localized_strings),
                util::get_buff_desc(*kind, *data, localized_strings),
            ),
            Self::Stance(stance) => {
                util::ability_description(stance.pseudo_ability_id(), localized_strings)
            },
        }
    }
}

impl PartialOrd for BuffIconKind {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}

impl Ord for BuffIconKind {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (
                BuffIconKind::Buff { kind, .. },
                BuffIconKind::Buff {
                    kind: other_kind, ..
                },
            ) => kind.cmp(other_kind),
            (BuffIconKind::Buff { .. }, BuffIconKind::Stance(_)) => Ordering::Greater,
            (BuffIconKind::Stance(_), BuffIconKind::Buff { .. }) => Ordering::Less,
            (BuffIconKind::Stance(stance), BuffIconKind::Stance(stance_other)) => {
                stance.cmp(stance_other)
            },
        }
    }
}

impl PartialEq for BuffIconKind {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                BuffIconKind::Buff { kind, .. },
                BuffIconKind::Buff {
                    kind: other_kind, ..
                },
            ) => kind == other_kind,
            (BuffIconKind::Stance(stance), BuffIconKind::Stance(stance_other)) => {
                stance == stance_other
            },
            _ => false,
        }
    }
}

impl Eq for BuffIconKind {}

#[derive(Clone, Copy, Debug)]
pub struct BuffIcon {
    kind: BuffIconKind,
    is_buff: bool,
    end_time: Option<f64>,
}

impl BuffIcon {
    pub fn multiplicity(&self) -> usize {
        match self.kind {
            BuffIconKind::Buff { multiplicity, .. } => multiplicity,
            BuffIconKind::Stance(_) => 1,
        }
    }

    pub fn get_buff_time(&self, time: Time) -> String {
        if let Some(end) = self.end_time {
            format!("{:.0}s", end - time.0)
        } else {
            "".to_string()
        }
    }

    pub fn icons_vec(buffs: &comp::Buffs, stance: Option<&comp::Stance>) -> Vec<Self> {
        buffs
            .iter_active()
            .filter_map(BuffIcon::from_buffs)
            .chain(stance.and_then(BuffIcon::from_stance))
            .collect::<Vec<_>>()
    }

    fn from_stance(stance: &comp::Stance) -> Option<Self> {
        let stance = if let Stance::None = stance {
            return None;
        } else {
            stance
        };
        Some(BuffIcon {
            kind: BuffIconKind::Stance(*stance),
            is_buff: true,
            end_time: None,
        })
    }

    fn from_buffs<'b, I: Iterator<Item = &'b comp::Buff>>(buffs: I) -> Option<Self> {
        let (buff, count) = buffs.fold((None, 0), |(strongest, count), buff| {
            (strongest.or(Some(buff)), count + 1)
        });
        let buff = buff?;
        Some(Self {
            kind: BuffIconKind::Buff {
                kind: buff.kind,
                data: buff.data,
                multiplicity: count,
            },
            is_buff: buff.kind.is_buff(),
            end_time: buff.end_time.map(|end| end.0),
        })
    }
}

pub struct ExpFloater {
    pub owner: Uid,
    pub exp_change: u32,
    pub timer: f32,
    pub jump_timer: f32,
    pub rand_offset: (f32, f32),
    pub xp_pools: HashSet<SkillGroupKind>,
}

pub struct SkillPointGain {
    pub skill_tree: SkillGroupKind,
    pub total_points: u16,
    pub timer: f32,
}

#[derive(Debug, Clone, Copy)]
pub struct ComboFloater {
    pub combo: u32,
    pub timer: f64,
}

pub struct BlockFloater {
    pub timer: f32,
}

pub struct DebugInfo {
    pub tps: f64,
    pub frame_time: Duration,
    pub ping_ms: f64,
    pub coordinates: Option<comp::Pos>,
    pub velocity: Option<comp::Vel>,
    pub ori: Option<comp::Ori>,
    pub character_state: Option<comp::CharacterState>,
    pub look_dir: Dir,
    pub in_fluid: Option<comp::Fluid>,
    pub num_chunks: u32,
    pub num_lights: u32,
    pub num_visible_chunks: u32,
    pub num_shadow_chunks: u32,
    pub num_figures: u32,
    pub num_figures_visible: u32,
    pub num_particles: u32,
    pub num_particles_visible: u32,
    pub current_track: String,
    pub current_artist: String,
    pub active_channels: ActiveChannels,
}

pub struct HudInfo {
    pub is_aiming: bool,
    pub active_mine_tool: Option<ToolKind>,
    pub is_first_person: bool,
    pub viewpoint_entity: specs::Entity,
    pub mutable_viewpoint: bool,
    pub target_entity: Option<specs::Entity>,
    pub selected_entity: Option<(specs::Entity, Instant)>,
    pub persistence_load_error: Option<SkillsPersistenceError>,
}

#[derive(Clone)]
pub enum Event {
    SendMessage(String),
    SendCommand(String, Vec<String>),

    CharacterSelection,
    UseSlot {
        slot: comp::slot::Slot,
        bypass_dialog: bool,
    },
    SwapEquippedWeapons,
    SwapSlots {
        slot_a: comp::slot::Slot,
        slot_b: comp::slot::Slot,
        bypass_dialog: bool,
    },
    SplitSwapSlots {
        slot_a: comp::slot::Slot,
        slot_b: comp::slot::Slot,
        bypass_dialog: bool,
    },
    DropSlot(comp::slot::Slot),
    SplitDropSlot(comp::slot::Slot),
    SortInventory,
    ChangeHotbarState(Box<HotbarState>),
    TradeAction(TradeAction),
    Ability(usize, bool),
    Logout,
    Quit,

    CraftRecipe {
        recipe_name: String,
        craft_sprite: Option<(VolumePos, SpriteKind)>,
        amount: u32,
    },
    SalvageItem {
        slot: InvSlotId,
        salvage_pos: VolumePos,
    },
    CraftModularWeapon {
        primary_slot: InvSlotId,
        secondary_slot: InvSlotId,
        craft_sprite: Option<VolumePos>,
    },
    CraftModularWeaponComponent {
        toolkind: ToolKind,
        material: InvSlotId,
        modifier: Option<InvSlotId>,
        craft_sprite: Option<VolumePos>,
    },
    RepairItem {
        item: Slot,
        sprite_pos: VolumePos,
    },
    InviteMember(Uid),
    AcceptInvite,
    DeclineInvite,
    KickMember(Uid),
    LeaveGroup,
    AssignLeader(Uid),
    RemoveBuff(BuffKind),
    LeaveStance,
    UnlockSkill(Skill),
    SelectExpBar(Option<SkillGroupKind>),

    RequestSiteInfo(SiteId),
    ChangeAbility(usize, AuxiliaryAbility),

    SettingsChange(SettingsChange),
    AcknowledgePersistenceLoadError,
    MapMarkerEvent(MapMarkerChange),
}

// TODO: Are these the possible layouts we want?
// TODO: Maybe replace this with bitflags.
// `map` is not here because it currently is displayed over the top of other
// open windows.
#[derive(PartialEq, Eq)]
pub enum Windows {
    Settings, // Display settings window.
    None,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum CrosshairType {
    RoundEdges,
    Edges,
    #[serde(other)]
    Round,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum Intro {
    Never,
    #[serde(other)]
    Show,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum XpBar {
    OnGain,
    #[serde(other)]
    Always,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum BarNumbers {
    Percent,
    Off,
    #[serde(other)]
    Values,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum ShortcutNumbers {
    Off,
    #[serde(other)]
    On,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum BuffPosition {
    Map,
    #[serde(other)]
    Bar,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum PressBehavior {
    Hold = 1,
    #[serde(other)]
    Toggle = 0,
}
/// Similar to [PressBehavior], with different semantics for settings that
/// change state automatically. There is no [PressBehavior::update][update]
/// implementation because it doesn't apply to the use case; this is just a
/// sentinel.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum AutoPressBehavior {
    Auto = 1,
    #[serde(other)]
    Toggle = 0,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChatTab {
    pub label: String,
    pub filter: ChatFilter,
}
impl Default for ChatTab {
    fn default() -> Self {
        Self {
            label: String::from("Chat"),
            filter: ChatFilter::default(),
        }
    }
}

impl PressBehavior {
    pub fn update(&self, keystate: bool, setting: &mut bool, f: impl FnOnce(bool)) {
        match (self, keystate) {
            // flip the state on key press in toggle mode
            (PressBehavior::Toggle, true) => {
                *setting ^= true;
                f(*setting);
            },
            // do nothing on key release in toggle mode
            (PressBehavior::Toggle, false) => {},
            // set the setting to the key state in hold mode
            (PressBehavior::Hold, state) => {
                *setting = state;
                f(*setting);
            },
        }
    }
}

#[derive(Default, Clone)]
pub struct MapMarkers {
    owned: Option<Vec2<i32>>,
    group: HashMap<Uid, Vec2<i32>>,
}

/// (target slot, input value, inventory quantity, is our inventory, error,
/// trade.offers index of trade slot)
pub struct TradeAmountInput {
    slot: InvSlotId,
    input: String,
    inv: u32,
    ours: bool,
    err: Option<String>,
    who: usize,
    input_painted: bool,
    submit_action: Option<TradeAction>,
}

impl TradeAmountInput {
    pub fn new(slot: InvSlotId, input: String, inv: u32, ours: bool, who: usize) -> Self {
        Self {
            slot,
            input,
            inv,
            ours,
            who,
            err: None,
            input_painted: false,
            submit_action: None,
        }
    }
}

pub struct Show {
    ui: bool,
    intro: bool,
    crafting: bool,
    bag: bool,
    bag_inv: bool,
    bag_details: bool,
    trade: bool,
    trade_details: bool,
    social: bool,
    diary: bool,
    group: bool,
    quest: bool,
    group_menu: bool,
    esc_menu: bool,
    open_windows: Windows,
    map: bool,
    ingame: bool,
    chat_tab_settings_index: Option<usize>,
    settings_tab: SettingsTab,
    diary_fields: diary::DiaryShow,
    crafting_fields: crafting::CraftingShow,
    social_search_key: Option<String>,
    want_grab: bool,
    stats: bool,
    free_look: bool,
    auto_walk: bool,
    zoom_lock: ChangeNotification,
    camera_clamp: bool,
    prompt_dialog: Option<PromptDialogSettings>,
    location_markers: MapMarkers,
    trade_amount_input_key: Option<TradeAmountInput>,
}
impl Show {
    fn bag(&mut self, open: bool) {
        if !self.esc_menu {
            self.bag = open;
            self.map = false;
            self.crafting_fields.salvage = false;

            if !open {
                self.crafting = false;
            }

            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn trade(&mut self, open: bool) {
        if !self.esc_menu {
            self.bag = open;
            self.trade = open;
            self.map = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn map(&mut self, open: bool) {
        if !self.esc_menu {
            self.map = open;
            self.bag = false;
            self.crafting = false;
            self.crafting_fields.salvage = false;
            self.social = false;
            self.quest = false;
            self.diary = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn social(&mut self, open: bool) {
        if !self.esc_menu {
            if !self.social && open {
                // rising edge detector
                self.search_social_players(None);
            }
            self.social = open;
            self.diary = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn quest(&mut self, open: bool) {
        if !self.esc_menu {
            self.quest = open;
            self.diary = false;
            self.map = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn crafting(&mut self, open: bool) {
        if !self.esc_menu {
            if !self.crafting && open {
                // rising edge detector
                self.search_crafting_recipe(None);
            }
            self.crafting = open;
            self.crafting_fields.salvage = false;
            self.crafting_fields.recipe_inputs = HashMap::new();
            self.bag = open;
            self.map = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    pub fn open_crafting_tab(
        &mut self,
        tab: CraftingTab,
        craft_sprite: Option<(VolumePos, SpriteKind)>,
    ) {
        self.selected_crafting_tab(tab);
        self.crafting(true);
        self.crafting_fields.craft_sprite = self.crafting_fields.craft_sprite.or(craft_sprite);
        self.crafting_fields.salvage = matches!(
            self.crafting_fields.craft_sprite,
            Some((_, SpriteKind::DismantlingBench))
        ) && matches!(tab, CraftingTab::Dismantle);
        self.crafting_fields.initialize_repair = matches!(
            self.crafting_fields.craft_sprite,
            Some((_, SpriteKind::RepairBench))
        );
    }

    fn diary(&mut self, open: bool) {
        if !self.esc_menu {
            self.social = false;
            self.quest = false;
            self.crafting = false;
            self.crafting_fields.salvage = false;
            self.bag = false;
            self.map = false;
            self.diary_fields = diary::DiaryShow::default();
            self.diary = open;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn settings(&mut self, open: bool) {
        if !self.esc_menu {
            self.open_windows = if open {
                Windows::Settings
            } else {
                Windows::None
            };
            self.bag = false;
            self.social = false;
            self.quest = false;
            self.crafting = false;
            self.crafting_fields.salvage = false;
            self.diary = false;
            self.want_grab = !self.any_window_requires_cursor();
        }
    }

    fn toggle_trade(&mut self) { self.trade(!self.trade); }

    fn toggle_map(&mut self) { self.map(!self.map) }

    fn toggle_social(&mut self) { self.social(!self.social); }

    fn toggle_crafting(&mut self) { self.crafting(!self.crafting) }

    fn toggle_diary(&mut self) { self.diary(!self.diary) }

    fn toggle_ui(&mut self) { self.ui = !self.ui; }

    fn toggle_settings(&mut self, global_state: &GlobalState) {
        match self.open_windows {
            Windows::Settings => {
                #[cfg(feature = "singleplayer")]
                global_state.unpause();

                self.settings(false);
            },
            _ => {
                #[cfg(feature = "singleplayer")]
                global_state.pause();

                self.settings(true)
            },
        };
        #[cfg(not(feature = "singleplayer"))]
        let _global_state = global_state;
    }

    // TODO: Add self updating key-bindings element

    fn any_window_requires_cursor(&self) -> bool {
        self.bag
            || self.trade
            || self.esc_menu
            || self.map
            || self.social
            || self.crafting
            || self.diary
            || self.intro
            || self.quest
            || !matches!(self.open_windows, Windows::None)
    }

    fn toggle_windows(&mut self, global_state: &mut GlobalState) {
        if self.any_window_requires_cursor() {
            self.bag = false;
            self.trade = false;
            self.esc_menu = false;
            self.intro = false;
            self.map = false;
            self.social = false;
            self.quest = false;
            self.diary = false;
            self.crafting = false;
            self.open_windows = Windows::None;
            self.want_grab = true;

            // Unpause the game if we are on singleplayer
            #[cfg(feature = "singleplayer")]
            global_state.unpause();
        } else {
            self.esc_menu = true;
            self.want_grab = false;

            // Pause the game if we are on singleplayer
            #[cfg(feature = "singleplayer")]
            global_state.pause();
        }
        #[cfg(not(feature = "singleplayer"))]
        let _global_state = global_state;
    }

    fn open_setting_tab(&mut self, tab: SettingsTab) {
        self.open_windows = Windows::Settings;
        self.esc_menu = false;
        self.settings_tab = tab;
        self.bag = false;
        self.want_grab = false;
    }

    fn open_skill_tree(&mut self, tree_sel: SelectedSkillTree) {
        self.diary_fields.skilltreetab = tree_sel;
        self.social = false;
    }

    fn selected_crafting_tab(&mut self, sel_cat: CraftingTab) {
        self.crafting_fields.crafting_tab = sel_cat;
    }

    fn search_crafting_recipe(&mut self, search_key: Option<String>) {
        self.crafting_fields.crafting_search_key = search_key;
    }

    fn search_social_players(&mut self, search_key: Option<String>) {
        self.social_search_key = search_key;
    }

    pub fn update_map_markers(&mut self, event: comp::MapMarkerUpdate) {
        match event {
            comp::MapMarkerUpdate::Owned(event) => match event {
                MapMarkerChange::Update(waypoint) => self.location_markers.owned = Some(waypoint),
                MapMarkerChange::Remove => self.location_markers.owned = None,
            },
            comp::MapMarkerUpdate::GroupMember(user, event) => match event {
                MapMarkerChange::Update(waypoint) => {
                    self.location_markers.group.insert(user, waypoint);
                },
                MapMarkerChange::Remove => {
                    self.location_markers.group.remove(&user);
                },
            },
            comp::MapMarkerUpdate::ClearGroup => {
                self.location_markers.group.clear();
            },
        }
    }
}

pub struct PromptDialogSettings {
    message: String,
    affirmative_event: Event,
    negative_option: bool,
    negative_event: Option<Event>,
    outcome_via_keypress: Option<bool>,
}

impl PromptDialogSettings {
    pub fn new(message: String, affirmative_event: Event, negative_event: Option<Event>) -> Self {
        Self {
            message,
            affirmative_event,
            negative_option: true,
            negative_event,
            outcome_via_keypress: None,
        }
    }

    pub fn set_outcome_via_keypress(&mut self, outcome: bool) {
        self.outcome_via_keypress = Some(outcome);
    }

    #[must_use]
    pub fn with_no_negative_option(mut self) -> Self {
        self.negative_option = false;
        self
    }
}

pub struct Floaters {
    pub exp_floaters: Vec<ExpFloater>,
    pub skill_point_displays: Vec<SkillPointGain>,
    pub combo_floater: Option<ComboFloater>,
    pub block_floaters: Vec<BlockFloater>,
}

#[derive(Clone)]
pub enum HudLootOwner {
    Name(String),
    Group,
    Unknown,
}

#[derive(Clone)]
pub enum HudCollectFailedReason {
    InventoryFull,
    LootOwned {
        owner: HudLootOwner,
        expiry_secs: u64,
    },
}

impl HudCollectFailedReason {
    pub fn from_server_reason(reason: &CollectFailedReason, ecs: &specs::World) -> Self {
        match reason {
            CollectFailedReason::InventoryFull => HudCollectFailedReason::InventoryFull,
            CollectFailedReason::LootOwned { owner, expiry_secs } => {
                let owner = match owner {
                    LootOwnerKind::Player(owner_uid) => {
                        let maybe_owner_name = ecs.entity_from_uid(*owner_uid).and_then(|entity| {
                            ecs.read_storage::<comp::Stats>()
                                .get(entity)
                                .map(|stats| stats.name.clone())
                        });

                        if let Some(name) = maybe_owner_name {
                            HudLootOwner::Name(name)
                        } else {
                            HudLootOwner::Unknown
                        }
                    },
                    LootOwnerKind::Group(_) => HudLootOwner::Group,
                };

                HudCollectFailedReason::LootOwned {
                    owner,
                    expiry_secs: *expiry_secs,
                }
            },
        }
    }
}
#[derive(Clone)]
pub struct CollectFailedData {
    pulse: f32,
    reason: HudCollectFailedReason,
}

impl CollectFailedData {
    pub fn new(pulse: f32, reason: HudCollectFailedReason) -> Self { Self { pulse, reason } }
}

pub struct Hud {
    ui: Ui,
    ids: Ids,
    world_map: (/* Id */ Vec<Rotations>, Vec2<u32>),
    imgs: Imgs,
    item_imgs: ItemImgs,
    item_i18n: ItemI18n,
    fonts: Fonts,
    rot_imgs: ImgsRot,
    failed_block_pickups: HashMap<VolumePos, CollectFailedData>,
    failed_entity_pickups: HashMap<EcsEntity, CollectFailedData>,
    new_loot_messages: VecDeque<LootMessage>,
    new_messages: VecDeque<comp::ChatMsg>,
    // NOTE Used for storing messages sent while the chat is hidden. This is needed because NPC
    // speech uses new_messages so we need to clear it every frame.
    message_backlog: VecDeque<comp::ChatMsg>,
    new_notifications: VecDeque<Notification>,
    speech_bubbles: HashMap<Uid, comp::SpeechBubble>,
    content_bubbles: Vec<(Vec3<f32>, comp::SpeechBubble)>,
    pub show: Show,
    //never_show: bool,
    //intro: bool,
    //intro_2: bool,
    to_focus: Option<Option<widget::Id>>,
    force_ungrab: bool,
    force_chat_input: Option<String>,
    force_chat_cursor: Option<Index>,
    tab_complete: Option<String>,
    pulse: f32,
    hp_pulse: f32,
    slot_manager: slots::SlotManager,
    hotbar: hotbar::State,
    events: Vec<Event>,
    crosshair_opacity: f32,
    floaters: Floaters,
    voxel_minimap: VoxelMinimap,
    map_drag: Vec2<f64>,
    force_chat: bool,
    clear_chat: bool,
}

impl Hud {
    pub fn new(global_state: &mut GlobalState, client: &Client) -> Self {
        let window = &mut global_state.window;
        let settings = &global_state.settings;

        let mut ui = Ui::new(window).unwrap();
        ui.set_scaling_mode(settings.interface.ui_scale);
        // Generate ids.
        let ids = Ids::new(ui.id_generator());
        // Load world map
        let mut layers = Vec::new();
        for layer in client.world_data().map_layers() {
            // NOTE: Use a border the same color as the LOD ocean color (but with a
            // translucent alpha since UI have transparency and LOD doesn't).
            layers.push(ui.add_graphic_with_rotations(Graphic::Image(
                Arc::clone(layer),
                Some(default_water_color()),
            )));
        }
        let world_map = (layers, client.world_data().chunk_size().map(|e| e as u32));
        // Load images.
        let imgs = Imgs::load(&mut ui).expect("Failed to load images!");
        // Load rotation images.
        let rot_imgs = ImgsRot::load(&mut ui).expect("Failed to load rot images!");
        // Load item images.
        let item_imgs = ItemImgs::new(&mut ui, imgs.not_found);
        // Load item text ("reference" to name and description)
        let item_i18n = ItemI18n::new_expect();
        // Load fonts.
        let fonts = Fonts::load(global_state.i18n.read().fonts(), &mut ui)
            .expect("Impossible to load fonts!");
        // Get the server name.
        let server = &client.server_info().name;
        // Get the id, unwrap is safe because this CANNOT be None at this
        // point.

        let character_id = match client.presence().unwrap() {
            PresenceKind::Character(id) => Some(id),
            PresenceKind::LoadingCharacter(id) => Some(id),
            PresenceKind::Spectator => None,
            PresenceKind::Possessor => None,
        };

        // Create a new HotbarState from the persisted slots.
        let hotbar_state =
            HotbarState::new(global_state.profile.get_hotbar_slots(server, character_id));

        let slot_manager = slots::SlotManager::new(
            ui.id_generator(),
            Vec2::broadcast(40.0),
            global_state.settings.interface.slots_use_prefixes,
            global_state.settings.interface.slots_prefix_switch_point,
            // TODO(heyzoos) Will be useful for whoever works on rendering the number of items
            // "in hand".
            // fonts.cyri.conrod_id,
            // Vec2::new(1.0, 1.0),
            // fonts.cyri.scale(12),
            // TEXT_COLOR,
        );

        Self {
            voxel_minimap: VoxelMinimap::new(&mut ui),
            ui,
            imgs,
            world_map,
            rot_imgs,
            item_imgs,
            item_i18n,
            fonts,
            ids,
            failed_block_pickups: HashMap::default(),
            failed_entity_pickups: HashMap::default(),
            new_loot_messages: VecDeque::new(),
            new_messages: VecDeque::new(),
            message_backlog: VecDeque::new(),
            new_notifications: VecDeque::new(),
            speech_bubbles: HashMap::new(),
            content_bubbles: Vec::new(),
            //intro: false,
            //intro_2: false,
            show: Show {
                intro: false,
                bag: false,
                bag_inv: false,
                bag_details: false,
                trade: false,
                trade_details: false,
                esc_menu: false,
                open_windows: Windows::None,
                map: false,
                crafting: false,
                ui: true,
                social: false,
                diary: false,
                group: false,
                // Change this before implementation!
                quest: false,
                group_menu: false,
                chat_tab_settings_index: None,
                settings_tab: SettingsTab::Interface,
                diary_fields: diary::DiaryShow::default(),
                crafting_fields: crafting::CraftingShow::default(),
                social_search_key: None,
                want_grab: true,
                ingame: true,
                stats: false,
                free_look: false,
                auto_walk: false,
                zoom_lock: ChangeNotification::default(),
                camera_clamp: false,
                prompt_dialog: None,
                location_markers: MapMarkers::default(),
                trade_amount_input_key: None,
            },
            to_focus: None,
            //never_show: false,
            force_ungrab: false,
            force_chat_input: None,
            force_chat_cursor: None,
            tab_complete: None,
            pulse: 0.0,
            hp_pulse: 0.0,
            slot_manager,
            hotbar: hotbar_state,
            events: Vec::new(),
            crosshair_opacity: 0.0,
            floaters: Floaters {
                exp_floaters: Vec::new(),
                skill_point_displays: Vec::new(),
                combo_floater: None,
                block_floaters: Vec::new(),
            },
            map_drag: Vec2::zero(),
            force_chat: false,
            clear_chat: false,
        }
    }

    pub fn clear_chat(&mut self) { self.clear_chat = true; }

    pub fn set_prompt_dialog(&mut self, prompt_dialog: PromptDialogSettings) {
        self.show.prompt_dialog = Some(prompt_dialog);
    }

    pub fn update_fonts(&mut self, i18n: &Localization) {
        self.fonts = Fonts::load(i18n.fonts(), &mut self.ui).expect("Impossible to load fonts!");
    }

    pub fn set_slots_use_prefixes(&mut self, use_prefixes: bool) {
        self.slot_manager.set_use_prefixes(use_prefixes);
    }

    pub fn set_slots_prefix_switch_point(&mut self, prefix_switch_point: u32) {
        self.slot_manager
            .set_prefix_switch_point(prefix_switch_point);
    }

    #[allow(clippy::single_match)] // TODO: Pending review in #587
    fn update_layout(
        &mut self,
        client: &Client,
        global_state: &mut GlobalState,
        debug_info: &Option<DebugInfo>,
        dt: Duration,
        info: HudInfo,
        camera: &Camera,
        interactable: Option<&Interactable>,
    ) -> Vec<Event> {
        span!(_guard, "update_layout", "Hud::update_layout");
        let mut events = core::mem::take(&mut self.events);
        if global_state.settings.interface.map_show_voxel_map {
            self.voxel_minimap.maintain(client, &mut self.ui);
        }
        let scale = self.ui.scale();
        let (ref mut ui_widgets, ref mut item_tooltip_manager, ref mut tooltip_manager) =
            &mut self.ui.set_widgets();
        // self.ui.set_item_widgets(); pulse time for pulsating elements
        self.pulse += dt.as_secs_f32();
        // FPS
        let fps = global_state.clock.stats().average_tps;
        let version = common::util::DISPLAY_VERSION_LONG.clone();
        let i18n = &global_state.i18n.read();
        let key_layout = &global_state.window.key_layout;

        if self.show.ingame {
            prof_span!("ingame elements");

            let ecs = client.state().ecs();
            let pos = ecs.read_storage::<comp::Pos>();
            let stats = ecs.read_storage::<comp::Stats>();
            let skill_sets = ecs.read_storage::<comp::SkillSet>();
            let healths = ecs.read_storage::<Health>();
            let hardcore = ecs.read_storage::<comp::Hardcore>();
            let buffs = ecs.read_storage::<comp::Buffs>();
            let energy = ecs.read_storage::<comp::Energy>();
            let mut hp_floater_lists = ecs.write_storage::<HpFloaterList>();
            let uids = ecs.read_storage::<Uid>();
            let interpolated = ecs.read_storage::<vcomp::Interpolated>();
            let scales = ecs.read_storage::<comp::Scale>();
            let bodies = ecs.read_storage::<comp::Body>();
            let items = ecs.read_storage::<PickupItem>();
            let inventories = ecs.read_storage::<comp::Inventory>();
            let msm = ecs.read_resource::<MaterialStatManifest>();
            let entities = ecs.entities();
            let me = info.viewpoint_entity;
            let poises = ecs.read_storage::<comp::Poise>();
            let alignments = ecs.read_storage::<comp::Alignment>();
            let is_mounts = ecs.read_storage::<Is<Mount>>();
            let is_riders = ecs.read_storage::<Is<Rider>>();
            let stances = ecs.read_storage::<comp::Stance>();
            let char_activities = ecs.read_storage::<comp::CharacterActivity>();
            let time = ecs.read_resource::<Time>();

            // Check if there was a persistence load error of the skillset, and if so
            // display a dialog prompt
            if self.show.prompt_dialog.is_none() {
                if let Some(persistence_error) = info.persistence_load_error {
                    let persistence_error = match persistence_error {
                        SkillsPersistenceError::HashMismatch => {
                            "hud-skill-persistence-hash_mismatch"
                        },
                        SkillsPersistenceError::DeserializationFailure => {
                            "hud-skill-persistence-deserialization_failure"
                        },
                        SkillsPersistenceError::SpentExpMismatch => {
                            "hud-skill-persistence-spent_experience_missing"
                        },
                        SkillsPersistenceError::SkillsUnlockFailed => {
                            "hud-skill-persistence-skills_unlock_failed"
                        },
                    };
                    let persistence_error = global_state
                        .i18n
                        .read()
                        .get_content(&Content::localized(persistence_error));

                    let common_message = global_state
                        .i18n
                        .read()
                        .get_content(&Content::localized("hud-skill-persistence-common_message"));

                    warn!("{}\n{}", persistence_error, common_message);
                    // TODO: Let the player see the more detailed message `persistence_error`?
                    let prompt_dialog = PromptDialogSettings::new(
                        format!("{}\n", common_message),
                        Event::AcknowledgePersistenceLoadError,
                        None,
                    )
                    .with_no_negative_option();
                    // self.set_prompt_dialog(prompt_dialog);
                    self.show.prompt_dialog = Some(prompt_dialog);
                }
            }

            if (client.pending_trade().is_some() && !self.show.trade)
                || (client.pending_trade().is_none() && self.show.trade)
            {
                self.show.toggle_trade();
            }

            //self.input = client.read_storage::<comp::ControllerInputs>();
            if let Some(health) = healths.get(me) {
                // Hurt Frame
                let hp_percentage = health.current() / health.maximum() * 100.0;
                self.hp_pulse += dt.as_secs_f32() * 10.0 / hp_percentage.clamp(3.0, 7.0);
                if hp_percentage < 10.0 && !health.is_dead {
                    let hurt_fade = (self.hp_pulse).sin() * 0.5 + 0.6; //Animation timer
                    Image::new(self.imgs.hurt_bg)
                        .wh_of(ui_widgets.window)
                        .middle_of(ui_widgets.window)
                        .graphics_for(ui_widgets.window)
                        .color(Some(Color::Rgba(1.0, 1.0, 1.0, hurt_fade)))
                        .set(self.ids.hurt_bg, ui_widgets);
                }
                // Alpha Disclaimer
                Text::new(&format!("Veloren {}", &version))
                    .font_id(self.fonts.cyri.conrod_id)
                    .font_size(self.fonts.cyri.scale(10))
                    .color(TEXT_COLOR)
                    .mid_top_with_margin_on(ui_widgets.window, 2.0)
                    .set(self.ids.alpha_text, ui_widgets);

                // Death Frame
                if health.is_dead {
                    Image::new(self.imgs.death_bg)
                        .wh_of(ui_widgets.window)
                        .middle_of(ui_widgets.window)
                        .graphics_for(ui_widgets.window)
                        .color(Some(Color::Rgba(0.0, 0.0, 0.0, 1.0)))
                        .set(self.ids.death_bg, ui_widgets);
                } // Crosshair
                let show_crosshair = (info.is_aiming || info.is_first_person) && !health.is_dead;
                self.crosshair_opacity = Lerp::lerp(
                    self.crosshair_opacity,
                    if show_crosshair { 1.0 } else { 0.0 },
                    5.0 * dt.as_secs_f32(),
                );

                Image::new(
                    // TODO: Do we want to match on this every frame?
                    match global_state.settings.interface.crosshair_type {
                        CrosshairType::Round => self.imgs.crosshair_outer_round,
                        CrosshairType::RoundEdges => self.imgs.crosshair_outer_round_edges,
                        CrosshairType::Edges => self.imgs.crosshair_outer_edges,
                    },
                )
                .w_h(21.0 * 1.5, 21.0 * 1.5)
                .middle_of(ui_widgets.window)
                .color(Some(Color::Rgba(
                    1.0,
                    1.0,
                    1.0,
                    self.crosshair_opacity * global_state.settings.interface.crosshair_opacity,
                )))
                .set(self.ids.crosshair_outer, ui_widgets);
                Image::new(self.imgs.crosshair_inner)
                    .w_h(21.0 * 2.0, 21.0 * 2.0)
                    .middle_of(self.ids.crosshair_outer)
                    .color(Some(Color::Rgba(1.0, 1.0, 1.0, 0.6)))
                    .set(self.ids.crosshair_inner, ui_widgets);
            }

            // Max amount the sct font size increases when "flashing"
            const FLASH_MAX: u32 = 2;

            // Get player position.
            let player_pos = client
                .state()
                .ecs()
                .read_storage::<comp::Pos>()
                .get(client.entity())
                .map_or(Vec3::zero(), |pos| pos.0);
            // SCT Output values are called hp_damage and floater.info.amount
            // Numbers are currently divided by 10 and rounded
            if global_state.settings.interface.sct {
                // Render Player SCT numbers
                let mut player_sct_bg_id_walker = self.ids.player_sct_bgs.walk();
                let mut player_sct_id_walker = self.ids.player_scts.walk();
                if let (Some(HpFloaterList { floaters, .. }), Some(health)) = (
                    hp_floater_lists
                        .get_mut(me)
                        .filter(|fl| !fl.floaters.is_empty()),
                    healths.get(me),
                ) {
                    let player_font_col = |precise: bool| {
                        if precise {
                            Rgb::new(1.0, 0.9, 0.0)
                        } else {
                            Rgb::new(1.0, 0.1, 0.0)
                        }
                    };

                    fn calc_fade(floater: &HpFloater) -> f32 {
                        ((crate::ecs::sys::floater::MY_HP_SHOWTIME - floater.timer) * 0.25) + 0.2
                    }

                    floaters.retain(|fl| calc_fade(fl) > 0.0);

                    for floater in floaters {
                        let number_speed = 50.0; // Player number speed
                        let player_sct_bg_id = player_sct_bg_id_walker.next(
                            &mut self.ids.player_sct_bgs,
                            &mut ui_widgets.widget_id_generator(),
                        );
                        let player_sct_id = player_sct_id_walker.next(
                            &mut self.ids.player_scts,
                            &mut ui_widgets.widget_id_generator(),
                        );
                        // Clamp the amount so you don't have absurdly large damage numbers
                        let max_hp_frac = floater
                            .info
                            .amount
                            .abs()
                            .clamp(Health::HEALTH_EPSILON, health.maximum() * 1.25)
                            / health.maximum();
                        let hp_dmg_text = if floater.info.amount.abs() < 0.1 {
                            String::new()
                        } else if global_state.settings.interface.sct_damage_rounding
                            && floater.info.amount.abs() >= 1.0
                        {
                            format!("{:.0}", floater.info.amount.abs())
                        } else {
                            format!("{:.1}", floater.info.amount.abs())
                        };
                        let precise = floater.info.precise;

                        // Timer sets text transparency
                        let hp_fade = calc_fade(floater);

                        // Increase font size based on fraction of maximum health
                        // "flashes" by having a larger size in the first 100ms
                        let font_size =
                            30 + (if precise {
                                (max_hp_frac * 10.0) as u32 * 3 + 10
                            } else {
                                (max_hp_frac * 10.0) as u32 * 3
                            }) + if floater.jump_timer < 0.1 {
                                FLASH_MAX
                                    * (((1.0 - floater.jump_timer * 10.0)
                                        * 10.0
                                        * if precise { 1.25 } else { 1.0 })
                                        as u32)
                            } else {
                                0
                            };
                        let font_col = player_font_col(precise);
                        // Timer sets the widget offset
                        let y = if floater.info.amount < 0.0 {
                            floater.timer as f64
                                * number_speed
                                * floater.info.amount.signum() as f64
                                //* -1.0
                                + 300.0
                                - ui_widgets.win_h * 0.5
                        } else {
                            floater.timer as f64
                                * number_speed
                                * floater.info.amount.signum() as f64
                                * -1.0
                                + 300.0
                                - ui_widgets.win_h * 0.5
                        };
                        // Healing is offset randomly
                        let x = if floater.info.amount < 0.0 {
                            0.0
                        } else {
                            (floater.rand as f64 - 0.5) * 0.08 * ui_widgets.win_w
                                + (0.03 * ui_widgets.win_w * (floater.rand as f64 - 0.5).signum())
                        };
                        Text::new(&hp_dmg_text)
                            .font_size(font_size)
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(Color::Rgba(0.0, 0.0, 0.0, hp_fade))
                            .x_y(x, y - 3.0)
                            .set(player_sct_bg_id, ui_widgets);
                        Text::new(&hp_dmg_text)
                            .font_size(font_size)
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(if floater.info.amount < 0.0 {
                                Color::Rgba(font_col.r, font_col.g, font_col.b, hp_fade)
                            } else {
                                Color::Rgba(0.1, 1.0, 0.1, hp_fade)
                            })
                            .x_y(x, y)
                            .set(player_sct_id, ui_widgets);
                    }
                }
                // EXP Numbers
                self.floaters.exp_floaters.iter_mut().for_each(|f| {
                    f.timer -= dt.as_secs_f32();
                    f.jump_timer += dt.as_secs_f32();
                });
                self.floaters.exp_floaters.retain(|f| f.timer > 0.0);
                for floater in self.floaters.exp_floaters.iter_mut() {
                    let number_speed = 50.0; // Number Speed for Single EXP
                    let player_sct_bg_id = player_sct_bg_id_walker.next(
                        &mut self.ids.player_sct_bgs,
                        &mut ui_widgets.widget_id_generator(),
                    );
                    let player_sct_id = player_sct_id_walker.next(
                        &mut self.ids.player_scts,
                        &mut ui_widgets.widget_id_generator(),
                    );
                    /*let player_sct_icon_id = player_sct_id_walker.next(
                        &mut self.ids.player_scts,
                        &mut ui_widgets.widget_id_generator(),
                    );*/
                    // Increase font size based on fraction of maximum Experience
                    // "flashes" by having a larger size in the first 100ms
                    let font_size_xp = 30
                        + ((floater.exp_change as f32 / 300.0).min(1.0) * 50.0) as u32
                        + if floater.jump_timer < 0.1 {
                            FLASH_MAX * (((1.0 - floater.jump_timer * 10.0) * 10.0) as u32)
                        } else {
                            0
                        };
                    let y = floater.timer as f64 * number_speed; // Timer sets the widget offset
                    //let fade = ((4.0 - floater.timer as f32) * 0.25) + 0.2; // Timer sets
                    // text transparency
                    let fade = floater.timer.min(1.0);

                    if floater.exp_change > 0 {
                        let xp_pool = &floater.xp_pools;
                        let exp_string =
                            &i18n.get_msg_ctx("hud-sct-experience", &i18n::fluent_args! {
                                // Don't show 0 Exp
                                "amount" => &floater.exp_change.max(1),
                            });
                        Text::new(exp_string)
                            .font_size(font_size_xp)
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(Color::Rgba(0.0, 0.0, 0.0, fade))
                            .x_y(
                                ui_widgets.win_w * (0.5 * floater.rand_offset.0 as f64 - 0.25),
                                ui_widgets.win_h * (0.15 * floater.rand_offset.1 as f64) + y - 3.0,
                            )
                            .set(player_sct_bg_id, ui_widgets);
                        Text::new(exp_string)
                            .font_size(font_size_xp)
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(
                                if xp_pool.contains(&SkillGroupKind::Weapon(ToolKind::Pick)) {
                                    Color::Rgba(0.18, 0.32, 0.9, fade)
                                } else {
                                    Color::Rgba(0.59, 0.41, 0.67, fade)
                                },
                            )
                            .x_y(
                                ui_widgets.win_w * (0.5 * floater.rand_offset.0 as f64 - 0.25),
                                ui_widgets.win_h * (0.15 * floater.rand_offset.1 as f64) + y,
                            )
                            .set(player_sct_id, ui_widgets);
                        // Exp Source Image (TODO: fix widget id crash)
                        /*if xp_pool.contains(&SkillGroupKind::Weapon(ToolKind::Pick)) {
                            Image::new(self.imgs.pickaxe_ico)
                                .w_h(font_size_xp as f64, font_size_xp as f64)
                                .left_from(player_sct_id, 5.0)
                                .set(player_sct_icon_id, ui_widgets);
                        }*/
                    }
                }

                // Skill points
                self.floaters
                    .skill_point_displays
                    .iter_mut()
                    .for_each(|f| f.timer -= dt.as_secs_f32());
                self.floaters
                    .skill_point_displays
                    .retain(|d| d.timer > 0_f32);
                if let Some(display) = self.floaters.skill_point_displays.iter_mut().next() {
                    let fade = if display.timer < 3.0 {
                        display.timer * 0.33
                    } else if display.timer < 2.0 {
                        display.timer * 0.33 * 0.1
                    } else {
                        1.0
                    };
                    // Background image
                    let offset = if display.timer < 2.0 {
                        300.0 - (display.timer as f64 - 2.0) * -300.0
                    } else {
                        300.0
                    };
                    Image::new(self.imgs.level_up)
                        .w_h(328.0, 126.0)
                        .mid_top_with_margin_on(ui_widgets.window, offset)
                        .graphics_for(ui_widgets.window)
                        .color(Some(Color::Rgba(1.0, 1.0, 1.0, fade)))
                        .set(self.ids.player_rank_up, ui_widgets);
                    // Rank Number
                    let rank = display.total_points;
                    let fontsize = match rank {
                        1..=99 => (20, 8.0),
                        100..=999 => (18, 9.0),
                        1000..=9999 => (17, 10.0),
                        _ => (14, 12.0),
                    };
                    Text::new(&format!("{}", rank))
                        .font_size(fontsize.0)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(1.0, 1.0, 1.0, fade))
                        .mid_top_with_margin_on(self.ids.player_rank_up, fontsize.1)
                        .set(self.ids.player_rank_up_txt_number, ui_widgets);
                    // Static "New Rank!" text
                    Text::new(&i18n.get_msg("hud-rank_up"))
                        .font_size(40)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(0.0, 0.0, 0.0, fade))
                        .mid_bottom_with_margin_on(self.ids.player_rank_up, 20.0)
                        .set(self.ids.player_rank_up_txt_0_bg, ui_widgets);
                    Text::new(&i18n.get_msg("hud-rank_up"))
                        .font_size(40)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(1.0, 1.0, 1.0, fade))
                        .bottom_left_with_margins_on(self.ids.player_rank_up_txt_0_bg, 2.0, 2.0)
                        .set(self.ids.player_rank_up_txt_0, ui_widgets);
                    // Variable skilltree text
                    let skill = match display.skill_tree {
                        General => i18n.get_msg("common-weapons-general"),
                        Weapon(ToolKind::Hammer) => i18n.get_msg("common-weapons-hammer"),
                        Weapon(ToolKind::Axe) => i18n.get_msg("common-weapons-axe"),
                        Weapon(ToolKind::Sword) => i18n.get_msg("common-weapons-sword"),
                        Weapon(ToolKind::Sceptre) => i18n.get_msg("common-weapons-sceptre"),
                        Weapon(ToolKind::Bow) => i18n.get_msg("common-weapons-bow"),
                        Weapon(ToolKind::Staff) => i18n.get_msg("common-weapons-staff"),
                        Weapon(ToolKind::Pick) => i18n.get_msg("common-tool-mining"),
                        _ => Cow::Borrowed("Unknown"),
                    };
                    Text::new(&skill)
                        .font_size(20)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(0.0, 0.0, 0.0, fade))
                        .mid_top_with_margin_on(self.ids.player_rank_up, 45.0)
                        .set(self.ids.player_rank_up_txt_1_bg, ui_widgets);
                    Text::new(&skill)
                        .font_size(20)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(1.0, 1.0, 1.0, fade))
                        .bottom_left_with_margins_on(self.ids.player_rank_up_txt_1_bg, 2.0, 2.0)
                        .set(self.ids.player_rank_up_txt_1, ui_widgets);
                    // Variable skilltree icon
                    use crate::hud::SkillGroupKind::{General, Weapon};
                    Image::new(match display.skill_tree {
                        General => self.imgs.swords_crossed,
                        Weapon(ToolKind::Hammer) => self.imgs.hammer,
                        Weapon(ToolKind::Axe) => self.imgs.axe,
                        Weapon(ToolKind::Sword) => self.imgs.sword,
                        Weapon(ToolKind::Sceptre) => self.imgs.sceptre,
                        Weapon(ToolKind::Bow) => self.imgs.bow,
                        Weapon(ToolKind::Staff) => self.imgs.staff,
                        Weapon(ToolKind::Pick) => self.imgs.mining,
                        _ => self.imgs.swords_crossed,
                    })
                    .w_h(20.0, 20.0)
                    .left_from(self.ids.player_rank_up_txt_1_bg, 5.0)
                    .color(Some(Color::Rgba(1.0, 1.0, 1.0, fade)))
                    .set(self.ids.player_rank_up_icon, ui_widgets);
                }

                // Scrolling Combat Text for Parrying an attack
                self.floaters
                    .block_floaters
                    .iter_mut()
                    .for_each(|f| f.timer -= dt.as_secs_f32());
                self.floaters.block_floaters.retain(|f| f.timer > 0_f32);
                for floater in self.floaters.block_floaters.iter_mut() {
                    let number_speed = 50.0;
                    let player_sct_bg_id = player_sct_bg_id_walker.next(
                        &mut self.ids.player_sct_bgs,
                        &mut ui_widgets.widget_id_generator(),
                    );
                    let player_sct_id = player_sct_id_walker.next(
                        &mut self.ids.player_scts,
                        &mut ui_widgets.widget_id_generator(),
                    );
                    let font_size = 30;
                    let y = floater.timer as f64 * number_speed; // Timer sets the widget offset
                    // text transparency
                    let fade = if floater.timer < 0.25 {
                        floater.timer / 0.25
                    } else {
                        1.0
                    };

                    Text::new(&i18n.get_msg("hud-sct-block"))
                        .font_size(font_size)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(0.0, 0.0, 0.0, fade))
                        .x_y(
                            ui_widgets.win_w * (0.0),
                            ui_widgets.win_h * (-0.3) + y - 3.0,
                        )
                        .set(player_sct_bg_id, ui_widgets);
                    Text::new(&i18n.get_msg("hud-sct-block"))
                        .font_size(font_size)
                        .font_id(self.fonts.cyri.conrod_id)
                        .color(Color::Rgba(0.69, 0.82, 0.88, fade))
                        .x_y(ui_widgets.win_w * 0.0, ui_widgets.win_h * -0.3 + y)
                        .set(player_sct_id, ui_widgets);
                }
            }

            // Pop speech bubbles
            let now = Instant::now();
            self.speech_bubbles
                .retain(|_uid, bubble| bubble.timeout > now);
            self.content_bubbles
                .retain(|(_pos, bubble)| bubble.timeout > now);

            // Don't show messages from muted players
            self.new_messages.retain(|msg| match msg.uid() {
                Some(uid) => match client.player_list().get(&uid) {
                    Some(player_info) => {
                        if let Some(uuid) = get_player_uuid(client, &player_info.player_alias) {
                            !global_state.profile.mutelist.contains_key(&uuid)
                        } else {
                            true
                        }
                    },
                    None => true,
                },
                None => true,
            });

            // Push speech bubbles
            for msg in self.new_messages.iter() {
                if let Some((bubble, uid)) = msg.to_bubble() {
                    self.speech_bubbles.insert(uid, bubble);
                }
            }

            let mut overhead_walker = self.ids.overheads.walk();
            let mut overitem_walker = self.ids.overitems.walk();
            let mut sct_walker = self.ids.scts.walk();
            let mut sct_bg_walker = self.ids.sct_bgs.walk();
            let pulse = self.pulse;

            let make_overitem =
                |item: &PickupItem, pos, distance, properties, fonts, interaction_options| {
                    let quality = get_quality_col(item.item());

                    // Item
                    overitem::Overitem::new(
                        util::describe(item, i18n, &self.item_i18n).into(),
                        quality,
                        distance,
                        fonts,
                        i18n,
                        &global_state.settings.controls,
                        properties,
                        pulse,
                        &global_state.window.key_layout,
                        interaction_options,
                    )
                    .x_y(0.0, 100.0)
                    .position_ingame(pos)
                };

            self.failed_block_pickups
                .retain(|_, t| pulse - t.pulse < overitem::PICKUP_FAILED_FADE_OUT_TIME);
            self.failed_entity_pickups
                .retain(|_, t| pulse - t.pulse < overitem::PICKUP_FAILED_FADE_OUT_TIME);

            // Render overitem: name, etc.
            for (entity, pos, item, distance) in (&entities, &pos, &items)
                .join()
                .map(|(entity, pos, item)| (entity, pos, item, pos.0.distance_squared(player_pos)))
                .filter(|(_, _, _, distance)| distance < &MAX_PICKUP_RANGE.powi(2))
            {
                let overitem_id = overitem_walker.next(
                    &mut self.ids.overitems,
                    &mut ui_widgets.widget_id_generator(),
                );

                make_overitem(
                    item,
                    pos.0 + Vec3::unit_z() * 1.2,
                    distance,
                    overitem::OveritemProperties {
                        active: interactable.and_then(|i| i.entity()) == Some(entity),
                        pickup_failed_pulse: self.failed_entity_pickups.get(&entity).cloned(),
                    },
                    &self.fonts,
                    vec![(
                        Some(GameInput::Interact),
                        i18n.get_msg("hud-pick_up").to_string(),
                        overitem::TEXT_COLOR,
                    )],
                )
                .set(overitem_id, ui_widgets);
            }

            // Render overtime for an interactable block
            if let Some(Interactable::Block(block, pos, interaction)) = interactable
                && let Some((mat, _, _)) = pos.get_block_and_transform(
                    &ecs.read_resource(),
                    &ecs.read_resource(),
                    |e| {
                        ecs.read_storage::<vcomp::Interpolated>()
                            .get(e)
                            .map(|interpolated| (comp::Pos(interpolated.pos), interpolated.ori))
                    },
                    &ecs.read_storage(),
                )
            {
                let overitem_id = overitem_walker.next(
                    &mut self.ids.overitems,
                    &mut ui_widgets.widget_id_generator(),
                );

                let overitem_properties = overitem::OveritemProperties {
                    active: true,
                    pickup_failed_pulse: self.failed_block_pickups.get(pos).cloned(),
                };

                let pos = mat.mul_point(Vec3::broadcast(0.5));
                let over_pos = pos + Vec3::unit_z() * 0.7;

                let interaction_text = |collect_default, color| match interaction {
                    BlockInteraction::Collect => {
                        vec![(
                            Some(GameInput::Interact),
                            i18n.get_msg(collect_default).to_string(),
                            color,
                        )]
                    },
                    BlockInteraction::Craft(_) => {
                        vec![(
                            Some(GameInput::Interact),
                            i18n.get_msg("hud-use").to_string(),
                            color,
                        )]
                    },
                    BlockInteraction::Unlock(kind) => {
                        let item_name = |item_id: &ItemDefinitionIdOwned| {
                            // TODO: get ItemKey and use it with i18n?
                            item_id
                                .as_ref()
                                .itemdef_id()
                                .map(|id| {
                                    let item = Item::new_from_asset_expect(id);
                                    util::describe(&item, i18n, &self.item_i18n)
                                })
                                .unwrap_or_else(|| "modular item".to_string())
                        };

                        vec![(
                            Some(GameInput::Interact),
                            match kind {
                                UnlockKind::Free => i18n.get_msg("hud-open").to_string(),
                                UnlockKind::Requires(item_id) => i18n
                                    .get_msg_ctx("hud-unlock-requires", &i18n::fluent_args! {
                                        "item" => item_name(item_id),
                                    })
                                    .to_string(),
                                UnlockKind::Consumes(item_id) => i18n
                                    .get_msg_ctx("hud-unlock-requires", &i18n::fluent_args! {
                                        "item" => item_name(item_id),
                                    })
                                    .to_string(),
                            },
                            color,
                        )]
                    },
                    BlockInteraction::Mine(mine_tool) => {
                        match (mine_tool, &info.active_mine_tool) {
                            (ToolKind::Pick, Some(ToolKind::Pick)) => {
                                vec![(
                                    Some(GameInput::Primary),
                                    i18n.get_msg("hud-mine").to_string(),
                                    color,
                                )]
                            },
                            (ToolKind::Pick, _) => {
                                vec![(
                                    None,
                                    i18n.get_msg("hud-mine-needs_pickaxe").to_string(),
                                    color,
                                )]
                            },
                            (ToolKind::Shovel, Some(ToolKind::Shovel)) => {
                                vec![(
                                    Some(GameInput::Primary),
                                    i18n.get_msg("hud-dig").to_string(),
                                    color,
                                )]
                            },
                            (ToolKind::Shovel, _) => {
                                vec![(
                                    None,
                                    i18n.get_msg("hud-mine-needs_shovel").to_string(),
                                    color,
                                )]
                            },
                            _ => {
                                vec![(
                                    None,
                                    i18n.get_msg("hud-mine-needs_unhandled_case").to_string(),
                                    color,
                                )]
                            },
                        }
                    },
                    BlockInteraction::Mount => {
                        let key = match block.get_sprite() {
                            Some(SpriteKind::Helm) => "hud-steer",
                            Some(
                                SpriteKind::Bed
                                | SpriteKind::Bedroll
                                | SpriteKind::BedrollSnow
                                | SpriteKind::BedrollPirate,
                            ) => "hud-lay",
                            _ => "hud-sit",
                        };
                        vec![(Some(GameInput::Mount), i18n.get_msg(key).to_string(), color)]
                    },
                    BlockInteraction::Read(_) => vec![(
                        Some(GameInput::Interact),
                        i18n.get_msg("hud-read").to_string(),
                        color,
                    )],
                    // TODO: change to turn on/turn off?
                    BlockInteraction::LightToggle(enable) => vec![(
                        Some(GameInput::Interact),
                        i18n.get_msg(if *enable {
                            "hud-activate"
                        } else {
                            "hud-deactivate"
                        })
                        .to_string(),
                        color,
                    )],
                };

                // This is only done once per frame, so it's not a performance issue
                if let Some(desc) = block
                    .get_sprite()
                    .filter(|s| s.is_container())
                    .and_then(|s| get_sprite_desc(s, i18n))
                {
                    let (text, color) = if block.is_owned() {
                        ("hud-steal", overitem::NEGATIVE_TEXT_COLOR)
                    } else {
                        ("hud-open", overitem::TEXT_COLOR)
                    };

                    overitem::Overitem::new(
                        desc,
                        overitem::TEXT_COLOR,
                        pos.distance_squared(player_pos),
                        &self.fonts,
                        i18n,
                        &global_state.settings.controls,
                        overitem_properties,
                        self.pulse,
                        &global_state.window.key_layout,
                        interaction_text(text, color),
                    )
                    .x_y(0.0, 100.0)
                    .position_ingame(over_pos)
                    .set(overitem_id, ui_widgets);
                }
                // TODO: Handle this better. The items returned from `try_reclaim_from_block`
                // are based on rng. We probably want some function to get only gauranteed items
                // from `LootSpec`.
                else if let Some((amount, mut item)) = Item::try_reclaim_from_block(*block)
                    .into_iter()
                    .flatten()
                    .next()
                {
                    let (text, color) = if block.is_owned() {
                        ("hud-steal", overitem::NEGATIVE_TEXT_COLOR)
                    } else {
                        ("hud-collect", overitem::TEXT_COLOR)
                    };
                    item.set_amount(amount.clamp(1, item.max_amount()))
                        .expect("amount >= 1 and <= max_amount is always a valid amount");
                    make_overitem(
                        &PickupItem::new(item, ProgramTime(0.0)),
                        over_pos,
                        pos.distance_squared(player_pos),
                        overitem_properties,
                        &self.fonts,
                        interaction_text(text, color),
                    )
                    .set(overitem_id, ui_widgets);
                } else if let Some(desc) = block.get_sprite().and_then(|s| get_sprite_desc(s, i18n))
                {
                    let (text, color) = if block.is_owned() {
                        ("hud-steal", overitem::NEGATIVE_TEXT_COLOR)
                    } else {
                        ("hud-collect", overitem::TEXT_COLOR)
                    };
                    overitem::Overitem::new(
                        desc,
                        overitem::TEXT_COLOR,
                        pos.distance_squared(player_pos),
                        &self.fonts,
                        i18n,
                        &global_state.settings.controls,
                        overitem_properties,
                        self.pulse,
                        &global_state.window.key_layout,
                        interaction_text(text, color),
                    )
                    .x_y(0.0, 100.0)
                    .position_ingame(over_pos)
                    .set(overitem_id, ui_widgets);
                }
            } else if let Some(Interactable::Entity(entity)) = interactable {
                // show hud for campfires and portals
                if let Some(body) = client
                    .state()
                    .ecs()
                    .read_storage::<comp::Body>()
                    .get(*entity)
                    .filter(|b| b.is_campfire() || b.is_portal())
                {
                    let overitem_id = overitem_walker.next(
                        &mut self.ids.overitems,
                        &mut ui_widgets.widget_id_generator(),
                    );

                    let overitem_properties = overitem::OveritemProperties {
                        active: true,
                        pickup_failed_pulse: None,
                    };
                    let pos = client
                        .state()
                        .ecs()
                        .read_storage::<comp::Pos>()
                        .get(*entity)
                        .map_or(Vec3::zero(), |e| e.0);
                    let over_pos = pos + Vec3::unit_z() * 1.5;

                    overitem::Overitem::new(
                        i18n.get_msg(if body.is_campfire() {
                            "hud-crafting-campfire"
                        } else if body.is_portal() {
                            "hud-portal"
                        } else {
                            "hud-use"
                        }),
                        overitem::TEXT_COLOR,
                        pos.distance_squared(player_pos),
                        &self.fonts,
                        i18n,
                        &global_state.settings.controls,
                        overitem_properties,
                        self.pulse,
                        &global_state.window.key_layout,
                        vec![(
                            Some(GameInput::Interact),
                            i18n.get_msg(if body.is_campfire() {
                                "hud-sit"
                            } else if body.is_portal() {
                                "hud-activate"
                            } else {
                                "hud-use"
                            })
                            .to_string(),
                            overitem::TEXT_COLOR,
                        )],
                    )
                    .x_y(0.0, 100.0)
                    .position_ingame(over_pos)
                    .set(overitem_id, ui_widgets);
                }
            }

            let speech_bubbles = &self.speech_bubbles;
            // Render overhead name tags and health bars
            for (
                entity,
                pos,
                info,
                bubble,
                _,
                _,
                health,
                _,
                scale,
                body,
                hpfl,
                in_group,
                dist_sqr,
                alignment,
                is_mount,
                character_activity,
            ) in (
                &entities,
                &pos,
                interpolated.maybe(),
                &stats,
                &skill_sets,
                healths.maybe(),
                &buffs,
                energy.maybe(),
                scales.maybe(),
                &bodies,
                &mut hp_floater_lists,
                &uids,
                &inventories,
                char_activities.maybe(),
                poises.maybe(),
                (
                    alignments.maybe(),
                    is_mounts.maybe(),
                    is_riders.maybe(),
                    stances.maybe(),
                ),
            )
                .join()
                .filter(|t| {
                    let health = t.5;
                    !health.map_or(false, |h| h.is_dead)
                })
                .filter_map(
                    |(
                        entity,
                        pos,
                        interpolated,
                        stats,
                        skill_set,
                        health,
                        buffs,
                        energy,
                        scale,
                        body,
                        hpfl,
                        uid,
                        inventory,
                        character_activity,
                        poise,
                        (alignment, is_mount, is_rider, stance),
                    )| {
                        // Use interpolated position if available
                        let pos = interpolated.map_or(pos.0, |i| i.pos);
                        let in_group = client.group_members().contains_key(uid);
                        let is_me = entity == me;
                        let dist_sqr = pos.distance_squared(player_pos);

                        // Determine whether to display nametag and healthbar based on whether the
                        // entity is mounted, has been damaged, is targeted/selected, or is in your
                        // group
                        // Note: even if this passes the healthbar can
                        // be hidden in some cases if it is at maximum
                        let display_overhead_info = !is_me
                            && (is_mount.is_none()
                                || health.map_or(true, overhead::should_show_healthbar))
                            && is_rider
                                .map_or(true, |is_rider| Some(&is_rider.mount) != uids.get(me))
                            && (info.target_entity.map_or(false, |e| e == entity)
                                || info.selected_entity.map_or(false, |s| s.0 == entity)
                                || health.map_or(true, overhead::should_show_healthbar)
                                || in_group)
                            && dist_sqr
                                < (if in_group {
                                    NAMETAG_GROUP_RANGE
                                } else if hpfl
                                    .time_since_last_dmg_by_me
                                    .map_or(false, |t| t < NAMETAG_DMG_TIME)
                                {
                                    NAMETAG_DMG_RANGE
                                } else {
                                    NAMETAG_RANGE
                                })
                                .powi(2);

                        let info = display_overhead_info.then(|| overhead::Info {
                            name: Some(&stats.name),
                            health,
                            buffs: Some(buffs),
                            energy,
                            combat_rating: if let (Some(health), Some(energy), Some(poise)) =
                                (health, energy, poise)
                            {
                                Some(combat::combat_rating(
                                    inventory, health, energy, poise, skill_set, *body, &msm,
                                ))
                            } else {
                                None
                            },
                            hardcore: hardcore.contains(entity),
                            stance,
                        });
                        // Only render bubble if nearby or if its me and setting is on
                        let bubble = if (dist_sqr < SPEECH_BUBBLE_RANGE.powi(2) && !is_me)
                            || (is_me && global_state.settings.interface.speech_bubble_self)
                        {
                            speech_bubbles.get(uid)
                        } else {
                            None
                        };
                        (info.is_some() || bubble.is_some()).then_some({
                            (
                                entity,
                                pos,
                                info,
                                bubble,
                                stats,
                                skill_set,
                                health,
                                buffs,
                                scale,
                                body,
                                hpfl,
                                in_group,
                                dist_sqr,
                                alignment,
                                is_mount,
                                character_activity,
                            )
                        })
                    },
                )
            {
                let overhead_id = overhead_walker.next(
                    &mut self.ids.overheads,
                    &mut ui_widgets.widget_id_generator(),
                );

                let height_offset = body.height() * scale.map_or(1.0, |s| s.0) + 0.5;
                let ingame_pos = pos + Vec3::unit_z() * height_offset;

                // Speech bubble, name, level, and hp bars
                overhead::Overhead::new(
                    info,
                    bubble,
                    in_group,
                    &global_state.settings.interface,
                    self.pulse,
                    i18n,
                    &global_state.settings.controls,
                    &self.imgs,
                    &self.fonts,
                    &global_state.window.key_layout,
                    match alignment {
                        // TODO: Don't use `MAX_MOUNT_RANGE` here, add dedicated interaction range
                        Some(comp::Alignment::Npc)
                            if dist_sqr < common::consts::MAX_MOUNT_RANGE.powi(2)
                                && interactable.and_then(|i| i.entity()) == Some(entity) =>
                        {
                            vec![
                                (GameInput::Interact, i18n.get_msg("hud-talk").to_string()),
                                (GameInput::Trade, i18n.get_msg("hud-trade").to_string()),
                            ]
                        },
                        Some(comp::Alignment::Owned(owner))
                            if dist_sqr < common::consts::MAX_MOUNT_RANGE.powi(2) =>
                        {
                            let mut options = Vec::new();
                            if is_mount.is_none() {
                                if Some(*owner) == client.uid() {
                                    options.push((
                                        GameInput::Trade,
                                        i18n.get_msg("hud-trade").to_string(),
                                    ));
                                    if !client.is_riding()
                                        && is_mountable(body, bodies.get(client.entity()))
                                    {
                                        options.push((
                                            GameInput::Mount,
                                            i18n.get_msg("hud-mount").to_string(),
                                        ));
                                    }

                                    let is_staying = character_activity
                                        .map_or(false, |activity| activity.is_pet_staying);

                                    options.push((
                                        GameInput::StayFollow,
                                        i18n.get_msg(if is_staying {
                                            "hud-follow"
                                        } else {
                                            "hud-stay"
                                        })
                                        .to_string(),
                                    ));
                                }

                                // Anyone can pet a tamed animal
                                options.push((
                                    GameInput::Interact,
                                    i18n.get_msg("hud-pet").to_string(),
                                ));
                            }
                            options
                        },
                        Some(comp::Alignment::Tame) => {
                            vec![(GameInput::Interact, i18n.get_msg("hud-pet").to_string())]
                        },
                        _ => Vec::new(),
                    },
                    &time,
                )
                .x_y(0.0, 100.0)
                .position_ingame(ingame_pos)
                .set(overhead_id, ui_widgets);

                // Enemy SCT
                if global_state.settings.interface.sct && !hpfl.floaters.is_empty() {
                    fn calc_fade(floater: &HpFloater) -> f32 {
                        if floater.info.precise {
                            ((crate::ecs::sys::floater::PRECISE_SHOWTIME - floater.timer) * 0.75)
                                + 0.5
                        } else {
                            ((crate::ecs::sys::floater::HP_SHOWTIME - floater.timer) * 0.25) + 0.2
                        }
                    }

                    hpfl.floaters.retain(|fl| calc_fade(fl) > 0.0);
                    let floaters = &hpfl.floaters;

                    // Colors
                    const WHITE: Rgb<f32> = Rgb::new(1.0, 0.9, 0.8);
                    const LIGHT_OR: Rgb<f32> = Rgb::new(1.0, 0.925, 0.749);
                    const LIGHT_MED_OR: Rgb<f32> = Rgb::new(1.0, 0.85, 0.498);
                    const MED_OR: Rgb<f32> = Rgb::new(1.0, 0.776, 0.247);
                    const DARK_ORANGE: Rgb<f32> = Rgb::new(1.0, 0.7, 0.0);
                    const RED_ORANGE: Rgb<f32> = Rgb::new(1.0, 0.349, 0.0);
                    const DAMAGE_COLORS: [Rgb<f32>; 6] = [
                        WHITE,
                        LIGHT_OR,
                        LIGHT_MED_OR,
                        MED_OR,
                        DARK_ORANGE,
                        RED_ORANGE,
                    ];
                    // Largest value that select the first color is 40, then it shifts colors
                    // every 5
                    let font_col = |font_size: u32, precise: bool| {
                        if precise {
                            Rgb::new(1.0, 0.9, 0.0)
                        } else {
                            DAMAGE_COLORS[(font_size.saturating_sub(36) / 5).min(5) as usize]
                        }
                    };

                    for floater in floaters {
                        let number_speed = 250.0; // Enemy number speed
                        let sct_id = sct_walker
                            .next(&mut self.ids.scts, &mut ui_widgets.widget_id_generator());
                        let sct_bg_id = sct_bg_walker
                            .next(&mut self.ids.sct_bgs, &mut ui_widgets.widget_id_generator());
                        // Clamp the amount so you don't have absurdly large damage numbers
                        let max_hp_frac = floater
                            .info
                            .amount
                            .abs()
                            .clamp(Health::HEALTH_EPSILON, health.map_or(1.0, |h| h.maximum()))
                            / health.map_or(1.0, |h| h.maximum());
                        let hp_dmg_text = if floater.info.amount.abs() < 0.1 {
                            String::new()
                        } else if global_state.settings.interface.sct_damage_rounding
                            && floater.info.amount.abs() >= 1.0
                        {
                            format!("{:.0}", floater.info.amount.abs())
                        } else {
                            format!("{:.1}", floater.info.amount.abs())
                        };
                        let precise = floater.info.precise;
                        // Timer sets text transparency
                        let fade = calc_fade(floater);
                        // Increase font size based on fraction of maximum health
                        // "flashes" by having a larger size in the first 100ms
                        let font_size =
                            30 + (if precise {
                                (max_hp_frac * 10.0) as u32 * 3 + 10
                            } else {
                                (max_hp_frac * 10.0) as u32 * 3
                            }) + if floater.jump_timer < 0.1 {
                                FLASH_MAX
                                    * (((1.0 - floater.jump_timer * 10.0)
                                        * 10.0
                                        * if precise { 1.25 } else { 1.0 })
                                        as u32)
                            } else {
                                0
                            };
                        let font_col = font_col(font_size, precise);
                        // Timer sets the widget offset
                        let y = if precise {
                            ui_widgets.win_h * (floater.rand as f64 % 0.075)
                                + ui_widgets.win_h * 0.05
                        } else {
                            (floater.timer as f64 / crate::ecs::sys::floater::HP_SHOWTIME as f64
                                * number_speed)
                                + 100.0
                        };

                        let x = if !precise {
                            0.0
                        } else {
                            (floater.rand as f64 - 0.5) * 0.075 * ui_widgets.win_w
                                + (0.03 * ui_widgets.win_w * (floater.rand as f64 - 0.5).signum())
                        };

                        Text::new(&hp_dmg_text)
                            .font_size(font_size)
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(if floater.info.amount < 0.0 {
                                Color::Rgba(0.0, 0.0, 0.0, fade)
                            } else {
                                Color::Rgba(0.0, 0.0, 0.0, 1.0)
                            })
                            .x_y(x, y - 3.0)
                            .position_ingame(ingame_pos)
                            .set(sct_bg_id, ui_widgets);
                        Text::new(&hp_dmg_text)
                            .font_size(font_size)
                            .font_id(self.fonts.cyri.conrod_id)
                            .x_y(x, y)
                            .color(if floater.info.amount < 0.0 {
                                Color::Rgba(font_col.r, font_col.g, font_col.b, fade)
                            } else {
                                Color::Rgba(0.1, 1.0, 0.1, 1.0)
                            })
                            .position_ingame(ingame_pos)
                            .set(sct_id, ui_widgets);
                    }
                }
            }

            for (pos, bubble) in &self.content_bubbles {
                let overhead_id = overhead_walker.next(
                    &mut self.ids.overheads,
                    &mut ui_widgets.widget_id_generator(),
                );

                overhead::Overhead::new(
                    None,
                    Some(bubble),
                    false,
                    &global_state.settings.interface,
                    self.pulse,
                    i18n,
                    &global_state.settings.controls,
                    &self.imgs,
                    &self.fonts,
                    &global_state.window.key_layout,
                    Vec::new(),
                    &time,
                )
                .x_y(0.0, 100.0)
                .position_ingame(*pos)
                .set(overhead_id, ui_widgets);
            }
        }

        // Display debug window.
        // TODO:
        // Make it use i18n keys.
        if let Some(debug_info) = debug_info {
            prof_span!("debug info");

            const V_PAD: f64 = 5.0;
            const H_PAD: f64 = 5.0;

            // Alpha Version
            Text::new(&version)
                .top_left_with_margins_on(self.ids.debug_bg, V_PAD, H_PAD)
                .font_size(self.fonts.cyri.scale(14))
                .font_id(self.fonts.cyri.conrod_id)
                .color(TEXT_COLOR)
                .set(self.ids.version, ui_widgets);
            // Ticks per second
            Text::new(&format!(
                "FPS: {:.0} ({}ms)",
                debug_info.tps,
                debug_info.frame_time.as_millis()
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.version, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.fps_counter, ui_widgets);
            // Ping
            Text::new(&format!("Ping: {:.0}ms", debug_info.ping_ms))
                .color(TEXT_COLOR)
                .down_from(self.ids.fps_counter, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.ping, ui_widgets);
            // Player's position
            let coordinates_text = match debug_info.coordinates {
                Some(coordinates) => format!(
                    "Coordinates: ({:.0}, {:.0}, {:.0})",
                    coordinates.0.x, coordinates.0.y, coordinates.0.z,
                ),
                None => "Player has no Pos component".to_owned(),
            };
            Text::new(&coordinates_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.ping, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.coordinates, ui_widgets);
            // Player's velocity
            let (velocity_text, glide_ratio_text) = match debug_info.velocity {
                Some(velocity) => {
                    let velocity = velocity.0;
                    let velocity_text = format!(
                        "Velocity: ({:.1}, {:.1}, {:.1}) [{:.1} u/s]",
                        velocity.x,
                        velocity.y,
                        velocity.z,
                        velocity.magnitude()
                    );
                    let horizontal_velocity = velocity.xy().magnitude();
                    let dz = velocity.z;
                    // don't divide by zero
                    let glide_ratio_text = if dz.abs() > 0.0001 {
                        format!("Glide Ratio: {:.1}", (-1.0) * (horizontal_velocity / dz))
                    } else {
                        "Glide Ratio: Altitude is constant".to_owned()
                    };

                    (velocity_text, glide_ratio_text)
                },
                None => {
                    let err = "Player has no Vel component";
                    (err.to_owned(), err.to_owned())
                },
            };
            Text::new(&velocity_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.coordinates, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.velocity, ui_widgets);
            Text::new(&glide_ratio_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.velocity, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.glide_ratio, ui_widgets);
            // Glide Angle of Attack
            let glide_angle_text = angle_of_attack_text(
                debug_info.in_fluid,
                debug_info.velocity,
                debug_info.character_state.as_ref(),
            );
            Text::new(&glide_angle_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.glide_ratio, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.glide_aoe, ui_widgets);
            // Air velocity
            let air_vel_text = air_velocity(debug_info.in_fluid);
            Text::new(&air_vel_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.glide_aoe, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.air_vel, ui_widgets);
            // Player's orientation vector
            let orientation_text = match debug_info.ori {
                Some(ori) => {
                    let orientation = ori.look_dir();
                    format!(
                        "Orientation: ({:.2}, {:.2}, {:.2})",
                        orientation.x, orientation.y, orientation.z,
                    )
                },
                None => "Player has no Ori component".to_owned(),
            };
            Text::new(&orientation_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.air_vel, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.orientation, ui_widgets);
            let look_dir_text = {
                let look_vec = debug_info.look_dir.to_vec();

                format!(
                    "Look Direction: ({:.2}, {:.2}, {:.2})",
                    look_vec.x, look_vec.y, look_vec.z,
                )
            };
            Text::new(&look_dir_text)
                .color(TEXT_COLOR)
                .down_from(self.ids.orientation, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.look_direction, ui_widgets);
            // Loaded distance
            Text::new(&format!(
                "View distance: {:.2} blocks ({:.2} chunks)",
                client.loaded_distance(),
                client.loaded_distance() / TerrainChunk::RECT_SIZE.x as f32,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.look_direction, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.loaded_distance, ui_widgets);
            // Time
            let time_in_seconds = client.state().get_time_of_day();
            let current_time = NaiveTime::from_num_seconds_from_midnight_opt(
                // Wraps around back to 0s if it exceeds 24 hours (24 hours = 86400s)
                (time_in_seconds as u64 % 86400) as u32,
                0,
            )
            .expect("time always valid");
            Text::new(&format!("Time: {}", current_time.format("%H:%M")))
                .color(TEXT_COLOR)
                .down_from(self.ids.loaded_distance, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.time, ui_widgets);
            // Weather
            let weather = client.weather_at_player();
            Text::new(&format!(
                "Weather({kind}): {{cloud: {cloud:.2}, rain: {rain:.2}, wind: <{wind_x:.0}, \
                 {wind_y:.0}>}}",
                kind = weather.get_kind(),
                cloud = weather.cloud,
                rain = weather.rain,
                wind_x = weather.wind.x,
                wind_y = weather.wind.y
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.time, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.weather, ui_widgets);

            // Number of entities
            let entity_count = client.state().ecs().entities().join().count();
            Text::new(&format!("Entity count: {}", entity_count))
                .color(TEXT_COLOR)
                .down_from(self.ids.weather, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.entity_count, ui_widgets);

            // Number of chunks
            Text::new(&format!(
                "Chunks: {} ({} visible) & {} (shadow)",
                debug_info.num_chunks, debug_info.num_visible_chunks, debug_info.num_shadow_chunks,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.entity_count, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.num_chunks, ui_widgets);

            // Type of biome
            Text::new(&format!("Biome: {:?}", client.current_biome()))
                .color(TEXT_COLOR)
                .down_from(self.ids.num_chunks, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.current_biome, ui_widgets);

            // Type of site
            Text::new(&format!("Site: {:?}", client.current_site()))
                .color(TEXT_COLOR)
                .down_from(self.ids.current_biome, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.current_site, ui_widgets);

            // Current song info
            Text::new(&format!(
                "Now playing: {} [{}]",
                debug_info.current_track, debug_info.current_artist,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.current_site, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.song_info, ui_widgets);
            Text::new(&format!(
                "Active channels: M{}, A{}, S{}, U{}",
                debug_info.active_channels.music,
                debug_info.active_channels.ambience,
                debug_info.active_channels.sfx,
                debug_info.active_channels.ui,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.song_info, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.active_channels, ui_widgets);

            // Number of lights
            Text::new(&format!("Lights: {}", debug_info.num_lights,))
                .color(TEXT_COLOR)
                .down_from(self.ids.active_channels, V_PAD)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(14))
                .set(self.ids.num_lights, ui_widgets);

            // Number of figures
            Text::new(&format!(
                "Figures: {} ({} visible)",
                debug_info.num_figures, debug_info.num_figures_visible,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.num_lights, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.num_figures, ui_widgets);

            // Number of particles
            Text::new(&format!(
                "Particles: {} ({} visible)",
                debug_info.num_particles, debug_info.num_particles_visible,
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.num_figures, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.num_particles, ui_widgets);

            // Graphics backend
            Text::new(&format!(
                "Graphics backend: {}",
                global_state.window.renderer().graphics_backend(),
            ))
            .color(TEXT_COLOR)
            .down_from(self.ids.num_particles, V_PAD)
            .font_id(self.fonts.cyri.conrod_id)
            .font_size(self.fonts.cyri.scale(14))
            .set(self.ids.graphics_backend, ui_widgets);

            let gpu_timings = global_state.window.renderer().timings();
            let mut timings_height = 0.0;

            // GPU timing for different pipelines
            if !gpu_timings.is_empty() {
                let num_timings = gpu_timings.len();
                // Make sure we have enough ids
                if self.ids.gpu_timings.len() < num_timings {
                    self.ids
                        .gpu_timings
                        .resize(num_timings, &mut ui_widgets.widget_id_generator());
                }

                for (i, timing) in gpu_timings.iter().enumerate() {
                    let label = timing.1;
                    // We skip displaying these since they aren't present every frame.
                    if label.starts_with(crate::render::UI_PREMULTIPLY_PASS) {
                        continue;
                    }
                    let timings_text =
                        &format!("{:16}{:.3} ms", &format!("{label}:"), timing.2 * 1000.0,);
                    let timings_widget = Text::new(timings_text)
                        .color(TEXT_COLOR)
                        .down(V_PAD)
                        .x_place_on(
                            self.ids.debug_bg,
                            conrod_core::position::Place::Start(Some(
                                H_PAD + 10.0 * timing.0 as f64,
                            )),
                        )
                        .font_id(self.fonts.cyri.conrod_id)
                        .font_size(self.fonts.cyri.scale(14));

                    // Calculate timings height
                    timings_height += timings_widget.get_h(ui_widgets).unwrap_or(0.0) + V_PAD;

                    timings_widget.set(self.ids.gpu_timings[i], ui_widgets);
                }
            }

            // Set debug box dimensions, only timings height is dynamic
            // TODO: Make the background box size fully dynamic

            let debug_bg_size = [375.0, 405.0 + timings_height];

            Rectangle::fill(debug_bg_size)
                .rgba(0.0, 0.0, 0.0, global_state.settings.chat.chat_opacity)
                .top_left_with_margins_on(ui_widgets.window, 10.0, 10.0)
                .set(self.ids.debug_bg, ui_widgets);
        }

        if global_state.settings.interface.toggle_hotkey_hints {
            // Controls, Keybindings
            if let Some(help_key) = global_state
                .settings
                .controls
                .get_binding(GameInput::Controls)
            {
                Text::new(&i18n.get_msg_ctx(
                    "hud-press_key_to_show_keybindings_fmt",
                    &i18n::fluent_args! {
                        "key" => help_key.display_string(key_layout),
                    },
                ))
                .color(TEXT_COLOR)
                .bottom_left_with_margins_on(ui_widgets.window, 210.0, 10.0)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(12))
                .set(self.ids.help_info, ui_widgets);
            }
            // Lantern Key
            if let Some(toggle_lantern_key) = global_state
                .settings
                .controls
                .get_binding(GameInput::ToggleLantern)
            {
                Text::new(&i18n.get_msg_ctx(
                    "hud-press_key_to_toggle_lantern_fmt",
                    &i18n::fluent_args! {
                        "key" => toggle_lantern_key.display_string(key_layout),
                    },
                ))
                .color(TEXT_COLOR)
                .up_from(self.ids.help_info, 2.0)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(12))
                .set(self.ids.lantern_info, ui_widgets);
            }
        }

        // Bag button and nearby icons
        let ecs = client.state().ecs();
        // let entity = info.viewpoint_entity;
        let stats = ecs.read_storage::<comp::Stats>();
        let skill_sets = ecs.read_storage::<comp::SkillSet>();
        let buffs = ecs.read_storage::<comp::Buffs>();
        let msm = ecs.read_resource::<MaterialStatManifest>();
        let time = ecs.read_resource::<Time>();

        match Buttons::new(
            &self.imgs,
            &self.fonts,
            global_state,
            &self.rot_imgs,
            tooltip_manager,
            i18n,
        )
        .set(self.ids.buttons, ui_widgets)
        {
            Some(buttons::Event::ToggleSettings) => self.show.toggle_settings(global_state),
            Some(buttons::Event::ToggleSocial) => self.show.toggle_social(),
            Some(buttons::Event::ToggleMap) => self.show.toggle_map(),
            Some(buttons::Event::ToggleCrafting) => self.show.toggle_crafting(),
            None => {},
        }

        // Group Window
        for event in Group::new(
            &mut self.show,
            client,
            &global_state.settings,
            &self.imgs,
            &self.rot_imgs,
            &self.fonts,
            i18n,
            self.pulse,
            global_state,
            tooltip_manager,
            &msm,
            &time,
        )
        .set(self.ids.group_window, ui_widgets)
        {
            match event {
                group::Event::Accept => events.push(Event::AcceptInvite),
                group::Event::Decline => events.push(Event::DeclineInvite),
                group::Event::Kick(uid) => events.push(Event::KickMember(uid)),
                group::Event::LeaveGroup => events.push(Event::LeaveGroup),
                group::Event::AssignLeader(uid) => events.push(Event::AssignLeader(uid)),
            }
        }
        // Popup (waypoint saved and similar notifications)
        Popup::new(
            i18n,
            client,
            &self.new_notifications,
            &self.fonts,
            &self.show,
        )
        .set(self.ids.popup, ui_widgets);

        // MiniMap
        for event in MiniMap::new(
            client,
            &self.imgs,
            &self.rot_imgs,
            &self.world_map,
            &self.fonts,
            camera.get_orientation(),
            global_state,
            &self.show.location_markers,
            &self.voxel_minimap,
        )
        .set(self.ids.minimap, ui_widgets)
        {
            match event {
                minimap::Event::SettingsChange(interface_change) => {
                    events.push(Event::SettingsChange(interface_change.into()));
                },
            }
        }

        if let Some(prompt_dialog_settings) = &self.show.prompt_dialog {
            // Prompt Dialog
            match PromptDialog::new(
                &self.imgs,
                &self.fonts,
                &global_state.i18n,
                &global_state.settings,
                prompt_dialog_settings,
                &global_state.window.key_layout,
            )
            .set(self.ids.prompt_dialog, ui_widgets)
            {
                Some(dialog_outcome_event) => {
                    match dialog_outcome_event {
                        DialogOutcomeEvent::Affirmative(event) => events.push(event),
                        DialogOutcomeEvent::Negative(event) => {
                            if let Some(event) = event {
                                events.push(event);
                            };
                        },
                    };

                    // Close the prompt dialog once an option has been chosen
                    self.show.prompt_dialog = None;
                },
                None => {},
            }
        }

        // Skillbar
        // Get player stats
        let ecs = client.state().ecs();
        let entity = info.viewpoint_entity;
        let healths = ecs.read_storage::<Health>();
        let inventories = ecs.read_storage::<comp::Inventory>();
        let rbm = ecs.read_resource::<RecipeBookManifest>();
        let energies = ecs.read_storage::<comp::Energy>();
        let skillsets = ecs.read_storage::<comp::SkillSet>();
        let active_abilities = ecs.read_storage::<comp::ActiveAbilities>();
        let bodies = ecs.read_storage::<comp::Body>();
        let poises = ecs.read_storage::<comp::Poise>();
        let combos = ecs.read_storage::<comp::Combo>();
        let combo = combos.get(entity);
        let time = ecs.read_resource::<Time>();
        let stances = ecs.read_storage::<comp::Stance>();
        let char_states = ecs.read_storage::<comp::CharacterState>();
        // Combo floater stuffs
        self.floaters.combo_floater = self.floaters.combo_floater.map(|mut f| {
            f.timer -= dt.as_secs_f64();
            f
        });
        self.floaters.combo_floater = self.floaters.combo_floater.filter(|f| f.timer > 0_f64);

        if let (
            Some(health),
            Some(inventory),
            Some(energy),
            Some(poise),
            Some(skillset),
            Some(body),
        ) = (
            healths.get(entity),
            inventories.get(entity),
            energies.get(entity),
            poises.get(entity),
            skillsets.get(entity),
            bodies.get(entity),
        ) {
            let stance = stances.get(entity);
            let context = AbilityContext::from(stance, Some(inventory), combo);
            match Skillbar::new(
                client,
                &info,
                global_state,
                &self.imgs,
                &self.item_imgs,
                &self.fonts,
                &self.rot_imgs,
                health,
                inventory,
                energy,
                poise,
                skillset,
                active_abilities.get(entity),
                body,
                //&character_state,
                self.pulse,
                //&controller,
                &self.hotbar,
                tooltip_manager,
                item_tooltip_manager,
                &mut self.slot_manager,
                i18n,
                &self.item_i18n,
                &msm,
                &rbm,
                self.floaters.combo_floater,
                &context,
                combo,
                char_states.get(entity),
                stance,
                stats.get(entity),
            )
            .set(self.ids.skillbar, ui_widgets)
            {
                Some(skillbar::Event::OpenDiary(skillgroup)) => {
                    self.show.diary(true);
                    self.show.open_skill_tree(skillgroup);
                },
                Some(skillbar::Event::OpenBag) => self.show.bag(!self.show.bag),
                None => {},
            }
        }
        // Bag contents
        if self.show.bag {
            if let (
                Some(player_stats),
                Some(skill_set),
                Some(health),
                Some(energy),
                Some(body),
                Some(poise),
            ) = (
                stats.get(info.viewpoint_entity),
                skill_sets.get(info.viewpoint_entity),
                healths.get(entity),
                energies.get(entity),
                bodies.get(entity),
                poises.get(entity),
            ) {
                match Bag::new(
                    client,
                    &info,
                    global_state,
                    &self.imgs,
                    &self.item_imgs,
                    &self.fonts,
                    &self.rot_imgs,
                    tooltip_manager,
                    item_tooltip_manager,
                    &mut self.slot_manager,
                    self.pulse,
                    i18n,
                    &self.item_i18n,
                    player_stats,
                    skill_set,
                    health,
                    energy,
                    &self.show,
                    body,
                    &msm,
                    &rbm,
                    poise,
                )
                .set(self.ids.bag, ui_widgets)
                {
                    Some(bag::Event::BagExpand) => self.show.bag_inv = !self.show.bag_inv,
                    Some(bag::Event::SetDetailsMode(mode)) => self.show.bag_details = mode,
                    Some(bag::Event::Close) => {
                        self.show.stats = false;
                        Self::show_bag(&mut self.slot_manager, &mut self.show, false);
                        if !self.show.social {
                            self.show.want_grab = true;
                            self.force_ungrab = false;
                        } else {
                            self.force_ungrab = true
                        };
                    },
                    Some(bag::Event::SortInventory) => self.events.push(Event::SortInventory),
                    Some(bag::Event::SwapEquippedWeapons) => {
                        self.events.push(Event::SwapEquippedWeapons)
                    },
                    None => {},
                }
            }
        }
        // Trade window
        if self.show.trade {
            if let Some(action) = Trade::new(
                client,
                &info,
                &self.imgs,
                &self.item_imgs,
                &self.fonts,
                &self.rot_imgs,
                tooltip_manager,
                item_tooltip_manager,
                &mut self.slot_manager,
                i18n,
                &self.item_i18n,
                &msm,
                &rbm,
                self.pulse,
                &mut self.show,
            )
            .set(self.ids.trade, ui_widgets)
            {
                match action {
                    trade::TradeEvent::HudUpdate(update) => match update {
                        trade::HudUpdate::Focus(idx) => self.to_focus = Some(Some(idx)),
                        trade::HudUpdate::Submit => {
                            let key = self.show.trade_amount_input_key.take();
                            key.map(|k| {
                                k.submit_action.map(|action| {
                                    self.events.push(Event::TradeAction(action));
                                });
                            });
                        },
                    },
                    trade::TradeEvent::TradeAction(action) => {
                        if let TradeAction::Decline = action {
                            self.show.stats = false;
                            self.show.trade(false);
                            if !self.show.social {
                                self.show.want_grab = true;
                                self.force_ungrab = false;
                            } else {
                                self.force_ungrab = true
                            };
                            self.show.prompt_dialog = None;
                        }
                        events.push(Event::TradeAction(action));
                    },
                    trade::TradeEvent::SetDetailsMode(mode) => {
                        self.show.trade_details = mode;
                    },
                    trade::TradeEvent::ShowPrompt(prompt) => {
                        self.show.prompt_dialog = Some(prompt);
                    },
                }
            }
        }

        // Buffs
        if let (Some(player_buffs), Some(health), Some(energy)) = (
            buffs.get(info.viewpoint_entity),
            healths.get(entity),
            energies.get(entity),
        ) {
            for event in BuffsBar::new(
                &self.imgs,
                &self.fonts,
                &self.rot_imgs,
                tooltip_manager,
                i18n,
                player_buffs,
                stances.get(entity),
                self.pulse,
                global_state,
                health,
                energy,
                &time,
            )
            .set(self.ids.buffs, ui_widgets)
            {
                match event {
                    buffs::Event::RemoveBuff(buff_id) => events.push(Event::RemoveBuff(buff_id)),
                    buffs::Event::LeaveStance => events.push(Event::LeaveStance),
                }
            }
        }
        // Crafting
        if self.show.crafting {
            if let Some(inventory) = inventories.get(entity) {
                for event in Crafting::new(
                    //&self.show,
                    client,
                    &info,
                    &self.imgs,
                    &self.fonts,
                    i18n,
                    &self.item_i18n,
                    self.pulse,
                    &self.rot_imgs,
                    item_tooltip_manager,
                    &mut self.slot_manager,
                    &self.item_imgs,
                    inventory,
                    &rbm,
                    &msm,
                    tooltip_manager,
                    &mut self.show,
                    &global_state.settings,
                )
                .set(self.ids.crafting_window, ui_widgets)
                {
                    match event {
                        crafting::Event::CraftRecipe {
                            recipe_name,
                            amount,
                        } => {
                            events.push(Event::CraftRecipe {
                                recipe_name,
                                craft_sprite: self.show.crafting_fields.craft_sprite,
                                amount,
                            });
                        },
                        crafting::Event::CraftModularWeapon {
                            primary_slot,
                            secondary_slot,
                        } => {
                            events.push(Event::CraftModularWeapon {
                                primary_slot,
                                secondary_slot,
                                craft_sprite: self
                                    .show
                                    .crafting_fields
                                    .craft_sprite
                                    .map(|(pos, _sprite)| pos),
                            });
                        },
                        crafting::Event::CraftModularWeaponComponent {
                            toolkind,
                            material,
                            modifier,
                        } => {
                            events.push(Event::CraftModularWeaponComponent {
                                toolkind,
                                material,
                                modifier,
                                craft_sprite: self
                                    .show
                                    .crafting_fields
                                    .craft_sprite
                                    .map(|(pos, _sprite)| pos),
                            });
                        },
                        crafting::Event::Close => {
                            self.show.stats = false;
                            self.show.crafting(false);
                            if !self.show.social {
                                self.show.want_grab = true;
                                self.force_ungrab = false;
                            } else {
                                self.force_ungrab = true
                            };
                        },
                        crafting::Event::ChangeCraftingTab(sel_cat) => {
                            self.show.open_crafting_tab(sel_cat, None);
                        },
                        crafting::Event::Focus(widget_id) => {
                            self.to_focus = Some(Some(widget_id));
                        },
                        crafting::Event::SearchRecipe(search_key) => {
                            self.show.search_crafting_recipe(search_key);
                        },
                        crafting::Event::ClearRecipeInputs => {
                            self.show.crafting_fields.recipe_inputs.clear();
                        },
                        crafting::Event::RepairItem { slot } => {
                            if let Some(sprite_pos) = self
                                .show
                                .crafting_fields
                                .craft_sprite
                                .map(|(pos, _sprite)| pos)
                            {
                                events.push(Event::RepairItem {
                                    item: slot,
                                    sprite_pos,
                                });
                            }
                        },
                        crafting::Event::ShowAllRecipes(show) => {
                            events.push(Event::SettingsChange(SettingsChange::Gameplay(
                                crate::session::settings_change::Gameplay::ChangeShowAllRecipes(
                                    show,
                                ),
                            )));
                        },
                    }
                }
            }
        }

        if global_state.settings.audio.subtitles {
            Subtitles::new(
                client,
                &global_state.settings,
                global_state.audio.get_listener_pos(),
                global_state.audio.get_listener_ori(),
                &mut global_state.audio.subtitles,
                &self.fonts,
                i18n,
            )
            .set(self.ids.subtitles, ui_widgets);
        }

        //Loot
        LootScroller::new(
            &mut self.new_loot_messages,
            client,
            &info,
            &self.show,
            &self.imgs,
            &self.item_imgs,
            &self.rot_imgs,
            &self.fonts,
            i18n,
            &self.item_i18n,
            &msm,
            &rbm,
            item_tooltip_manager,
            self.pulse,
        )
        .set(self.ids.loot_scroller, ui_widgets);

        self.new_loot_messages.clear();

        // Don't put NPC messages in chat box.
        self.new_messages
            .retain(|m| !matches!(m.chat_type, comp::ChatType::Npc(_)));

        // Chat box
        // Draw this after loot scroller and subtitles so it can be dragged
        // even when hovering over them
        // TODO look into parenting and then settings movable widgets to floating
        if global_state.settings.interface.toggle_chat || self.force_chat {
            for hidden in self.message_backlog.drain(..).rev() {
                self.new_messages.push_front(hidden);
            }
            for event in Chat::new(
                &mut self.new_messages,
                client,
                global_state,
                self.pulse,
                &self.imgs,
                &self.fonts,
                i18n,
                scale,
                self.clear_chat,
            )
            .and_then(self.force_chat_input.take(), |c, input| c.input(input))
            .and_then(self.tab_complete.take(), |c, input| {
                c.prepare_tab_completion(input)
            })
            .and_then(self.force_chat_cursor.take(), |c, pos| c.cursor_pos(pos))
            .set(self.ids.chat, ui_widgets)
            {
                match event {
                    chat::Event::TabCompletionStart(input) => {
                        self.tab_complete = Some(input);
                    },
                    chat::Event::SendMessage(message) => {
                        events.push(Event::SendMessage(message));
                    },
                    chat::Event::SendCommand(name, args) => {
                        events.push(Event::SendCommand(name, args));
                    },
                    chat::Event::Focus(focus_id) => {
                        self.to_focus = Some(Some(focus_id));
                    },
                    chat::Event::ChangeChatTab(tab) => {
                        events.push(Event::SettingsChange(ChatChange::ChangeChatTab(tab).into()));
                    },
                    chat::Event::ShowChatTabSettings(tab) => {
                        self.show.chat_tab_settings_index = Some(tab);
                        self.show.settings_tab = SettingsTab::Chat;
                        self.show.settings(true);
                    },
                    chat::Event::ResizeChat(size) => {
                        global_state.settings.chat.chat_size_x = size.x;
                        global_state.settings.chat.chat_size_y = size.y;
                    },
                    chat::Event::MoveChat(pos) => {
                        global_state.settings.chat.chat_pos_x = pos.x;
                        global_state.settings.chat.chat_pos_y = pos.y;
                    },
                    chat::Event::DisableForceChat => {
                        self.force_chat = false;
                    },
                }
            }
        } else {
            self.message_backlog.extend(self.new_messages.drain(..));
            while self.message_backlog.len() > chat::MAX_MESSAGES {
                self.message_backlog.pop_front();
            }
        }

        self.new_messages.clear();
        self.new_notifications.clear();
        self.clear_chat = false;

        // Windows

        // Char Window will always appear at the left side. Other Windows default to the
        // left side, but when the Char Window is opened they will appear to the right
        // of it.

        // Settings
        if let Windows::Settings = self.show.open_windows {
            for event in SettingsWindow::new(
                global_state,
                &self.show,
                &self.imgs,
                &self.fonts,
                i18n,
                client.server_view_distance_limit(),
                fps as f32,
            )
            .set(self.ids.settings_window, ui_widgets)
            {
                match event {
                    settings_window::Event::ChangeTab(tab) => self.show.open_setting_tab(tab),
                    settings_window::Event::Close => {
                        // Unpause the game if we are on singleplayer so that we can logout
                        #[cfg(feature = "singleplayer")]
                        global_state.unpause();
                        self.show.want_grab = true;
                        self.force_ungrab = false;

                        self.show.settings(false)
                    },
                    settings_window::Event::ChangeChatSettingsTab(tab) => {
                        self.show.chat_tab_settings_index = tab;
                    },
                    settings_window::Event::SettingsChange(settings_change) => {
                        events.push(Event::SettingsChange(settings_change));
                    },
                }
            }
        }
        // Quest Window
        let stats = client.state().ecs().read_storage::<comp::Stats>();
        if self.show.quest {
            if let Some(stats) = stats.get(entity) {
                match Quest::new(
                    &self.show,
                    client,
                    &self.imgs,
                    &self.fonts,
                    i18n,
                    &self.rot_imgs,
                    tooltip_manager,
                    stats,
                    &self.item_imgs,
                    self.pulse,
                )
                .set(self.ids.quest_window, ui_widgets)
                {
                    Some(quest::Event::Close) => {
                        self.show.quest(false);
                        if !self.show.bag {
                            self.show.want_grab = true;
                            self.force_ungrab = false;
                        } else {
                            self.force_ungrab = true
                        };
                    },
                    None => {},
                }
            }
        }

        // Social Window
        if self.show.social {
            let ecs = client.state().ecs();
            let _stats = ecs.read_storage::<comp::Stats>();
            for event in Social::new(
                &self.show,
                client,
                &self.imgs,
                &self.fonts,
                i18n,
                info.selected_entity,
                &self.rot_imgs,
                tooltip_manager,
            )
            .set(self.ids.social_window, ui_widgets)
            {
                match event {
                    social::Event::Close => {
                        self.show.social(false);
                        if !self.show.bag {
                            self.show.want_grab = true;
                            self.force_ungrab = false;
                        } else {
                            self.force_ungrab = true
                        };
                    },
                    social::Event::Focus(widget_id) => {
                        self.to_focus = Some(Some(widget_id));
                    },
                    social::Event::Invite(uid) => events.push(Event::InviteMember(uid)),
                    social::Event::SearchPlayers(search_key) => {
                        self.show.search_social_players(search_key)
                    },
                }
            }
        }

        // Diary
        if self.show.diary {
            let entity = info.viewpoint_entity;
            let skill_sets = ecs.read_storage::<comp::SkillSet>();
            if let (
                Some(skill_set),
                Some(inventory),
                Some(char_state),
                Some(health),
                Some(energy),
                Some(body),
                Some(poise),
            ) = (
                skill_sets.get(entity),
                inventories.get(entity),
                char_states.get(entity),
                healths.get(entity),
                energies.get(entity),
                bodies.get(entity),
                poises.get(entity),
            ) {
                let context = AbilityContext::from(stances.get(entity), Some(inventory), combo);
                for event in Diary::new(
                    &self.show,
                    client,
                    global_state,
                    skill_set,
                    active_abilities.get(entity).unwrap_or(&Default::default()),
                    inventory,
                    char_state,
                    health,
                    energy,
                    poise,
                    body,
                    &msm,
                    &self.imgs,
                    &self.item_imgs,
                    &self.fonts,
                    i18n,
                    &self.item_i18n,
                    &self.rot_imgs,
                    tooltip_manager,
                    &mut self.slot_manager,
                    self.pulse,
                    &context,
                    stats.get(entity),
                )
                .set(self.ids.diary, ui_widgets)
                {
                    match event {
                        diary::Event::Close => {
                            self.show.diary(false);
                            self.show.want_grab = true;
                            self.force_ungrab = false;
                        },
                        diary::Event::ChangeSkillTree(tree_sel) => {
                            self.show.open_skill_tree(tree_sel)
                        },
                        diary::Event::UnlockSkill(skill) => events.push(Event::UnlockSkill(skill)),
                        diary::Event::ChangeSection(section) => {
                            self.show.diary_fields.section = section;
                        },
                        diary::Event::SelectExpBar(xp_bar) => {
                            events.push(Event::SelectExpBar(xp_bar))
                        },
                    }
                }
            }
        }
        // Map
        if self.show.map {
            for event in Map::new(
                client,
                &self.imgs,
                &self.rot_imgs,
                &self.world_map,
                &self.fonts,
                self.pulse,
                i18n,
                global_state,
                tooltip_manager,
                &self.show.location_markers,
                self.map_drag,
            )
            .set(self.ids.map, ui_widgets)
            {
                match event {
                    map::Event::Close => {
                        self.show.map(false);
                        self.show.want_grab = true;
                        self.force_ungrab = false;
                    },
                    map::Event::SettingsChange(settings_change) => {
                        events.push(Event::SettingsChange(settings_change.into()));
                    },
                    map::Event::RequestSiteInfo(id) => {
                        events.push(Event::RequestSiteInfo(id));
                    },
                    map::Event::SetLocationMarker(pos) => {
                        events.push(Event::MapMarkerEvent(MapMarkerChange::Update(pos)));
                        self.show.location_markers.owned = Some(pos);
                    },
                    map::Event::MapDrag(new_drag) => {
                        self.map_drag = new_drag;
                    },
                    map::Event::RemoveMarker => {
                        self.show.location_markers.owned = None;
                        events.push(Event::MapMarkerEvent(MapMarkerChange::Remove));
                    },
                }
            }
        } else {
            // Reset the map position when it's not showing
            self.map_drag = Vec2::zero();
        }

        if self.show.esc_menu {
            match EscMenu::new(&self.imgs, &self.fonts, i18n).set(self.ids.esc_menu, ui_widgets) {
                Some(esc_menu::Event::OpenSettings(tab)) => {
                    self.show.open_setting_tab(tab);
                },
                Some(esc_menu::Event::Close) => {
                    self.show.esc_menu = false;
                    self.show.want_grab = true;
                    self.force_ungrab = false;

                    // Unpause the game if we are on singleplayer
                    #[cfg(feature = "singleplayer")]
                    global_state.unpause();
                },
                Some(esc_menu::Event::Logout) => {
                    // Unpause the game if we are on singleplayer so that we can logout
                    #[cfg(feature = "singleplayer")]
                    global_state.unpause();

                    events.push(Event::Logout);
                },
                Some(esc_menu::Event::Quit) => events.push(Event::Quit),
                Some(esc_menu::Event::CharacterSelection) => {
                    // Unpause the game if we are on singleplayer so that we can logout
                    #[cfg(feature = "singleplayer")]
                    global_state.unpause();

                    events.push(Event::CharacterSelection)
                },
                None => {},
            }
        }

        let mut indicator_offset = 40.0;

        // Free look indicator
        if let Some(freelook_key) = global_state
            .settings
            .controls
            .get_binding(GameInput::FreeLook)
        {
            if self.show.free_look {
                let msg = i18n.get_msg_ctx("hud-free_look_indicator", &i18n::fluent_args! {
                    "key" => freelook_key.display_string(key_layout),
                });
                Text::new(&msg)
                    .color(TEXT_BG)
                    .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
                    .font_id(self.fonts.cyri.conrod_id)
                    .font_size(self.fonts.cyri.scale(20))
                    .set(self.ids.free_look_bg, ui_widgets);
                indicator_offset += 30.0;
                Text::new(&msg)
                    .color(KILL_COLOR)
                    .top_left_with_margins_on(self.ids.free_look_bg, -1.0, -1.0)
                    .font_id(self.fonts.cyri.conrod_id)
                    .font_size(self.fonts.cyri.scale(20))
                    .set(self.ids.free_look_txt, ui_widgets);
            }
        };

        // Auto walk indicator
        if self.show.auto_walk {
            Text::new(&i18n.get_msg("hud-auto_walk_indicator"))
                .color(TEXT_BG)
                .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(20))
                .set(self.ids.auto_walk_bg, ui_widgets);
            indicator_offset += 30.0;
            Text::new(&i18n.get_msg("hud-auto_walk_indicator"))
                .color(KILL_COLOR)
                .top_left_with_margins_on(self.ids.auto_walk_bg, -1.0, -1.0)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(20))
                .set(self.ids.auto_walk_txt, ui_widgets);
        }

        // Camera zoom lock
        self.show.zoom_lock.update(dt);

        if let Some(zoom_lock) = self.show.zoom_lock.reason {
            let zoom_lock_message = match zoom_lock {
                NotificationReason::Remind => "hud-zoom_lock_indicator-remind",
                NotificationReason::Enable => "hud-zoom_lock_indicator-enable",
                NotificationReason::Disable => "hud-zoom_lock_indicator-disable",
            };

            Text::new(&i18n.get_msg(zoom_lock_message))
                .color(TEXT_BG.alpha(self.show.zoom_lock.alpha))
                .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(20))
                .set(self.ids.zoom_lock_bg, ui_widgets);
            indicator_offset += 30.0;
            Text::new(&i18n.get_msg(zoom_lock_message))
                .color(TEXT_COLOR.alpha(self.show.zoom_lock.alpha))
                .top_left_with_margins_on(self.ids.zoom_lock_bg, -1.0, -1.0)
                .font_id(self.fonts.cyri.conrod_id)
                .font_size(self.fonts.cyri.scale(20))
                .set(self.ids.zoom_lock_txt, ui_widgets);
        }

        // Camera clamp indicator
        if let Some(cameraclamp_key) = global_state
            .settings
            .controls
            .get_binding(GameInput::CameraClamp)
        {
            if self.show.camera_clamp {
                let msg = i18n.get_msg_ctx("hud-camera_clamp_indicator", &i18n::fluent_args! {
                    "key" => cameraclamp_key.display_string(key_layout),
                });
                Text::new(&msg)
                    .color(TEXT_BG)
                    .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
                    .font_id(self.fonts.cyri.conrod_id)
                    .font_size(self.fonts.cyri.scale(20))
                    .set(self.ids.camera_clamp_bg, ui_widgets);
                Text::new(&msg)
                    .color(KILL_COLOR)
                    .top_left_with_margins_on(self.ids.camera_clamp_bg, -1.0, -1.0)
                    .font_id(self.fonts.cyri.conrod_id)
                    .font_size(self.fonts.cyri.scale(20))
                    .set(self.ids.camera_clamp_txt, ui_widgets);
            }
        }

        // Maintain slot manager
        'slot_events: for event in self.slot_manager.maintain(ui_widgets) {
            use slots::{AbilitySlot, InventorySlot, SlotKind::*};
            let to_slot = |slot_kind| match slot_kind {
                Inventory(
                    i @ InventorySlot {
                        slot: Slot::Inventory(_) | Slot::Overflow(_),
                        ours: true,
                        ..
                    },
                ) => Some(i.slot),
                Inventory(InventorySlot {
                    slot: Slot::Equip(_),
                    ours: true,
                    ..
                }) => None,
                Inventory(InventorySlot { ours: false, .. }) => None,
                Equip(e) => Some(Slot::Equip(e)),
                Hotbar(_) => None,
                Trade(_) => None,
                Ability(_) => None,
                Crafting(_) => None,
            };
            match event {
                slot::Event::Dragged(a, b) => {
                    // Swap between slots
                    if let (Some(a), Some(b)) = (to_slot(a), to_slot(b)) {
                        events.push(Event::SwapSlots {
                            slot_a: a,
                            slot_b: b,
                            bypass_dialog: false,
                        });
                    } else if let (
                        Inventory(InventorySlot {
                            slot, ours: true, ..
                        }),
                        Hotbar(h),
                    ) = (a, b)
                    {
                        if let Slot::Inventory(slot) = slot {
                            if let Some(item) = inventories
                                .get(info.viewpoint_entity)
                                .and_then(|inv| inv.get(slot))
                            {
                                self.hotbar.add_inventory_link(h, item);
                                events.push(Event::ChangeHotbarState(Box::new(
                                    self.hotbar.to_owned(),
                                )));
                            }
                        }
                    } else if let (Hotbar(a), Hotbar(b)) = (a, b) {
                        self.hotbar.swap(a, b);
                        events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
                    } else if let (Inventory(i), Trade(t)) = (a, b) {
                        if i.ours == t.ours {
                            if let (Some(inventory), Slot::Inventory(slot)) =
                                (inventories.get(t.entity), i.slot)
                            {
                                events.push(Event::TradeAction(TradeAction::AddItem {
                                    item: slot,
                                    quantity: i.amount(inventory).unwrap_or(1),
                                    ours: i.ours,
                                }));
                            }
                        }
                    } else if let (Trade(t), Inventory(i)) = (a, b) {
                        if i.ours == t.ours {
                            if let Some(inventory) = inventories.get(t.entity) {
                                if let Some(invslot) = t.invslot {
                                    events.push(Event::TradeAction(TradeAction::RemoveItem {
                                        item: invslot,
                                        quantity: t.amount(inventory).unwrap_or(1),
                                        ours: t.ours,
                                    }));
                                }
                            }
                        }
                    } else if let (Ability(a), Ability(b)) = (a, b) {
                        match (a, b) {
                            (AbilitySlot::Ability(ability), AbilitySlot::Slot(index)) => {
                                events.push(Event::ChangeAbility(index, ability));
                            },
                            (AbilitySlot::Slot(a), AbilitySlot::Slot(b)) => {
                                let me = info.viewpoint_entity;
                                if let Some(active_abilities) = active_abilities.get(me) {
                                    let ability_a = active_abilities
                                        .auxiliary_set(inventories.get(me), skill_sets.get(me))
                                        .get(a)
                                        .copied()
                                        .unwrap_or(AuxiliaryAbility::Empty);
                                    let ability_b = active_abilities
                                        .auxiliary_set(inventories.get(me), skill_sets.get(me))
                                        .get(b)
                                        .copied()
                                        .unwrap_or(AuxiliaryAbility::Empty);
                                    events.push(Event::ChangeAbility(a, ability_b));
                                    events.push(Event::ChangeAbility(b, ability_a));
                                }
                            },
                            (AbilitySlot::Slot(index), _) => {
                                events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
                            },
                            (AbilitySlot::Ability(_), AbilitySlot::Ability(_)) => {},
                        }
                    } else if let (Inventory(i), Crafting(c)) = (a, b) {
                        if let Slot::Inventory(slot) = i.slot {
                            // Add item to crafting input
                            if inventories
                                .get(info.viewpoint_entity)
                                .and_then(|inv| inv.get(slot))
                                .map_or(false, |item| {
                                    (c.requirement)(item, client.component_recipe_book(), c.info)
                                })
                            {
                                self.show
                                    .crafting_fields
                                    .recipe_inputs
                                    .insert(c.index, i.slot);
                            }
                        }
                    } else if let (Equip(e), Crafting(c)) = (a, b) {
                        // Add item to crafting input
                        if inventories
                            .get(client.entity())
                            .and_then(|inv| inv.equipped(e))
                            .map_or(false, |item| {
                                (c.requirement)(item, client.component_recipe_book(), c.info)
                            })
                        {
                            self.show
                                .crafting_fields
                                .recipe_inputs
                                .insert(c.index, Slot::Equip(e));
                        }
                    } else if let (Crafting(c), Inventory(_)) = (a, b) {
                        // Remove item from crafting input
                        self.show.crafting_fields.recipe_inputs.remove(&c.index);
                    } else if let (Ability(AbilitySlot::Ability(ability)), Hotbar(slot)) = (a, b) {
                        if let Some(Some(HotbarSlotContents::Ability(index))) =
                            self.hotbar.slots.get(slot as usize)
                        {
                            events.push(Event::ChangeAbility(*index, ability));
                        }
                    }
                },
                slot::Event::Dropped(from) => {
                    // Drop item
                    if let Some(from) = to_slot(from) {
                        events.push(Event::DropSlot(from));
                    } else if let Hotbar(h) = from {
                        self.hotbar.clear_slot(h);
                        events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
                    } else if let Trade(t) = from {
                        if let Some(inventory) = inventories.get(t.entity) {
                            if let Some(invslot) = t.invslot {
                                events.push(Event::TradeAction(TradeAction::RemoveItem {
                                    item: invslot,
                                    quantity: t.amount(inventory).unwrap_or(1),
                                    ours: t.ours,
                                }));
                            }
                        }
                    } else if let Ability(AbilitySlot::Slot(index)) = from {
                        events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
                    } else if let Crafting(c) = from {
                        // Remove item from crafting input
                        self.show.crafting_fields.recipe_inputs.remove(&c.index);
                    }
                },
                slot::Event::SplitDropped(from) => {
                    // Drop item
                    if let Some(from) = to_slot(from) {
                        events.push(Event::SplitDropSlot(from));
                    } else if let Hotbar(h) = from {
                        self.hotbar.clear_slot(h);
                        events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
                    } else if let Ability(AbilitySlot::Slot(index)) = from {
                        events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
                    }
                },
                slot::Event::SplitDragged(a, b) => {
                    // Swap between slots
                    if let (Some(a), Some(b)) = (to_slot(a), to_slot(b)) {
                        events.push(Event::SplitSwapSlots {
                            slot_a: a,
                            slot_b: b,
                            bypass_dialog: false,
                        });
                    } else if let (Inventory(i), Hotbar(h)) = (a, b) {
                        if let Slot::Inventory(slot) = i.slot {
                            if let Some(item) = inventories
                                .get(info.viewpoint_entity)
                                .and_then(|inv| inv.get(slot))
                            {
                                self.hotbar.add_inventory_link(h, item);
                                events.push(Event::ChangeHotbarState(Box::new(
                                    self.hotbar.to_owned(),
                                )));
                            }
                        }
                    } else if let (Hotbar(a), Hotbar(b)) = (a, b) {
                        self.hotbar.swap(a, b);
                        events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
                    } else if let (Inventory(i), Trade(t)) = (a, b) {
                        if i.ours == t.ours {
                            if let (Some(inventory), Slot::Inventory(slot)) =
                                (inventories.get(t.entity), i.slot)
                            {
                                events.push(Event::TradeAction(TradeAction::AddItem {
                                    item: slot,
                                    quantity: i.amount(inventory).unwrap_or(1) / 2,
                                    ours: i.ours,
                                }));
                            }
                        }
                    } else if let (Trade(t), Inventory(i)) = (a, b) {
                        if i.ours == t.ours {
                            if let Some(inventory) = inventories.get(t.entity) {
                                if let Some(invslot) = t.invslot {
                                    events.push(Event::TradeAction(TradeAction::RemoveItem {
                                        item: invslot,
                                        quantity: t.amount(inventory).unwrap_or(1) / 2,
                                        ours: t.ours,
                                    }));
                                }
                            }
                        }
                    } else if let (Ability(a), Ability(b)) = (a, b) {
                        match (a, b) {
                            (AbilitySlot::Ability(ability), AbilitySlot::Slot(index)) => {
                                events.push(Event::ChangeAbility(index, ability));
                            },
                            (AbilitySlot::Slot(a), AbilitySlot::Slot(b)) => {
                                let me = info.viewpoint_entity;
                                if let Some(active_abilities) = active_abilities.get(me) {
                                    let ability_a = active_abilities
                                        .auxiliary_set(inventories.get(me), skill_sets.get(me))
                                        .get(a)
                                        .copied()
                                        .unwrap_or(AuxiliaryAbility::Empty);
                                    let ability_b = active_abilities
                                        .auxiliary_set(inventories.get(me), skill_sets.get(me))
                                        .get(b)
                                        .copied()
                                        .unwrap_or(AuxiliaryAbility::Empty);
                                    events.push(Event::ChangeAbility(a, ability_b));
                                    events.push(Event::ChangeAbility(b, ability_a));
                                }
                            },
                            (AbilitySlot::Slot(index), _) => {
                                events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
                            },
                            (AbilitySlot::Ability(_), AbilitySlot::Ability(_)) => {},
                        }
                    }
                },
                slot::Event::Used(from) => {
                    // Item used (selected and then clicked again)
                    if let Some(from) = to_slot(from) {
                        if self.show.crafting_fields.salvage
                            && matches!(
                                self.show.crafting_fields.crafting_tab,
                                CraftingTab::Dismantle
                            )
                        {
                            if let (Slot::Inventory(slot), Some((salvage_pos, _sprite_kind))) =
                                (from, self.show.crafting_fields.craft_sprite)
                            {
                                events.push(Event::SalvageItem { slot, salvage_pos })
                            }
                        } else {
                            events.push(Event::UseSlot {
                                slot: from,
                                bypass_dialog: false,
                            });
                        }
                    } else if let Hotbar(h) = from {
                        // Used from hotbar
                        self.hotbar.get(h).map(|s| match s {
                            hotbar::SlotContents::Inventory(i, _) => {
                                if let Some(inv) = inventories.get(info.viewpoint_entity) {
                                    // If the item in the inactive main hand is the same as the item
                                    // pressed in the hotbar, then swap active and inactive hands
                                    // instead of looking for
                                    // the item in the inventory
                                    if inv
                                        .equipped(comp::slot::EquipSlot::InactiveMainhand)
                                        .map_or(false, |item| item.item_hash() == i)
                                    {
                                        events.push(Event::SwapEquippedWeapons);
                                    } else if let Some(slot) = inv.get_slot_from_hash(i) {
                                        events.push(Event::UseSlot {
                                            slot: Slot::Inventory(slot),
                                            bypass_dialog: false,
                                        });
                                    }
                                }
                            },
                            hotbar::SlotContents::Ability(_) => {},
                        });
                    } else if let Ability(AbilitySlot::Slot(index)) = from {
                        events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
                    } else if let Crafting(c) = from {
                        // Remove item from crafting input
                        self.show.crafting_fields.recipe_inputs.remove(&c.index);
                    }
                },
                slot::Event::Request {
                    slot,
                    auto_quantity,
                } => {
                    if let Some((_, trade, prices)) = client.pending_trade() {
                        let ecs = client.state().ecs();
                        let inventories = ecs.read_component::<comp::Inventory>();
                        let get_inventory = |uid: Uid| {
                            if let Some(entity) = ecs.entity_from_uid(uid) {
                                inventories.get(entity)
                            } else {
                                None
                            }
                        };
                        let mut r_inventories = [None, None];
                        for (i, party) in trade.parties.iter().enumerate() {
                            match get_inventory(*party) {
                                Some(inventory) => {
                                    r_inventories[i] = Some(ReducedInventory::from(inventory))
                                },
                                None => continue 'slot_events,
                            };
                        }
                        let who = match ecs
                            .uid_from_entity(info.viewpoint_entity)
                            .and_then(|uid| trade.which_party(uid))
                        {
                            Some(who) => who,
                            None => continue 'slot_events,
                        };
                        let do_auto_quantity =
                            |inventory: &comp::Inventory,
                             slot,
                             ours,
                             remove,
                             quantity: &mut u32| {
                                if let Some(prices) = prices {
                                    if let Some((balance0, balance1)) = prices
                                        .balance(&trade.offers, &r_inventories, who, true)
                                        .zip(prices.balance(
                                            &trade.offers,
                                            &r_inventories,
                                            1 - who,
                                            false,
                                        ))
                                    {
                                        if let Some(item) = inventory.get(slot) {
                                            if let Some(materials) = TradePricing::get_materials(
                                                &item.item_definition_id(),
                                            ) {
                                                let unit_price: f32 = materials
                                                    .iter()
                                                    .map(|e| {
                                                        prices
                                                            .values
                                                            .get(&e.1)
                                                            .cloned()
                                                            .unwrap_or_default()
                                                            * e.0
                                                            * (if ours {
                                                                e.1.trade_margin()
                                                            } else {
                                                                1.0
                                                            })
                                                    })
                                                    .sum();

                                                let mut float_delta = if ours ^ remove {
                                                    (balance1 - balance0) / unit_price
                                                } else {
                                                    (balance0 - balance1) / unit_price
                                                };
                                                if ours ^ remove {
                                                    float_delta = float_delta.ceil();
                                                } else {
                                                    float_delta = float_delta.floor();
                                                }
                                                *quantity = float_delta.max(0.0) as u32;
                                            }
                                        }
                                    }
                                }
                            };
                        match slot {
                            Inventory(i) => {
                                if let Some(inventory) = inventories.get(i.entity) {
                                    if let Slot::Inventory(slot) = i.slot {
                                        let mut quantity = 1;
                                        if auto_quantity {
                                            do_auto_quantity(
                                                inventory,
                                                slot,
                                                i.ours,
                                                false,
                                                &mut quantity,
                                            );
                                            let inv_quantity = i.amount(inventory).unwrap_or(1);
                                            quantity = quantity.min(inv_quantity);
                                        }

                                        events.push(Event::TradeAction(TradeAction::AddItem {
                                            item: slot,
                                            quantity,
                                            ours: i.ours,
                                        }));
                                    }
                                }
                            },
                            Trade(t) => {
                                if let Some(inventory) = inventories.get(t.entity) {
                                    if let Some(invslot) = t.invslot {
                                        let mut quantity = 1;
                                        if auto_quantity {
                                            do_auto_quantity(
                                                inventory,
                                                invslot,
                                                t.ours,
                                                true,
                                                &mut quantity,
                                            );
                                            let inv_quantity = t.amount(inventory).unwrap_or(1);
                                            quantity = quantity.min(inv_quantity);
                                        }
                                        events.push(Event::TradeAction(TradeAction::RemoveItem {
                                            item: invslot,
                                            quantity,
                                            ours: t.ours,
                                        }));
                                    }
                                }
                            },
                            _ => {},
                        }
                    }
                },
            }
        }
        self.hotbar.maintain_abilities(client, &info);

        // Temporary Example Quest
        let arrow_ani = (self.pulse * 4.0/* speed factor */).cos() * 0.5 + 0.8; //Animation timer
        let show_intro = self.show.intro; // borrow check doesn't understand closures
        if let Some(toggle_cursor_key) = global_state
            .settings
            .controls
            .get_binding(GameInput::ToggleCursor)
            .filter(|_| !show_intro)
        {
            prof_span!("temporary example quest");
            match global_state.settings.interface.intro_show {
                Intro::Show => {
                    if Button::image(self.imgs.button)
                        .w_h(200.0, 60.0)
                        .hover_image(self.imgs.button_hover)
                        .press_image(self.imgs.button_press)
                        .bottom_left_with_margins_on(ui_widgets.window, 350.0, 150.0)
                        .label(&i18n.get_msg("hud-tutorial_btn"))
                        .label_font_id(self.fonts.cyri.conrod_id)
                        .label_font_size(self.fonts.cyri.scale(18))
                        .label_color(TEXT_COLOR)
                        .label_y(conrod_core::position::Relative::Scalar(2.0))
                        .image_color(ENEMY_HP_COLOR)
                        .set(self.ids.intro_button, ui_widgets)
                        .was_clicked()
                    {
                        self.show.intro = true;
                        self.show.want_grab = true;
                    }
                    let tutorial_click_msg =
                        i18n.get_msg_ctx("hud-tutorial_click_here", &i18n::fluent_args! {
                            "key" => toggle_cursor_key.display_string(key_layout),
                        });
                    Image::new(self.imgs.sp_indicator_arrow)
                        .w_h(20.0, 11.0)
                        .mid_top_with_margin_on(self.ids.intro_button, -20.0 + arrow_ani as f64)
                        .color(Some(QUALITY_LEGENDARY))
                        .set(self.ids.tut_arrow, ui_widgets);
                    Text::new(&tutorial_click_msg)
                        .mid_top_with_margin_on(self.ids.tut_arrow, -40.0)
                        .font_id(self.fonts.cyri.conrod_id)
                        .font_size(self.fonts.cyri.scale(14))
                        .center_justify()
                        .color(BLACK)
                        .set(self.ids.tut_arrow_txt_bg, ui_widgets);
                    Text::new(&tutorial_click_msg)
                        .bottom_right_with_margins_on(self.ids.tut_arrow_txt_bg, 1.0, 1.0)
                        .center_justify()
                        .font_id(self.fonts.cyri.conrod_id)
                        .font_size(self.fonts.cyri.scale(14))
                        .color(QUALITY_LEGENDARY)
                        .set(self.ids.tut_arrow_txt, ui_widgets);
                },
                Intro::Never => {
                    self.show.intro = false;
                },
            }
        }
        // TODO: Add event/stat based tutorial system
        if self.show.intro && !self.show.esc_menu {
            prof_span!("intro show");
            match global_state.settings.interface.intro_show {
                Intro::Show => {
                    if self.show.intro {
                        self.show.want_grab = false;
                        let quest_headline = i18n.get_msg("hud-temp_quest_headline");
                        let quest_text = i18n.get_msg("hud-temp_quest_text");
                        Image::new(self.imgs.quest_bg0)
                            .w_h(404.0, 858.0)
                            .middle_of(ui_widgets.window)
                            .set(self.ids.quest_bg, ui_widgets);

                        Text::new(&quest_headline)
                            .mid_top_with_margin_on(self.ids.quest_bg, 310.0)
                            .font_size(self.fonts.cyri.scale(30))
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(TEXT_BG)
                            .set(self.ids.q_headline_bg, ui_widgets);
                        Text::new(&quest_headline)
                            .bottom_left_with_margins_on(self.ids.q_headline_bg, 1.0, 1.0)
                            .font_size(self.fonts.cyri.scale(30))
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(TEXT_COLOR)
                            .set(self.ids.q_headline, ui_widgets);

                        Text::new(&quest_text)
                            .mid_top_with_margin_on(self.ids.quest_bg, 360.0)
                            .w(350.0)
                            .font_size(self.fonts.cyri.scale(17))
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(TEXT_BG)
                            .set(self.ids.q_text_bg, ui_widgets);
                        Text::new(&quest_text)
                            .bottom_left_with_margins_on(self.ids.q_text_bg, 1.0, 1.0)
                            .w(350.0)
                            .font_size(self.fonts.cyri.scale(17))
                            .font_id(self.fonts.cyri.conrod_id)
                            .color(TEXT_COLOR)
                            .set(self.ids.q_text, ui_widgets);

                        if Button::image(self.imgs.button)
                            .w_h(212.0, 52.0)
                            .hover_image(self.imgs.button_hover)
                            .press_image(self.imgs.button_press)
                            .mid_bottom_with_margin_on(self.ids.q_text_bg, -80.0)
                            .label(&i18n.get_msg("common-close"))
                            .label_font_id(self.fonts.cyri.conrod_id)
                            .label_font_size(self.fonts.cyri.scale(22))
                            .label_color(TEXT_COLOR)
                            .label_y(conrod_core::position::Relative::Scalar(2.0))
                            .set(self.ids.accept_button, ui_widgets)
                            .was_clicked()
                        {
                            self.show.intro = false;
                            events.push(Event::SettingsChange(
                                InterfaceChange::Intro(Intro::Never).into(),
                            ));
                            self.show.want_grab = true;
                        }
                        if !self.show.crafting && !self.show.bag {
                            Image::new(self.imgs.sp_indicator_arrow)
                                .w_h(20.0, 11.0)
                                .bottom_right_with_margins_on(
                                    ui_widgets.window,
                                    40.0 + arrow_ani as f64,
                                    205.0,
                                )
                                .color(Some(QUALITY_LEGENDARY))
                                .set(self.ids.tut_arrow, ui_widgets);
                            Text::new(&i18n.get_msg("hud-tutorial_elements"))
                                .mid_top_with_margin_on(self.ids.tut_arrow, -50.0)
                                .font_id(self.fonts.cyri.conrod_id)
                                .font_size(self.fonts.cyri.scale(40))
                                .color(BLACK)
                                .floating(true)
                                .set(self.ids.tut_arrow_txt_bg, ui_widgets);
                            Text::new(&i18n.get_msg("hud-tutorial_elements"))
                                .bottom_right_with_margins_on(self.ids.tut_arrow_txt_bg, 1.0, 1.0)
                                .font_id(self.fonts.cyri.conrod_id)
                                .font_size(self.fonts.cyri.scale(40))
                                .color(QUALITY_LEGENDARY)
                                .floating(true)
                                .set(self.ids.tut_arrow_txt, ui_widgets);
                        }
                    }
                },
                Intro::Never => {
                    self.show.intro = false;
                },
            }
        }

        events
    }

    fn show_bag(slot_manager: &mut slots::SlotManager, show: &mut Show, state: bool) {
        show.bag(state);
        if !state {
            slot_manager.idle();
        }
    }

    pub fn add_failed_block_pickup(&mut self, pos: VolumePos, reason: HudCollectFailedReason) {
        self.failed_block_pickups
            .insert(pos, CollectFailedData::new(self.pulse, reason));
    }

    pub fn add_failed_entity_pickup(&mut self, entity: EcsEntity, reason: HudCollectFailedReason) {
        self.failed_entity_pickups
            .insert(entity, CollectFailedData::new(self.pulse, reason));
    }

    pub fn new_loot_message(&mut self, item: LootMessage) {
        self.new_loot_messages.push_back(item);
    }

    pub fn new_message(&mut self, msg: comp::ChatMsg) { self.new_messages.push_back(msg); }

    pub fn new_notification(&mut self, msg: Notification) { self.new_notifications.push_back(msg); }

    pub fn set_scaling_mode(&mut self, scale_mode: ScaleMode) {
        self.ui.set_scaling_mode(scale_mode);
    }

    pub fn scale_change(&mut self, scale_change: ScaleChange) -> ScaleMode {
        let scale_mode = match scale_change {
            ScaleChange::Adjust(scale) => ScaleMode::Absolute(scale),
            ScaleChange::ToAbsolute => self.ui.scale().scaling_mode_as_absolute(),
            ScaleChange::ToRelative => self.ui.scale().scaling_mode_as_relative(),
        };
        self.ui.set_scaling_mode(scale_mode);
        scale_mode
    }

    /// Checks if a TextEdit widget has the keyboard captured.
    fn typing(&self) -> bool { Hud::is_captured::<widget::TextEdit>(&self.ui.ui) }

    /// Checks if a widget of type `W` has captured the keyboard
    fn is_captured<W: Widget>(ui: &conrod_core::Ui) -> bool {
        if let Some(id) = ui.global_input().current.widget_capturing_keyboard {
            ui.widget_graph()
                .widget(id)
                .filter(|c| c.type_id == std::any::TypeId::of::<<W as Widget>::State>())
                .is_some()
        } else {
            false
        }
    }

    pub fn handle_event(
        &mut self,
        event: WinEvent,
        global_state: &mut GlobalState,
        client_inventory: Option<&comp::Inventory>,
    ) -> bool {
        // Helper
        fn handle_slot(
            slot: hotbar::Slot,
            state: bool,
            events: &mut Vec<Event>,
            slot_manager: &mut slots::SlotManager,
            hotbar: &mut hotbar::State,
            client_inventory: Option<&comp::Inventory>,
        ) {
            use slots::InventorySlot;
            if let Some(slots::SlotKind::Inventory(InventorySlot {
                slot: Slot::Inventory(i),
                ours: true,
                ..
            })) = slot_manager.selected()
            {
                if let Some(item) = client_inventory.and_then(|inv| inv.get(i)) {
                    hotbar.add_inventory_link(slot, item);
                    events.push(Event::ChangeHotbarState(Box::new(hotbar.to_owned())));
                    slot_manager.idle();
                }
            } else {
                let just_pressed = hotbar.process_input(slot, state);
                hotbar.get(slot).map(|s| match s {
                    hotbar::SlotContents::Inventory(i, _) => {
                        if just_pressed {
                            if let Some(inv) = client_inventory {
                                // If the item in the inactive main hand is the same as the item
                                // pressed in the hotbar, then swap active and inactive hands
                                // instead of looking for the item
                                // in the inventory
                                if inv
                                    .equipped(comp::slot::EquipSlot::InactiveMainhand)
                                    .map_or(false, |item| item.item_hash() == i)
                                {
                                    events.push(Event::SwapEquippedWeapons);
                                } else if let Some(slot) = inv.get_slot_from_hash(i) {
                                    events.push(Event::UseSlot {
                                        slot: comp::slot::Slot::Inventory(slot),
                                        bypass_dialog: false,
                                    });
                                }
                            }
                        }
                    },
                    hotbar::SlotContents::Ability(i) => events.push(Event::Ability(i, state)),
                });
            }
        }

        fn handle_map_zoom(
            factor: f64,
            world_size: Vec2<u32>,
            show: &Show,
            global_state: &mut GlobalState,
        ) -> bool {
            let max_zoom = world_size.reduce_partial_max() as f64;

            if show.map {
                let new_zoom_lvl = (global_state.settings.interface.map_zoom * factor)
                    .clamped(1.25, max_zoom / 64.0);
                global_state.settings.interface.map_zoom = new_zoom_lvl;
            } else if global_state.settings.interface.minimap_show {
                let new_zoom_lvl = global_state.settings.interface.minimap_zoom * factor;
                global_state.settings.interface.minimap_zoom = new_zoom_lvl;
            }

            show.map && global_state.settings.interface.minimap_show
        }

        let cursor_grabbed = global_state.window.is_cursor_grabbed();
        let handled = match event {
            WinEvent::Ui(event) => {
                if (self.typing() && event.is_keyboard() && self.show.ui)
                    || !(cursor_grabbed && event.is_keyboard_or_mouse())
                {
                    self.ui.handle_event(event);
                }
                true
            },
            WinEvent::ScaleFactorChanged(scale_factor) => {
                self.ui.scale_factor_changed(scale_factor);
                false
            },
            WinEvent::InputUpdate(GameInput::ToggleInterface, true) if !self.typing() => {
                self.show.toggle_ui();
                true
            },
            WinEvent::InputUpdate(GameInput::ToggleCursor, true) if !self.typing() => {
                self.force_ungrab = !self.force_ungrab;
                true
            },
            WinEvent::InputUpdate(GameInput::AcceptGroupInvite, true) if !self.typing() => {
                if let Some(prompt_dialog) = &mut self.show.prompt_dialog {
                    prompt_dialog.set_outcome_via_keypress(true);
                    true
                } else {
                    false
                }
            },
            WinEvent::InputUpdate(GameInput::DeclineGroupInvite, true) if !self.typing() => {
                if let Some(prompt_dialog) = &mut self.show.prompt_dialog {
                    prompt_dialog.set_outcome_via_keypress(false);
                    true
                } else {
                    false
                }
            },

            // If not showing the ui don't allow keys that change the ui state but do listen for
            // hotbar keys
            WinEvent::InputUpdate(key, state) if !self.show.ui => {
                if let Some(slot) = try_hotbar_slot_from_input(key) {
                    handle_slot(
                        slot,
                        state,
                        &mut self.events,
                        &mut self.slot_manager,
                        &mut self.hotbar,
                        client_inventory,
                    );
                    true
                } else {
                    false
                }
            },

            WinEvent::Zoom(_) => !cursor_grabbed && !self.ui.no_widget_capturing_mouse(),

            WinEvent::InputUpdate(GameInput::Chat, true) => {
                self.ui.focus_widget(if self.typing() {
                    None
                } else {
                    self.force_chat = true;
                    Some(self.ids.chat)
                });
                true
            },
            WinEvent::InputUpdate(GameInput::Escape, true) => {
                if self.typing() {
                    self.ui.focus_widget(None);
                    self.force_chat = false;
                } else if self.show.trade {
                    self.events.push(Event::TradeAction(TradeAction::Decline));
                } else {
                    // Close windows on esc
                    if self.show.bag {
                        self.slot_manager.idle();
                    }
                    self.show.toggle_windows(global_state);
                }
                true
            },

            // Press key while not typing
            WinEvent::InputUpdate(key, state) if !self.typing() => {
                let gs_audio = &global_state.settings.audio;
                let mut toggle_mute = |audio: Audio| {
                    self.events
                        .push(Event::SettingsChange(SettingsChange::Audio(audio)));
                    true
                };

                match key {
                    GameInput::Command if state => {
                        self.force_chat_input = Some("/".to_owned());
                        self.force_chat_cursor = Some(Index { line: 0, char: 1 });
                        self.force_chat = true;
                        self.ui.focus_widget(Some(self.ids.chat));
                        true
                    },
                    GameInput::Map if state => {
                        self.show.toggle_map();
                        true
                    },
                    GameInput::Bag if state => {
                        let state = !self.show.bag;
                        Self::show_bag(&mut self.slot_manager, &mut self.show, state);
                        true
                    },
                    GameInput::Social if state => {
                        self.show.toggle_social();
                        true
                    },
                    GameInput::Crafting if state => {
                        self.show.toggle_crafting();
                        true
                    },
                    GameInput::Diary if state => {
                        self.show.toggle_diary();
                        true
                    },
                    GameInput::Settings if state => {
                        self.show.toggle_settings(global_state);
                        true
                    },
                    GameInput::Controls if state => {
                        self.show.toggle_settings(global_state);
                        self.show.settings_tab = SettingsTab::Controls;
                        true
                    },
                    GameInput::ToggleDebug if state => {
                        global_state.settings.interface.toggle_debug =
                            !global_state.settings.interface.toggle_debug;
                        true
                    },
                    #[cfg(feature = "egui-ui")]
                    GameInput::ToggleEguiDebug if state => {
                        global_state.settings.interface.toggle_egui_debug =
                            !global_state.settings.interface.toggle_egui_debug;
                        true
                    },
                    GameInput::ToggleChat if state => {
                        global_state.settings.interface.toggle_chat =
                            !global_state.settings.interface.toggle_chat;
                        true
                    },
                    GameInput::ToggleIngameUi if state => {
                        self.show.ingame = !self.show.ingame;
                        true
                    },
                    GameInput::MapZoomIn if state => {
                        handle_map_zoom(2.0, self.world_map.1, &self.show, global_state)
                    },
                    GameInput::MapZoomOut if state => {
                        handle_map_zoom(0.5, self.world_map.1, &self.show, global_state)
                    },
                    GameInput::MuteMaster if state => {
                        toggle_mute(Audio::MuteMasterVolume(!gs_audio.master_volume.muted))
                    },
                    GameInput::MuteInactiveMaster if state => {
                        toggle_mute(Audio::MuteInactiveMasterVolume(
                            !gs_audio.inactive_master_volume_perc.muted,
                        ))
                    },
                    GameInput::MuteMusic if state => {
                        toggle_mute(Audio::MuteMusicVolume(!gs_audio.music_volume.muted))
                    },
                    GameInput::MuteSfx if state => {
                        toggle_mute(Audio::MuteSfxVolume(!gs_audio.sfx_volume.muted))
                    },
                    GameInput::MuteAmbience if state => {
                        toggle_mute(Audio::MuteAmbienceVolume(!gs_audio.ambience_volume.muted))
                    },
                    // Skillbar
                    input => {
                        if let Some(slot) = try_hotbar_slot_from_input(input) {
                            handle_slot(
                                slot,
                                state,
                                &mut self.events,
                                &mut self.slot_manager,
                                &mut self.hotbar,
                                client_inventory,
                            );
                            true
                        } else {
                            false
                        }
                    },
                }
            },
            // Else the player is typing in chat
            WinEvent::InputUpdate(_key, _) => self.typing(),
            WinEvent::Char(_) => self.typing(),
            WinEvent::Focused(state) => {
                self.force_ungrab = !state;
                true
            },
            WinEvent::Moved(_) => {
                // Prevent the cursor from being grabbed while the window is being moved as this
                // causes the window to move erratically
                // TODO: this creates an issue where if you move the window then you need to
                // close a menu to re-grab the mouse (and if one isn't already
                // open you need to open and close a menu)
                self.show.want_grab = false;
                true
            },
            _ => false,
        };
        // Handle cursor grab.
        global_state
            .window
            .grab_cursor(!self.force_ungrab && self.show.want_grab);

        handled
    }

    pub fn maintain(
        &mut self,
        client: &Client,
        global_state: &mut GlobalState,
        debug_info: &Option<DebugInfo>,
        camera: &Camera,
        dt: Duration,
        info: HudInfo,
        interactable: Option<&Interactable>,
    ) -> Vec<Event> {
        span!(_guard, "maintain", "Hud::maintain");
        // conrod eats tabs. Un-eat a tabstop so tab completion can work
        if self.ui.ui.global_input().events().any(|event| {
            use conrod_core::{event, input};
            matches!(
                event,
                /* event::Event::Raw(event::Input::Press(input::Button::Keyboard(input::Key::
                 * Tab))) | */
                event::Event::Ui(event::Ui::Press(_, event::Press {
                    button: event::Button::Keyboard(input::Key::Tab),
                    ..
                },))
            )
        }) {
            self.ui
                .ui
                .handle_event(conrod_core::event::Input::Text("\t".to_string()));
        }

        // Stop selecting a sprite to perform crafting with when out of range or sprite
        // has been removed
        self.show.crafting_fields.craft_sprite =
            self.show
                .crafting_fields
                .craft_sprite
                .filter(|(pos, sprite)| {
                    self.show.crafting
                        && if let Some(player_pos) = client.position() {
                            pos.get_block_and_transform(
                                &client.state().terrain(),
                                &client.state().ecs().read_resource(),
                                |e| {
                                    client
                                        .state()
                                        .read_storage::<vcomp::Interpolated>()
                                        .get(e)
                                        .map(|interpolated| {
                                            (comp::Pos(interpolated.pos), interpolated.ori)
                                        })
                                },
                                &client.state().read_storage(),
                            )
                            .map_or(false, |(mat, _, block)| {
                                block.get_sprite() == Some(*sprite)
                                    && mat.mul_point(Vec3::broadcast(0.5)).distance(player_pos)
                                        < MAX_PICKUP_RANGE
                            })
                        } else {
                            false
                        }
                });

        // Optimization: skip maintaining UI when it's off.
        if !self.show.ui {
            return std::mem::take(&mut self.events);
        }

        if let Some(maybe_id) = self.to_focus.take() {
            self.ui.focus_widget(maybe_id);
        }
        let events = self.update_layout(
            client,
            global_state,
            debug_info,
            dt,
            info,
            camera,
            interactable,
        );
        let camera::Dependents {
            view_mat, proj_mat, ..
        } = camera.dependents();
        let focus_off = camera.get_focus_pos().map(f32::trunc);

        // Check if item images need to be reloaded
        self.item_imgs.reload_if_changed(&mut self.ui);
        // TODO: using a thread pool in the obvious way for speeding up map zoom results
        // in flickering artifacts, figure out a better way to make use of the
        // thread pool
        let _pool = client.state().ecs().read_resource::<SlowJobPool>();
        self.ui.maintain(
            global_state.window.renderer_mut(),
            None,
            //Some(&pool),
            Some(proj_mat * view_mat * Mat4::translation_3d(-focus_off)),
        );

        events
    }

    #[inline]
    pub fn clear_cursor(&mut self) { self.slot_manager.idle(); }

    pub fn render<'a>(&'a self, drawer: &mut UiDrawer<'_, 'a>) {
        span!(_guard, "render", "Hud::render");
        // Don't show anything if the UI is toggled off.
        if self.show.ui {
            self.ui.render(drawer);
        }
    }

    pub fn free_look(&mut self, free_look: bool) { self.show.free_look = free_look; }

    pub fn auto_walk(&mut self, auto_walk: bool) { self.show.auto_walk = auto_walk; }

    pub fn camera_clamp(&mut self, camera_clamp: bool) { self.show.camera_clamp = camera_clamp; }

    /// Remind the player camera zoom is currently locked, for example if they
    /// are trying to zoom.
    pub fn zoom_lock_reminder(&mut self) {
        if self.show.zoom_lock.reason.is_none() {
            self.show.zoom_lock = ChangeNotification::from_reason(NotificationReason::Remind);
        }
    }

    /// Start showing a temporary notification ([ChangeNotification]) that zoom
    /// lock was toggled on/off.
    pub fn zoom_lock_toggle(&mut self, state: bool) {
        self.show.zoom_lock = ChangeNotification::from_state(state);
    }

    pub fn show_content_bubble(&mut self, pos: Vec3<f32>, content: comp::Content) {
        self.content_bubbles.push((
            pos,
            comp::SpeechBubble::new(content, comp::SpeechBubbleType::None),
        ));
    }

    pub fn handle_outcome(
        &mut self,
        outcome: &Outcome,
        client: &Client,
        global_state: &GlobalState,
    ) {
        let interface = &global_state.settings.interface;
        match outcome {
            Outcome::ExpChange { uid, exp, xp_pools } => {
                let ecs = client.state().ecs();
                let uids = ecs.read_storage::<Uid>();
                let me = client.entity();

                if uids.get(me).map_or(false, |me| *me == *uid) {
                    match self.floaters.exp_floaters.last_mut() {
                        Some(floater)
                            if floater.timer
                                > (EXP_FLOATER_LIFETIME - EXP_ACCUMULATION_DURATION)
                                && global_state.settings.interface.accum_experience
                                && floater.owner == *uid =>
                        {
                            floater.jump_timer = 0.0;
                            floater.exp_change += *exp;
                        },
                        _ => self.floaters.exp_floaters.push(ExpFloater {
                            // Store the owner as to not accumulate old experience floaters
                            owner: *uid,
                            exp_change: *exp,
                            timer: EXP_FLOATER_LIFETIME,
                            jump_timer: 0.0,
                            rand_offset: rand::thread_rng().gen::<(f32, f32)>(),
                            xp_pools: xp_pools.clone(),
                        }),
                    }
                }
            },
            Outcome::SkillPointGain {
                uid,
                skill_tree,
                total_points,
                ..
            } => {
                let ecs = client.state().ecs();
                let uids = ecs.read_storage::<Uid>();
                let me = client.entity();

                if uids.get(me).map_or(false, |me| *me == *uid) {
                    self.floaters.skill_point_displays.push(SkillPointGain {
                        skill_tree: *skill_tree,
                        total_points: *total_points,
                        timer: 5.0,
                    });
                }
            },
            Outcome::ComboChange { uid, combo } => {
                let ecs = client.state().ecs();
                let uids = ecs.read_storage::<Uid>();
                let me = client.entity();

                if uids.get(me).map_or(false, |me| *me == *uid) {
                    self.floaters.combo_floater = Some(ComboFloater {
                        combo: *combo,
                        timer: comp::combo::COMBO_DECAY_START,
                    });
                }
            },
            Outcome::Block { uid, parry, .. } if *parry => {
                let ecs = client.state().ecs();
                let uids = ecs.read_storage::<Uid>();
                let me = client.entity();

                if uids.get(me).map_or(false, |me| *me == *uid) {
                    self.floaters
                        .block_floaters
                        .push(BlockFloater { timer: 1.0 });
                }
            },
            Outcome::HealthChange { info, .. } => {
                let ecs = client.state().ecs();
                let mut hp_floater_lists = ecs.write_storage::<HpFloaterList>();
                let uids = ecs.read_storage::<Uid>();
                let me = client.entity();
                let my_uid = uids.get(me);

                if let Some(entity) = ecs.entity_from_uid(info.target) {
                    if let Some(floater_list) = hp_floater_lists.get_mut(entity) {
                        let hit_me = my_uid.map_or(false, |&uid| {
                            (info.target == uid) && global_state.settings.interface.sct_inc_dmg
                        });
                        if match info.by {
                            Some(by) => {
                                let by_me = my_uid.map_or(false, |&uid| by.uid() == uid);
                                // If the attack was by me also reset this timer
                                if by_me {
                                    floater_list.time_since_last_dmg_by_me = Some(0.0);
                                }
                                hit_me || by_me
                            },
                            None => hit_me,
                        } {
                            // Group up damage from the same tick and instance number
                            for floater in floater_list.floaters.iter_mut().rev() {
                                if floater.timer > 0.0 {
                                    break;
                                }
                                if floater.info.instance == info.instance
                                    // Group up precision hits and regular attacks for incoming damage
                                    && (hit_me
                                        || floater.info.precise
                                            == info.precise)
                                {
                                    floater.info.amount += info.amount;
                                    if info.precise {
                                        floater.info.precise = info.precise
                                    }
                                    return;
                                }
                            }

                            // To separate healing and damage floaters alongside the precise and
                            // non-precise ones
                            let last_floater = if !info.precise || hit_me {
                                floater_list.floaters.iter_mut().rev().find(|f| {
                                    (if info.amount < 0.0 {
                                        f.info.amount < 0.0
                                    } else {
                                        f.info.amount > 0.0
                                    }) && f.timer
                                        < if hit_me {
                                            interface.sct_inc_dmg_accum_duration
                                        } else {
                                            interface.sct_dmg_accum_duration
                                        }
                                    // Ignore precise floaters, unless the damage is incoming
                                    && (hit_me || !f.info.precise)
                                })
                            } else {
                                None
                            };

                            match last_floater {
                                Some(f) => {
                                    f.jump_timer = 0.0;
                                    f.info.amount += info.amount;
                                    f.info.precise = info.precise;
                                },
                                _ => {
                                    floater_list.floaters.push(HpFloater {
                                        timer: 0.0,
                                        jump_timer: 0.0,
                                        info: *info,
                                        rand: rand::random(),
                                    });
                                },
                            }
                        }
                    }
                }
            },

            _ => {},
        }
    }
}
// Get item qualities of equipped items and assign a tooltip title/frame color
pub fn get_quality_col<I: ItemDesc + ?Sized>(item: &I) -> Color {
    match item.quality() {
        Quality::Low => QUALITY_LOW,
        Quality::Common => QUALITY_COMMON,
        Quality::Moderate => QUALITY_MODERATE,
        Quality::High => QUALITY_HIGH,
        Quality::Epic => QUALITY_EPIC,
        Quality::Legendary => QUALITY_LEGENDARY,
        Quality::Artifact => QUALITY_ARTIFACT,
        Quality::Debug => QUALITY_DEBUG,
    }
}

fn try_hotbar_slot_from_input(input: GameInput) -> Option<hotbar::Slot> {
    Some(match input {
        GameInput::Slot1 => hotbar::Slot::One,
        GameInput::Slot2 => hotbar::Slot::Two,
        GameInput::Slot3 => hotbar::Slot::Three,
        GameInput::Slot4 => hotbar::Slot::Four,
        GameInput::Slot5 => hotbar::Slot::Five,
        GameInput::Slot6 => hotbar::Slot::Six,
        GameInput::Slot7 => hotbar::Slot::Seven,
        GameInput::Slot8 => hotbar::Slot::Eight,
        GameInput::Slot9 => hotbar::Slot::Nine,
        GameInput::Slot10 => hotbar::Slot::Ten,
        _ => return None,
    })
}

pub fn cr_color(combat_rating: f32) -> Color {
    let common = 2.0;
    let moderate = 3.5;
    let high = 6.5;
    let epic = 8.5;
    let legendary = 10.4;
    let artifact = 122.0;
    let debug = 200.0;

    match combat_rating {
        x if (0.0..common).contains(&x) => QUALITY_LOW,
        x if (common..moderate).contains(&x) => QUALITY_COMMON,
        x if (moderate..high).contains(&x) => QUALITY_MODERATE,
        x if (high..epic).contains(&x) => QUALITY_HIGH,
        x if (epic..legendary).contains(&x) => QUALITY_EPIC,
        x if (legendary..artifact).contains(&x) => QUALITY_LEGENDARY,
        x if (artifact..debug).contains(&x) => QUALITY_ARTIFACT,
        x if x >= debug => QUALITY_DEBUG,
        _ => XP_COLOR,
    }
}

pub fn get_buff_image(buff: BuffKind, imgs: &Imgs) -> conrod_core::image::Id {
    match buff {
        // Buffs
        BuffKind::Regeneration => imgs.buff_plus_0,
        BuffKind::Saturation => imgs.buff_saturation_0,
        BuffKind::Potion => imgs.buff_potion_0,
        // TODO: Need unique image for Agility (uses same as Hastened atm)
        BuffKind::Agility => imgs.buff_haste_0,
        BuffKind::CampfireHeal => imgs.buff_campfire_heal_0,
        BuffKind::EnergyRegen => imgs.buff_energyplus_0,
        BuffKind::IncreaseMaxEnergy => imgs.buff_energyplus_0,
        BuffKind::IncreaseMaxHealth => imgs.buff_healthplus_0,
        BuffKind::Invulnerability => imgs.buff_invincibility_0,
        BuffKind::ProtectingWard => imgs.buff_dmg_red_0,
        BuffKind::Frenzied => imgs.buff_frenzy_0,
        BuffKind::Hastened => imgs.buff_haste_0,
        BuffKind::Fortitude => imgs.buff_fortitude_0,
        BuffKind::Reckless => imgs.buff_reckless,
        BuffKind::Flame => imgs.buff_flame,
        BuffKind::Frigid => imgs.buff_frigid,
        BuffKind::Lifesteal => imgs.buff_lifesteal,
        BuffKind::Resilience => imgs.buff_resilience,
        // TODO: Get image
        // BuffKind::SalamanderAspect => imgs.debuff_burning_0,
        BuffKind::ImminentCritical => imgs.buff_imminentcritical,
        BuffKind::Fury => imgs.buff_fury,
        BuffKind::Sunderer => imgs.buff_sunderer,
        BuffKind::Defiance => imgs.buff_defiance,
        BuffKind::Bloodfeast => imgs.buff_plus_0,
        BuffKind::Berserk => imgs.buff_reckless,
        BuffKind::ScornfulTaunt => imgs.buff_scornfultaunt,
        BuffKind::Tenacity => imgs.buff_tenacity,
        //  Debuffs
        BuffKind::Bleeding => imgs.debuff_bleed_0,
        BuffKind::Cursed => imgs.debuff_skull_0,
        BuffKind::Burning => imgs.debuff_burning_0,
        BuffKind::Crippled => imgs.debuff_crippled_0,
        BuffKind::Frozen => imgs.debuff_frozen_0,
        BuffKind::Wet => imgs.debuff_wet_0,
        BuffKind::Ensnared => imgs.debuff_ensnared_0,
        BuffKind::Poisoned => imgs.debuff_poisoned_0,
        BuffKind::Parried => imgs.debuff_parried_0,
        BuffKind::PotionSickness => imgs.debuff_potionsickness_0,
        BuffKind::Polymorphed => imgs.debuff_polymorphed,
        BuffKind::Heatstroke => imgs.debuff_heatstroke_0,
        BuffKind::Rooted => imgs.debuff_rooted,
        BuffKind::Winded => imgs.debuff_winded,
        BuffKind::Concussion => imgs.debuff_concussion,
        BuffKind::Staggered => imgs.debuff_staggered,
    }
}

pub fn get_sprite_desc(sprite: SpriteKind, localized_strings: &Localization) -> Option<Cow<str>> {
    let i18n_key = match sprite {
        SpriteKind::Empty | SpriteKind::GlassBarrier => return None,
        SpriteKind::Anvil => "hud-crafting-anvil",
        SpriteKind::Cauldron => "hud-crafting-cauldron",
        SpriteKind::CookingPot => "hud-crafting-cooking_pot",
        SpriteKind::RepairBench => "hud-crafting-repair_bench",
        SpriteKind::CraftingBench => "hud-crafting-crafting_bench",
        SpriteKind::Forge => "hud-crafting-forge",
        SpriteKind::Loom => "hud-crafting-loom",
        SpriteKind::SpinningWheel => "hud-crafting-spinning_wheel",
        SpriteKind::TanningRack => "hud-crafting-tanning_rack",
        SpriteKind::DismantlingBench => "hud-crafting-salvaging_station",
        SpriteKind::ChestBuried
        | SpriteKind::Chest
        | SpriteKind::CoralChest
        | SpriteKind::DungeonChest0
        | SpriteKind::DungeonChest1
        | SpriteKind::DungeonChest2
        | SpriteKind::DungeonChest3
        | SpriteKind::DungeonChest4
        | SpriteKind::DungeonChest5
        | SpriteKind::SahaginChest
        | SpriteKind::TerracottaChest => "common-sprite-chest",
        SpriteKind::Mud => "common-sprite-mud",
        SpriteKind::Grave => "common-sprite-grave",
        SpriteKind::ChairSingle
        | SpriteKind::ChairDouble
        | SpriteKind::Bench
        | SpriteKind::BenchCoastal => "common-sprite-chair",
        SpriteKind::Crate => "common-sprite-crate",
        SpriteKind::HangingSign => "common-sprite-signboard",
        SpriteKind::StreetLamp => "common-sprite-street_lamp",
        SpriteKind::Lantern => "common-sprite-lantern",
        SpriteKind::SeashellLantern => "common-sprite-seashell_lantern",
        SpriteKind::FireBowlGround => "common-sprite-firebowl_ground",
        sprite => return Some(Cow::Owned(format!("{:?}", sprite))),
    };
    Some(localized_strings.get_msg(i18n_key))
}

pub fn angle_of_attack_text(
    fluid: Option<comp::Fluid>,
    velocity: Option<comp::Vel>,
    character_state: Option<&comp::CharacterState>,
) -> String {
    use comp::CharacterState;

    let glider_ori = if let Some(CharacterState::Glide(data)) = character_state {
        data.ori
    } else {
        return "Angle of Attack: Not gliding".to_owned();
    };

    let fluid = if let Some(fluid) = fluid {
        fluid
    } else {
        return "Angle of Attack: Not in fluid".to_owned();
    };

    let velocity = if let Some(velocity) = velocity {
        velocity
    } else {
        return "Angle of Attack: Player has no vel component".to_owned();
    };
    let rel_flow = fluid.relative_flow(&velocity).0;
    let v_sq = rel_flow.magnitude_squared();

    if v_sq.abs() > 0.0001 {
        let rel_flow_dir = Dir::new(rel_flow / v_sq.sqrt());
        let aoe = fluid_dynamics::angle_of_attack(&glider_ori, &rel_flow_dir);
        let (rel_x, rel_y, rel_z) = (rel_flow.x, rel_flow.y, rel_flow.z);
        format!(
            "Angle of Attack: {:.1} ({:.1},{:.1},{:.1})",
            aoe.to_degrees(),
            rel_x,
            rel_y,
            rel_z
        )
    } else {
        "Angle of Attack: Not moving".to_owned()
    }
}

fn air_velocity(fluid: Option<comp::Fluid>) -> String {
    if let Some(comp::Fluid::Air { vel: air_vel, .. }) = fluid {
        format!(
            "Air Velocity: ({:.1}, {:.1}, {:.1})",
            air_vel.0.x, air_vel.0.y, air_vel.0.z
        )
    } else {
        "Air Velocity: Not in Air".to_owned()
    }
}

/// Converts multiplier to percentage.
/// NOTE: floats are not the most precise type.
///
/// # Examples
/// ```
/// use veloren_voxygen::hud::multiplier_to_percentage;
///
/// let positive = multiplier_to_percentage(1.05);
/// assert!((positive - 5.0).abs() < 0.0001);
/// let negative = multiplier_to_percentage(0.85);
/// assert!((negative - (-15.0)).abs() < 0.0001);
/// ```
pub fn multiplier_to_percentage(value: f32) -> f32 { value * 100.0 - 100.0 }