File: PlayerInfo.cpp

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

Endless Sky is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.

Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
*/

#include "PlayerInfo.h"

#include "AI.h"
#include "audio/Audio.h"
#include "ConversationPanel.h"
#include "DataFile.h"
#include "DataWriter.h"
#include "Dialog.h"
#include "DistanceMap.h"
#include "Files.h"
#include "text/Format.h"
#include "GameData.h"
#include "Gamerules.h"
#include "Government.h"
#include "Logger.h"
#include "Messages.h"
#include "Outfit.h"
#include "Person.h"
#include "Planet.h"
#include "Plugins.h"
#include "Politics.h"
#include "Port.h"
#include "Preferences.h"
#include "RaidFleet.h"
#include "Random.h"
#include "SavedGame.h"
#include "Ship.h"
#include "ShipEvent.h"
#include "StartConditions.h"
#include "StellarObject.h"
#include "System.h"
#include "UI.h"

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <ctime>
#include <functional>
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>

using namespace std;

namespace {
	// Move the flagship to the start of your list of ships. It does not make sense
	// that the flagship would change if you are reunited with a different ship that
	// was higher up the list.
	void MoveFlagshipBegin(vector<shared_ptr<Ship>> &ships, const shared_ptr<Ship> &flagship)
	{
		if(!flagship)
			return;

		// Find the current location of the flagship.
		auto it = find(ships.begin(), ships.end(), flagship);
		if(it != ships.begin() && it != ships.end())
		{
			// Move all ships before the flagship one position backwards (which overwrites
			// the flagship at its position).
			move_backward(ships.begin(), it, next(it));
			// Re-add the flagship at the beginning of the list.
			ships[0] = flagship;
		}
	}

	string EntryToString(SystemEntry entryType)
	{
		switch(entryType)
		{
			case SystemEntry::HYPERDRIVE:
				return "hyperdrive";
			case SystemEntry::JUMP:
				return "jump drive";
			case SystemEntry::WORMHOLE:
				return "wormhole";
			default:
			case SystemEntry::TAKE_OFF:
				return "takeoff";
		}
	}

	SystemEntry StringToEntry(const string &entry)
	{
		if(entry == "hyperdrive")
			return SystemEntry::HYPERDRIVE;
		else if(entry == "jump drive")
			return SystemEntry::JUMP;
		else if(entry == "wormhole")
			return SystemEntry::WORMHOLE;
		return SystemEntry::TAKE_OFF;
	}

	// Sort the given list of missions in the order they should be offered.
	void SortMissions(list<Mission> &missions, bool hasPriorityMissions, unsigned nonBlockingMissions)
	{
		if(missions.empty())
			return;

		// This list is already in alphabetical order by virtue of the way that the Set
		// class stores objects, so stable sorting on the offer precedence will maintain
		// the alphabetical ordering for missions with the same precedence.
		missions.sort([](const Mission &a, const Mission &b)
			{
				return a.OfferPrecedence() > b.OfferPrecedence();
			});

		// If any of the available missions are "priority" missions, then only priority
		// and non-blocking missions are allowed to offer.
		if(hasPriorityMissions)
			erase_if(missions, [](const Mission &m) noexcept -> bool
				{
					return !m.HasPriority() && !m.IsNonBlocking();
				});
		else if(missions.size() > 1 + nonBlockingMissions)
		{
			// Minor missions only get offered if no other missions (including other
			// minor missions) are competing with them, except for "non-blocking" missions.
			// This is to avoid having two or three missions pop up as soon as you enter the spaceport.
			// Note that the manner in which excess minor missions are discarded means that the
			// minor mission with the lowest precedence is the one that will be offered.
			auto it = missions.begin();
			while(it != missions.end())
			{
				if(it->IsMinor())
				{
					it = missions.erase(it);
					if(missions.size() <= 1 + nonBlockingMissions)
						break;
				}
				else
					++it;
			}
		}
	}
}



// Completely clear all loaded information, to prepare for loading a file or
// creating a new pilot.
void PlayerInfo::Clear()
{
	*this = PlayerInfo();

	Random::Seed(time(nullptr));
	GameData::Revert();
	Messages::Reset();

	delete transactionSnapshot;
	transactionSnapshot = nullptr;
}



// Check if a player has been loaded.
bool PlayerInfo::IsLoaded() const
{
	return !firstName.empty();
}



// Make a new player.
void PlayerInfo::New(const StartConditions &start)
{
	// Clear any previously loaded data.
	Clear();

	// Copy the core information from the full starting scenario.
	startData = start;
	// Copy any ships in the start conditions.
	for(const Ship &ship : start.Ships())
	{
		ships.emplace_back(new Ship(ship));
		ships.back()->SetSystem(&start.GetSystem());
		ships.back()->SetPlanet(&start.GetPlanet());
		ships.back()->SetIsSpecial();
		ships.back()->SetIsYours();
		ships.back()->SetGovernment(GameData::PlayerGovernment());
	}
	// Load starting conditions from a "start" item in the data files. If no
	// such item exists, StartConditions defines default values.
	date = start.GetDate();
	GameData::SetDate(date);
	// Make sure the fleet depreciation object knows it is tracking the player's
	// fleet, not the planet's stock.
	depreciation.Init(ships, date.DaysSinceEpoch());

	SetSystem(start.GetSystem());
	SetPlanet(&start.GetPlanet());
	accounts = start.GetAccounts();
	RegisterDerivedConditions();
	start.GetConditions().Apply();

	// Generate missions that will be available on the first day.
	CreateMissions();

	// Add to the list of events that should happen on certain days.
	for(const auto &it : GameData::Events())
		if(it.second.GetDate())
			AddEvent(it.second, it.second.GetDate());
}



// Load player information from a saved game file.
void PlayerInfo::Load(const filesystem::path &path)
{
	// Make sure any previously loaded data is cleared.
	Clear();

	// A listing of missions and the ships where their cargo or passengers were when the game was saved.
	// Missions and ships are referred to by string UUIDs.
	// Any mission cargo or passengers that were in the player's system will not be recorded here,
	// as that can be safely redistributed from the player's overall CargoHold to any ships in their system.
	map<string, map<string, int>> missionCargoToDistribute;
	map<string, map<string, int>> missionPassengersToDistribute;

	filePath = path.string();
	// Strip anything after the "~" from snapshots, so that the file we save
	// will be the auto-save, not the snapshot.
	size_t pos = filePath.find('~');
	size_t namePos = filePath.length() - Files::Name(filePath).length();
	if(pos != string::npos && pos > namePos)
		filePath = filePath.substr(0, pos) + ".txt";

	// The player may have bribed their current planet in the last session. Ensure
	// we provide the same access to services in this session, too.
	bool hasFullClearance = false;

	// Register derived conditions now, so old primary versions can load into them.
	RegisterDerivedConditions();

	DataFile file(path);
	for(const DataNode &child : file)
	{
		const string &key = child.Token(0);
		bool hasValue = child.Size() >= 2;
		// Basic player information and persistent UI settings:
		if(key == "pilot" && child.Size() >= 3)
		{
			firstName = child.Token(1);
			lastName = child.Token(2);
		}
		else if(key == "date" && child.Size() >= 4)
			date = Date(child.Value(1), child.Value(2), child.Value(3));
		else if(key == "system entry method" && hasValue)
			entry = StringToEntry(child.Token(1));
		else if(key == "previous system" && hasValue)
			previousSystem = GameData::Systems().Get(child.Token(1));
		else if(key == "system" && hasValue)
			system = GameData::Systems().Get(child.Token(1));
		else if(key == "planet" && hasValue)
			planet = GameData::Planets().Get(child.Token(1));
		else if(key == "clearance")
			hasFullClearance = true;
		else if(key == "launching")
			shouldLaunch = true;
		else if(key == "playtime" && hasValue)
			playTime = child.Value(1);
		else if(key == "travel" && hasValue)
			travelPlan.push_back(GameData::Systems().Get(child.Token(1)));
		else if(key == "travel destination" && hasValue)
			travelDestination = GameData::Planets().Get(child.Token(1));
		else if(key == "map coloring" && hasValue)
			mapColoring = child.Value(1);
		else if(key == "map zoom" && hasValue)
			mapZoom = child.Value(1);
		else if(key == "collapsed" && hasValue)
		{
			for(const DataNode &grand : child)
				collapsed[child.Token(1)].insert(grand.Token(0));
		}
		else if(key == "reputation with")
		{
			for(const DataNode &grand : child)
				if(grand.Size() >= 2)
					reputationChanges.emplace_back(
						GameData::Governments().Get(grand.Token(0)), grand.Value(1));
		}
		else if(key == "tribute received")
		{
			for(const DataNode &grand : child)
				if(grand.Size() >= 2)
					tributeReceived[GameData::Planets().Get(grand.Token(0))] = grand.Value(1);
		}
		// Records of things you own:
		else if(key == "ship")
		{
			// Ships owned by the player have various special characteristics:
			ships.push_back(make_shared<Ship>(child, &conditions));
			ships.back()->SetIsSpecial();
			ships.back()->SetIsYours();
			// Defer finalizing this ship until we have processed all changes to game state.
		}
		else if(key == "groups" && hasValue && !ships.empty())
			groups[ships.back().get()] = child.Value(1);
		else if(key == "storage")
		{
			for(const DataNode &grand : child)
				if(grand.Token(0) == "planet" && grand.Size() >= 2)
				{
					const Planet *planet = GameData::Planets().Get(grand.Token(1));
					for(const DataNode &great : grand)
					{
						if(great.Token(0) == "cargo")
						{
							CargoHold &storage = planetaryStorage[planet];
							storage.Load(great);
						}
					}
				}
		}
		else if(key == "licenses")
		{
			for(const DataNode &grand : child)
				AddLicense(grand.Token(0));
		}
		else if(key == "account")
			accounts.Load(child, true);
		else if(key == "cargo")
			cargo.Load(child);
		else if(key == "basis")
		{
			for(const DataNode &grand : child)
				if(grand.Size() >= 2)
					costBasis[grand.Token(0)] += grand.Value(1);
		}
		else if(key == "stock")
		{
			for(const DataNode &grand : child)
				if(grand.Size() >= 2)
					stock[GameData::Outfits().Get(grand.Token(0))] += grand.Value(1);
		}
		else if(key == "fleet depreciation")
			depreciation.Load(child);
		else if(key == "stock depreciation")
			stockDepreciation.Load(child);

		// Records of things you have done or are doing, or have happened to you:
		else if(key == "mission")
		{
			missions.emplace_back(child, &conditions, &visitedSystems, &visitedPlanets);
			cargo.AddMissionCargo(&missions.back());
		}
		else if((key == "mission cargo" || key == "mission passengers") && child.HasChildren())
		{
			map<string, map<string, int>> &toDistribute = (key == "mission cargo")
					? missionCargoToDistribute : missionPassengersToDistribute;
			for(const DataNode &grand : child)
				if(grand.Token(0) == "player ships" && grand.HasChildren())
					for(const DataNode &great : grand)
					{
						if(great.Size() != 3)
							continue;
						toDistribute[great.Token(0)][great.Token(1)] = great.Value(2);
					}
		}
		else if(key == "available job")
			availableJobs.emplace_back(child, &conditions, &visitedSystems, &visitedPlanets);
		else if(key == "sort type")
			availableSortType = static_cast<SortType>(child.Value(1));
		else if(key == "sort descending")
			availableSortAsc = false;
		else if(key == "separate deadline")
			sortSeparateDeadline = true;
		else if(key == "separate possible")
			sortSeparatePossible = true;
		else if(key == "available mission")
			availableMissions.emplace_back(child, &conditions, &visitedSystems, &visitedPlanets);
		else if(key == "conditions")
			conditions.Load(child);
		else if(key == "gifted ships" && child.HasChildren())
		{
			for(const DataNode &grand : child)
				giftedShips[grand.Token(0)] = EsUuid::FromString(grand.Token(1));
		}
		else if(key == "event")
			gameEvents.emplace(GameEvent(child, &conditions));
		else if(key == "changes")
		{
			for(const DataNode &grand : child)
				dataChanges.push_back(grand);
		}
		else if(key == "economy")
			economy = child;
		else if(key == "destroyed" && hasValue)
			destroyedPersons.push_back(child.Token(1));

		// Records of things you have discovered:
		else if(key == "visited" && hasValue)
			Visit(*GameData::Systems().Get(child.Token(1)));
		else if(key == "visited planet" && hasValue)
			Visit(*GameData::Planets().Get(child.Token(1)));
		else if(key == "harvested")
		{
			for(const DataNode &grand : child)
				if(grand.Size() >= 2)
					harvested.emplace(
						GameData::Systems().Get(grand.Token(0)),
						GameData::Outfits().Get(grand.Token(1)));
		}
		else if(key == "logbook")
		{
			for(const DataNode &grand : child)
			{
				if(grand.Size() >= 3)
				{
					Date date(grand.Value(0), grand.Value(1), grand.Value(2));
					string text;
					for(const DataNode &great : grand)
					{
						if(!text.empty())
							text += "\n\t";
						text += great.Token(0);
					}
					logbook.emplace(date, text);
				}
				else if(grand.Size() >= 2)
				{
					string &text = specialLogs[grand.Token(0)][grand.Token(1)];
					for(const DataNode &great : grand)
					{
						if(!text.empty())
							text += "\n\t";
						text += great.Token(0);
					}
				}
			}
		}
		else if(key == "start")
			startData.Load(child);
	}
	// Modify the game data with any changes that were loaded from this file.
	ApplyChanges();
	// Ensure the player is in a valid state after loading & applying changes.
	ValidateLoad();
	// Cache the remaining number of days for all deadline missions.
	CalculateRemainingDeadlines();

	// Restore access to services, if it was granted previously.
	if(planet && hasFullClearance)
		planet->Bribe();

	// Based on the ships that were loaded, calculate the player's capacity for
	// cargo and passengers.
	UpdateCargoCapacities();

	auto DistributeMissionCargo = [](const map<string, map<string, int>> &toDistribute, const list<Mission> &missions,
			vector<shared_ptr<Ship>> &ships, CargoHold &cargo, bool passengers) -> void
	{
		for(const auto &it : toDistribute)
		{
			const auto missionIt = find_if(missions.begin(), missions.end(),
					[&it](const Mission &mission) { return mission.UUID().ToString() == it.first; });
			if(missionIt != missions.end())
			{
				const Mission *cargoOf = &*missionIt;
				for(const auto &shipCargo : it.second)
				{
					auto shipIt = find_if(ships.begin(), ships.end(),
							[&shipCargo](const shared_ptr<Ship> &ship) { return ship->UUID().ToString() == shipCargo.first; });
					if(shipIt != ships.end())
					{
						Ship *destination = shipIt->get();
						if(passengers)
							cargo.TransferPassengers(cargoOf, shipCargo.second, destination->Cargo());
						else
							cargo.Transfer(cargoOf, shipCargo.second, destination->Cargo());
					}
				}
			}
		}
	};

	DistributeMissionCargo(missionCargoToDistribute, missions, ships, cargo, false);
	DistributeMissionCargo(missionPassengersToDistribute, missions, ships, cargo, true);

	// If no depreciation record was loaded, every item in the player's fleet
	// will count as non-depreciated.
	if(!depreciation.IsLoaded())
		depreciation.Init(ships, date.DaysSinceEpoch());
}



// Load the most recently saved player (if any). Returns false when no save was loaded.
bool PlayerInfo::LoadRecent()
{
	string recentPath = Files::Read(Files::Config() / "recent.txt");
	// Trim trailing whitespace (including newlines) from the path.
	while(!recentPath.empty() && recentPath.back() <= ' ')
		recentPath.pop_back();

	if(recentPath.empty() || !Files::Exists(recentPath))
	{
		Clear();
		return false;
	}

	Load(recentPath);
	return true;
}



// Save this player. The file name is based on the player's name.
void PlayerInfo::Save() const
{
	// Don't save dead players or players that are not fully created.
	if(!CanBeSaved())
		return;

	// Remember that this was the most recently saved player.
	Files::Write(Files::Config() / "recent.txt", filePath + '\n');

	if(filePath.rfind(".txt") == filePath.length() - 4)
	{
		// Only update the backups if this save will have a newer date.
		SavedGame saved(filePath);
		if(saved.GetDate() != date.ToString())
		{
			string root = filePath.substr(0, filePath.length() - 4);
			const int previousCount = Preferences::GetPreviousSaveCount();
			const string rootPrevious = root + "~~previous-";
			for(int i = previousCount - 1; i > 0; --i)
			{
				const string toMove = rootPrevious + to_string(i) + ".txt";
				if(Files::Exists(toMove))
					Files::Move(toMove, rootPrevious + to_string(i + 1) + ".txt");
			}
			if(Files::Exists(filePath))
				Files::Move(filePath, rootPrevious + "1.txt");
			if(planet->HasServices())
				Save(rootPrevious + "spaceport.txt");
		}
	}

	Save(filePath);

	// Save global conditions:
	DataWriter globalConditions(Files::Config() / "global conditions.txt");
	GameData::GlobalConditions().Save(globalConditions);
}



// Get the base file name for the player, without the ".txt" extension. This
// will usually be "<first> <last>", but may be different if multiple players
// exist with the same name, in which case a number is appended.
string PlayerInfo::Identifier() const
{
	string name = Files::Name(filePath);
	return (name.length() < 4) ? "" : name.substr(0, name.length() - 4);
}



void PlayerInfo::StartTransaction()
{
	assert(!transactionSnapshot && "Starting PlayerInfo transaction while one is already active");

	// Create in-memory DataWriter and save to it.
	transactionSnapshot = new DataWriter();
	Save(*transactionSnapshot);
}



void PlayerInfo::FinishTransaction()
{
	assert(transactionSnapshot && "Finishing PlayerInfo while one hasn't been started");
	delete transactionSnapshot;
	transactionSnapshot = nullptr;
}



// Apply the given set of changes to the game data.
void PlayerInfo::AddChanges(list<DataNode> &changes, bool instantChanges)
{
	bool changedSystems = false;
	for(const DataNode &change : changes)
	{
		const string &key = change.Token(0);
		changedSystems |= (key == "system");
		changedSystems |= (key == "link");
		changedSystems |= (key == "unlink");
		GameData::Change(change, *this);
	}
	if(changedSystems)
	{
		// Recalculate what systems have been seen.
		GameData::UpdateSystems();
		seen.clear();
		for(const System *system : visitedSystems)
		{
			seen.insert(system);
			for(const System *neighbor : system->VisibleNeighbors())
				if(!neighbor->Hidden() || system->Links().contains(neighbor))
					seen.insert(neighbor);
		}
		// Update the deadline calculations for missions in case the system
		// changes resulted in a change in DistanceMap calculations.
		if(instantChanges)
			CalculateRemainingDeadlines();
	}

	// Only move the changes into my list if they are not already there.
	if(&changes != &dataChanges)
		dataChanges.splice(dataChanges.end(), changes);
}



// Add an event that will happen at the given date.
void PlayerInfo::AddEvent(GameEvent event, const Date &date)
{
	// Check if the event should be applied right now or scheduled for later.
	if(date <= this->date)
	{
		GameEvent eventCopy = event;
		list<DataNode> eventChanges = {eventCopy.Apply(*this)};
		if(!eventChanges.empty())
			AddChanges(eventChanges, true);
	}
	else
	{
		event.SetDate(date);
		gameEvents.insert(std::move(event));
	}
}



// Mark this player as dead, and handle the changes to the player's fleet.
void PlayerInfo::Die(int response, const shared_ptr<Ship> &capturer)
{
	isDead = true;
	// The player loses access to all their ships if they die on a planet.
	if(GetPlanet() || !flagship)
		ships.clear();
	// If the flagship should explode due to choices made in a mission's
	// conversation, it should still appear in the player's ship list (but
	// will be red, because it is dead). The player's escorts will scatter
	// automatically, as they have a now-dead parent.
	else if(response == Conversation::EXPLODE)
		flagship->Destroy();
	// If it died in open combat, it is already marked destroyed.
	else if(!flagship->IsDestroyed())
	{
		// The player died due to the failed capture of an NPC or a
		// "mutiny". The flagship is either captured or changes government.
		if(!flagship->IsYours())
		{
			// The flagship was already captured, via BoardingPanel,
			// and its parent-escort relationships were updated in
			// Ship::WasCaptured().
		}
		// The referenced ship may not be boarded by the player, so before
		// letting it capture the flagship it must be near the flagship.
		else if(capturer && capturer->Position().Distance(flagship->Position()) <= 1.)
			flagship->WasCaptured(capturer);
		else
		{
			// A "mutiny" occurred.
			flagship->SetIsYours(false);
			// TODO: perhaps allow missions to set the new government.
			flagship->SetGovernment(GameData::Governments().Get("Independent"));
			// Your escorts do not follow it, nor does it wait for them.
			for(const shared_ptr<Ship> &ship : ships)
				ship->SetParent(nullptr);
		}
		// Remove the flagship from the player's ship list.
		auto it = find(ships.begin(), ships.end(), flagship);
		if(it != ships.end())
			ships.erase(it);
	}
}



// Query whether this player is dead.
bool PlayerInfo::IsDead() const
{
	return isDead;
}



// Get the player's first name.
const string &PlayerInfo::FirstName() const
{
	return firstName;
}



// Get the player's last name.
const string &PlayerInfo::LastName() const
{
	return lastName;
}



// Set the player's name. This will also set the saved game file name.
void PlayerInfo::SetName(const string &first, const string &last)
{
	firstName = first;
	lastName = last;

	string fileName = first + " " + last;

	// If there are multiple pilots with the same name, append a number to the
	// pilot name to generate a unique file name.
	filePath = (Files::Saves() / fileName).string();
	int index = 0;
	while(true)
	{
		string path = filePath;
		if(index++)
			path += " " + to_string(index);
		path += ".txt";

		if(!Files::Exists(path))
		{
			filePath.swap(path);
			break;
		}
	}
}



// Get the current date (game world, not real world).
const Date &PlayerInfo::GetDate() const
{
	return date;
}



// Set the date, and perform all daily actions the given number of times.
void PlayerInfo::AdvanceDate(int amount)
{
	if(amount <= 0)
		return;
	while(amount--)
	{
		++date;

		// Check if any special events should happen today.
		auto it = gameEvents.begin();
		list<DataNode> eventChanges;
		while(it != gameEvents.end() && date >= it->GetDate())
		{
			GameEvent event = *it;
			eventChanges.splice(eventChanges.end(), event.Apply(*this));
			it = gameEvents.erase(it);
		}
		if(!eventChanges.empty())
			AddChanges(eventChanges);

		// Check if any missions have failed because of deadlines and
		// do any daily mission actions for those that have not failed.
		for(Mission &mission : missions)
		{
			if(mission.CheckDeadline(date) && mission.IsVisible())
				Messages::Add("You failed to meet the deadline for the mission \"" + mission.DisplayName() + "\".",
					Messages::Importance::Highest);
			if(!mission.IsFailed())
				mission.Do(Mission::DAILY, *this);
		}

		DoAccounting();
	}
	// Reset the reload counters for all your ships.
	for(const shared_ptr<Ship> &ship : ships)
		ship->GetArmament().ReloadAll();

	// Recalculate how many days you have left for deadline missions.
	// We need to fully recalculate the number of days remaining instead of
	// just reducing the cached values by 1 because the player may have
	// explored new systems that change the DistanceMap calculations.
	CalculateRemainingDeadlines();
}



const CoreStartData &PlayerInfo::StartData() const noexcept
{
	return startData;
}



void PlayerInfo::SetSystemEntry(SystemEntry entryType)
{
	entry = entryType;
}



SystemEntry PlayerInfo::GetSystemEntry() const
{
	return entry;
}



// Set the player's current start system, and mark that system as visited.
void PlayerInfo::SetSystem(const System &system)
{
	this->previousSystem = this->system;
	this->system = &system;
	Visit(system);
}



// Get the player's current star system.
const System *PlayerInfo::GetSystem() const
{
	return system;
}



const System *PlayerInfo::GetPreviousSystem() const
{
	return previousSystem;
}



// Set the planet the player is landed on.
void PlayerInfo::SetPlanet(const Planet *planet)
{
	this->planet = planet;
}



// Get the planet the player is landed on.
const Planet *PlayerInfo::GetPlanet() const
{
	return planet;
}



// If the player is landed, return the stellar object they are on. Some planets
// (e.g. ringworlds) may include multiple stellar objects in the same system.
const StellarObject *PlayerInfo::GetStellarObject() const
{
	if(!system || !planet)
		return nullptr;

	double closestDistance = numeric_limits<double>::infinity();
	const StellarObject *closestObject = nullptr;
	for(const StellarObject &object : system->Objects())
		if(object.GetPlanet() == planet)
		{
			if(!Flagship())
				return &object;

			double distance = Flagship()->Position().Distance(object.Position());
			if(distance < closestDistance)
			{
				closestDistance = distance;
				closestObject = &object;
			}
		}
	return closestObject;
}



// Check if the player must take off immediately.
bool PlayerInfo::ShouldLaunch() const
{
	return shouldLaunch;
}



// Access the player's account information.
const Account &PlayerInfo::Accounts() const
{
	return accounts;
}



// Access the player's account information (and allow modifying it).
Account &PlayerInfo::Accounts()
{
	return accounts;
}



// Calculate how much the player pays in daily salaries.
int64_t PlayerInfo::Salaries() const
{
	// Don't count extra crew on anything but the flagship.
	int64_t crew = 0;
	const Ship *flagship = Flagship();
	if(flagship)
		crew = flagship->Crew() - flagship->RequiredCrew();

	// A ship that is "parked" remains on a planet and requires no salaries.
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsParked() && !ship->IsDestroyed())
			crew += ship->RequiredCrew();
	if(!crew)
		return 0;

	// Every crew member except the player receives 100 credits per day.
	return 100 * (crew - 1);
}



// Calculate the daily maintenance cost and generated income for all ships and in cargo outfits.
PlayerInfo::FleetBalance PlayerInfo::MaintenanceAndReturns() const
{
	FleetBalance b;

	// If the player is landed, then cargo will be in the player's
	// pooled cargo. Check there so that the bank panel can display the
	// correct total maintenance costs. When launched all cargo will be
	// in the player's ships instead of in the pooled cargo, so no outfit
	// will be counted twice.
	for(const auto &outfit : Cargo().Outfits())
	{
		b.maintenanceCosts += max<int64_t>(0, outfit.first->Get("maintenance costs")) * outfit.second;
		b.assetsReturns += max<int64_t>(0, outfit.first->Get("income")) * outfit.second;
	}
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsDestroyed())
		{
			b.maintenanceCosts += max<int64_t>(0, ship->Attributes().Get("maintenance costs"));
			b.assetsReturns += max<int64_t>(0, ship->Attributes().Get("income"));
			for(const auto &outfit : ship->Cargo().Outfits())
			{
				b.maintenanceCosts += max<int64_t>(0, outfit.first->Get("maintenance costs")) * outfit.second;
				b.assetsReturns += max<int64_t>(0, outfit.first->Get("income")) * outfit.second;
			}
			if(!ship->IsParked())
			{
				b.maintenanceCosts += max<int64_t>(0, ship->Attributes().Get("operating costs"));
				b.assetsReturns += max<int64_t>(0, ship->Attributes().Get("operating income"));
			}
		}
	return b;
}



void PlayerInfo::AddLicense(const string &name)
{
	licenses.insert(name);
}



void PlayerInfo::RemoveLicense(const string &name)
{
	licenses.erase(name);
}



bool PlayerInfo::HasLicense(const string &name) const
{
	return licenses.contains(name);
}



const set<string> &PlayerInfo::Licenses() const
{
	return licenses;
}



// Get a pointer to the ship that the player controls. This is usually the first
// ship in the list.
const Ship *PlayerInfo::Flagship() const
{
	return const_cast<PlayerInfo *>(this)->FlagshipPtr().get();
}



// Get a pointer to the ship that the player controls. This is usually the first
// ship in the list.
Ship *PlayerInfo::Flagship()
{
	return FlagshipPtr().get();
}



// Determine which ship is the flagship and return the shared pointer to it.
const shared_ptr<Ship> &PlayerInfo::FlagshipPtr()
{
	if(!flagship)
	{
		bool clearance = false;
		if(planet)
			clearance = planet->CanLand() || HasClearance();
		for(const shared_ptr<Ship> &it : ships)
		{
			if(it->IsParked())
				continue;
			if(it->GetSystem() != system)
				continue;
			if(!it->CanBeFlagship())
				continue;
			const bool sameLocation = !planet || it->GetPlanet() == planet;
			if(sameLocation || (clearance && !it->GetPlanet() && planet->IsAccessible(it.get())))
			{
				flagship = it;
				break;
			}
		}
	}

	static const shared_ptr<Ship> empty;
	return (flagship && flagship->IsYours()) ? flagship : empty;
}



// Access the full list of ships that the player owns.
const vector<shared_ptr<Ship>> &PlayerInfo::Ships() const
{
	return ships;
}



// Inspect the flightworthiness of the player's active fleet, individually and
// as a whole, to determine which ships cannot travel with the group.
// Returns a mapping of ships to the reason their flight check failed.
map<const shared_ptr<Ship>, vector<string>> PlayerInfo::FlightCheck() const
{
	// Count of all bay types in the active fleet.
	auto bayCount = map<string, size_t>{};
	// Classification of the present ships by category. Parked ships are ignored.
	auto categoryCount = map<string, vector<shared_ptr<Ship>>>{};

	auto flightChecks = map<const shared_ptr<Ship>, vector<string>>{};
	for(const auto &ship : ships)
		if(ship->GetSystem() && !ship->IsDisabled() && !ship->IsParked())
		{
			auto checks = ship->FlightCheck();
			if(!checks.empty())
				flightChecks.emplace(ship, checks);

			// Only check bays for in-system ships.
			if(ship->GetSystem() != system)
				continue;

			categoryCount[ship->Attributes().Category()].emplace_back(ship);
			// Ensure bayCount has an entry for this category for the special case
			// where we have no bays at all available for this type of ship.
			if(ship->CanBeCarried())
				bayCount.emplace(ship->Attributes().Category(), 0);

			if(ship->CanBeCarried() || !ship->HasBays())
				continue;

			for(auto &bay : ship->Bays())
			{
				++bayCount[bay.category];
				// The bays should always be empty. But if not, count that ship too.
				if(bay.ship)
				{
					Logger::LogError("Expected bay to be empty for " + ship->TrueModelName() + ": " + ship->GivenName());
					categoryCount[bay.ship->Attributes().Category()].emplace_back(bay.ship);
				}
			}
		}

	// Identify transportable ships that cannot jump and have no bay to be carried in.
	for(auto &bayType : bayCount)
	{
		const auto &shipsOfType = categoryCount[bayType.first];
		if(shipsOfType.empty())
			continue;
		for(const auto &carriable : shipsOfType)
		{
			if(carriable->JumpsRemaining() != 0)
			{
				// This ship can travel between systems and does not require a bay.
			}
			// This ship requires a bay to travel between systems.
			else if(bayType.second > 0)
				--bayType.second;
			else
			{
				// Include the lack of bay availability amongst any other
				// warnings for this carriable ship.
				auto it = flightChecks.find(carriable);
				string warning = "no bays?";
				if(it != flightChecks.end())
					it->second.emplace_back(warning);
				else
					flightChecks.emplace(carriable, vector<string>{warning});
			}
		}
	}
	return flightChecks;
}



// Add a captured ship to your fleet.
void PlayerInfo::AddShip(const shared_ptr<Ship> &ship)
{
	ships.push_back(ship);
	ship->SetIsSpecial();
	ship->SetIsYours();
	if(ship->HasBays())
		displayCarrierHelp = true;
}



// Adds a ship of the given model with the given name to the player's fleet.
void PlayerInfo::BuyShip(const Ship *model, const string &name)
{
	if(!model)
		return;

	int day = date.DaysSinceEpoch();
	int64_t cost = stockDepreciation.Value(*model, day);
	if(accounts.Credits() >= cost)
	{
		AddStockShip(model, name);

		accounts.AddCredits(-cost);
		flagship.reset();

		depreciation.Buy(*model, day, &stockDepreciation);
		for(const auto &it : model->Outfits())
			stock[it.first] -= it.second;

		if(ships.back()->HasBays())
			displayCarrierHelp = true;
	}
}



// Because this ship is being gifted, it costs nothing and starts fully depreciated.
const Ship *PlayerInfo::GiftShip(const Ship *model, const string &name, const string &id)
{
	if(!model)
		return nullptr;

	AddStockShip(model, name);

	flagship.reset();

	// If an id was given, associate and store it with the UUID of the gifted ship.
	if(!id.empty())
		giftedShips[id].Clone(ships.back()->UUID());

	return ships.back().get();
}



// Sell the given ship (if it belongs to the player).
void PlayerInfo::SellShip(const Ship *selected, bool storeOutfits)
{
	for(auto it = ships.begin(); it != ships.end(); ++it)
		if(it->get() == selected)
		{
			int day = date.DaysSinceEpoch();
			int64_t cost;

			// Passing a pointer to Value gets only the hull cost. Passing a reference
			// gets hull and outfit costs.
			if(storeOutfits)
				cost = depreciation.Value(selected, day);
			else
				cost = depreciation.Value(*selected, day);

			// Record the transfer of this ship in the depreciation and stock info.
			stockDepreciation.Buy(*selected, day, &depreciation, storeOutfits);
			if(storeOutfits)
			{
				CargoHold &storage = Storage();
				for(const auto &it : selected->Outfits())
					storage.Add(it.first, it.second);
			}
			else
			{
				for(const auto &it : selected->Outfits())
					stock[it.first] += it.second;
			}

			accounts.AddCredits(cost);
			ForgetGiftedShip(*it->get());
			ships.erase(it);
			flagship.reset();
			break;
		}
}



// Take the ship from the player, if a model is specified this will permanently remove outfits in said model,
// instead of allowing the player to buy them back by putting them in the stock.
void PlayerInfo::TakeShip(const Ship *shipToTake, const Ship *model, bool takeOutfits)
{
	for(auto it = ships.begin(); it != ships.end(); ++it)
		if(it->get() == shipToTake)
		{
			// Record the transfer of this ship in the depreciation and stock info.
			stockDepreciation.Buy(*shipToTake, date.DaysSinceEpoch(), &depreciation);
			if(takeOutfits)
				for(const auto &it : shipToTake->Outfits())
				{
					// We only take all of the outfits specified in the model without putting them in the stock.
					// The extra outfits of this ship are transferred into the stock.
					int amountToTake = 0;
					if(model)
					{
						auto outfit = model->Outfits().find(it.first);
						if(outfit != model->Outfits().end())
							amountToTake = max(it.second, outfit->second);
					}
					stock[it.first] += it.second - amountToTake;
				}
			ForgetGiftedShip(*it->get(), false);
			ships.erase(it);
			flagship.reset();
			break;
		}
}



vector<shared_ptr<Ship>>::iterator PlayerInfo::DisownShip(const Ship *selected)
{
	for(auto it = ships.begin(); it != ships.end(); ++it)
		if(it->get() == selected)
		{
			flagship.reset();
			ForgetGiftedShip(*it->get());
			it = ships.erase(it);
			return (it == ships.begin()) ? it : --it;
		}
	return ships.begin();
}



// Park or unpark the given ship. A parked ship remains on a planet instead of
// flying with the player, and requires no daily crew payments.
void PlayerInfo::ParkShip(const Ship *selected, bool isParked)
{
	for(auto &ship : ships)
		if(ship.get() == selected)
		{
			isParked &= !ship->IsDisabled();
			ship->SetIsParked(isParked);
			UpdateCargoCapacities();
			flagship.reset();
			return;
		}
}



// Rename the given ship.
void PlayerInfo::RenameShip(const Ship *selected, const string &name)
{
	for(auto &ship : ships)
		if(ship.get() == selected)
		{
			ship->SetGivenName(name);
			return;
		}
}



// Change the order of the given ship in the list.
void PlayerInfo::ReorderShip(int fromIndex, int toIndex)
{
	// Make sure the indices are valid.
	if(fromIndex == toIndex)
		return;
	if(static_cast<unsigned>(fromIndex) >= ships.size())
		return;
	if(static_cast<unsigned>(toIndex) >= ships.size())
		return;

	// Reorder the list.
	shared_ptr<Ship> ship = ships[fromIndex];
	auto oldFirstShip = ships[0];
	ships.erase(ships.begin() + fromIndex);
	ships.insert(ships.begin() + toIndex, ship);
	auto newFirstShip = ships[0];
	// Check if the ship in the first position can be a flagship and is in the current system.
	HandleFlagshipParking(oldFirstShip.get(), newFirstShip.get());
	flagship.reset();
}



void PlayerInfo::SetShipOrder(const vector<shared_ptr<Ship>> &newOrder)
{
	// Check if the incoming vector contains the same elements
	if(std::is_permutation(ships.begin(), ships.end(), newOrder.begin()))
	{
		Ship *oldFirstShip = ships.front().get();
		ships = newOrder;
		Ship *newFirstShip = ships.front().get();
		// Check if the position of the flagship has changed, and the ship in the first position
		// can be a flagship and is in the current system.
		HandleFlagshipParking(oldFirstShip, newFirstShip);
		flagship.reset();
	}
	else
		throw runtime_error("Cannot reorder ships because the new order does not contain the same ships");
}



// Find out how attractive the player's fleet is to pirates. Aside from a
// heavy freighter, no single ship should attract extra pirate attention.
pair<double, double> PlayerInfo::RaidFleetFactors() const
{
	double attraction = 0.;
	double deterrence = 0.;
	for(const shared_ptr<Ship> &ship : Ships())
	{
		if(ship->IsParked() || ship->IsDestroyed())
			continue;

		attraction += ship->Attraction();
		deterrence += ship->Deterrence();
	}

	return make_pair(attraction, deterrence);
}



double PlayerInfo::RaidFleetAttraction(const RaidFleet &raid, const System *system) const
{
	double attraction = 0.;
	const Fleet *raidFleet = raid.GetFleet();
	const Government *raidGov = raidFleet ? raidFleet->GetGovernment() : nullptr;
	if(raidGov && raidGov->IsEnemy())
	{
		// The player's base attraction to a fleet is determined by their fleet attraction minus
		// their fleet deterrence, minus whatever the minimum attraction of this raid fleet is.
		pair<double, double> factors = RaidFleetFactors();
		// If there is a maximum attraction for this fleet, and we are above it, it will not spawn.
		if(raid.MaxAttraction() > 0 && factors.first > raid.MaxAttraction())
			return 0;

		attraction = .005 * (factors.first - factors.second - raid.MinAttraction());
		// Then we consider the strength of other fleets in the system.
		int64_t raidStrength = raidFleet->Strength();
		if(system && raidStrength)
			for(const auto &fleet : system->Fleets())
			{
				const Government *gov = fleet.Get()->GetGovernment();
				if(gov)
				{
					// If this fleet is neutral or hostile to both the player and raid fleet, it has
					// no impact on the attraction. If the fleet is hostile to only the player, the
					// raid attraction will increase. If the fleet is hostile to only the raid fleet,
					// the raid attraction will decrease. The amount of increase or decrease is determined
					// by the strength of the fleet relative to the raid fleet. System fleets which are
					// stronger have a larger impact.
					double strength = fleet.Get()->Strength() / fleet.Period();
					attraction -= (gov->IsEnemy(raidGov) - gov->IsEnemy()) * (strength / raidStrength);
				}
			}
	}
	return max(0., min(1., attraction));
}



// Get cargo information.
CargoHold &PlayerInfo::Cargo()
{
	return cargo;
}



// Get cargo information.
const CargoHold &PlayerInfo::Cargo() const
{
	return cargo;
}



// Get items stored on the player's current planet.
CargoHold &PlayerInfo::Storage()
{
	assert(planet && "can't get planetary storage in-flight");
	return planetaryStorage[planet];
}



// Get planetary storage information for all planets (for map and overviews).
const map<const Planet *, CargoHold> &PlayerInfo::PlanetaryStorage() const
{
	return planetaryStorage;
}



// Adjust the cost basis for the given commodity.
void PlayerInfo::AdjustBasis(const string &commodity, int64_t adjustment)
{
	costBasis[commodity] += adjustment;
}



// Get the cost basis for some number of tons of the given commodity. Each ton
// of the commodity that you own is assumed to have the same basis.
int64_t PlayerInfo::GetBasis(const string &commodity, int tons) const
{
	// Handle cost basis even when not landed on a planet.
	int total = cargo.Get(commodity);
	for(const auto &ship : ships)
		total += ship->Cargo().Get(commodity);
	if(!total)
		return 0;

	auto it = costBasis.find(commodity);
	int64_t basis = (it == costBasis.end()) ? 0 : it->second;
	return (basis * tons) / total;
}



// Call this after missions update, if leaving the outfitter, shipyard, or
// hiring panel, or after backing out of a take-off warning.
// Updates the information on how much space is available.
void PlayerInfo::UpdateCargoCapacities()
{
	int size = 0;
	int bunks = 0;
	flagship = FlagshipPtr();
	for(const shared_ptr<Ship> &ship : ships)
		if(ship->GetPlanet() == planet && !ship->IsParked())
		{
			size += ship->Attributes().Get("cargo space");
			int crew = (ship == flagship ? ship->Crew() : ship->RequiredCrew());
			bunks += ship->Attributes().Get("bunks") - crew;
		}
	cargo.SetSize(size);
	cargo.SetBunks(bunks);
}



// Switch cargo from being stored in ships to being stored here. Also recharge
// ships, check for mission completion, and apply fines for contraband.
void PlayerInfo::Land(UI *ui)
{
	// This can only be done while landed.
	if(!system || !planet)
		return;

	if(!freshlyLoaded)
		Audio::Play(Audio::Get("landing"), SoundCategory::ENGINE);
	Audio::PlayMusic(planet->MusicName());

	// Mark this planet as visited.
	Visit(*planet);
	if(planet == travelDestination)
		travelDestination = nullptr;

	// Remove any ships that have been destroyed or captured.
	map<string, int> lostCargo;
	vector<shared_ptr<Ship>>::iterator it = ships.begin();
	while(it != ships.end())
	{
		if((*it)->IsDestroyed() || !(*it)->IsYours())
		{
			// If any of your ships are destroyed, your cargo "cost basis" should
			// be adjusted based on what you lost.
			for(const auto &cargo : (*it)->Cargo().Commodities())
				if(cargo.second)
					lostCargo[cargo.first] += cargo.second;
			// Also, the ship and everything in it should be removed from your
			// depreciation records. Transfer it to a throw-away record:
			Depreciation().Buy(**it, date.DaysSinceEpoch(), &depreciation);

			ForgetGiftedShip(*it->get());
			it = ships.erase(it);
		}
		else
			++it;
	}

	// "Unload" all fighters, so they will get recharged, etc.
	for(const shared_ptr<Ship> &ship : ships)
		ship->UnloadBays();

	// Ships that are landed with you on the planet should fully recharge.
	// Those in remote systems restore what they can without landing.
	bool clearance = HasClearance();
	const bool canUseServices = planet->CanUseServices();
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsParked() && !ship->IsDisabled())
		{
			if(ship->GetSystem() == system)
			{
				const bool alreadyLanded = ship->GetPlanet() == planet;
				if(alreadyLanded || planet->CanLand(*ship) || (clearance && planet->IsAccessible(ship.get())))
				{
					const Port &port = planet->GetPort();
					ship->Recharge(canUseServices ? port.GetRecharges() : Port::RechargeType::None,
						port.HasService(Port::ServicesType::HireCrew));
					if(!ship->GetPlanet())
						ship->SetPlanet(planet);
				}
				// Ships that cannot land with the flagship choose the most suitable planet
				// in the system.
				else
				{
					const StellarObject *landingObject = AI::FindLandingLocation(*ship);
					if(!landingObject)
						landingObject = AI::FindLandingLocation(*ship, false);
					if(landingObject)
					{
						const Planet *landingPlanet = landingObject->GetPlanet();
						const Port &port = landingPlanet->GetPort();
						ship->Recharge(landingPlanet->CanUseServices() ? port.GetRecharges() : Port::RechargeType::None,
							port.HasService(Port::ServicesType::HireCrew));
						ship->SetPlanet(landingPlanet);
					}
					else
						ship->Recharge(Port::RechargeType::None, false);
				}
			}
			else
				ship->Recharge(Port::RechargeType::None, false);
		}

	// Cargo management needs to be done after updating ship locations (above).
	UpdateCargoCapacities();
	// If the player is actually landing (rather than simply loading the game),
	// new fines may be levied.
	if(!freshlyLoaded)
		Fine(ui);
	// Ships that are landed with you on the planet should pool all their cargo together.
	PoolCargo();
	// Adjust cargo cost basis for any cargo lost due to a ship being destroyed.
	for(const auto &it : lostCargo)
		AdjustBasis(it.first, -(costBasis[it.first] * it.second) / (cargo.Get(it.first) + it.second));

	// Evaluate changes to NPC spawning criteria.
	if(!freshlyLoaded)
		UpdateMissionNPCs();

	// Update missions that are completed, or should be failed.
	StepMissions(ui);
	UpdateCargoCapacities();

	// Create whatever missions this planet has to offer.
	if(!freshlyLoaded)
		CreateMissions();
	// Upon loading the game, prompt the player about any paused missions, but if there are many
	// do not name them all (since this would overflow the screen).
	else if(ui && !inactiveMissions.empty())
	{
		string message = "These active missions or jobs were deactivated due to a missing definition"
			" - perhaps you recently removed a plugin?\n";
		auto mit = inactiveMissions.rbegin();
		int named = 0;
		while(mit != inactiveMissions.rend() && (++named < 10))
		{
			message += "\t\"" + mit->DisplayName() + "\"\n";
			++mit;
		}
		if(mit != inactiveMissions.rend())
			message += " and " + to_string(distance(mit, inactiveMissions.rend())) + " more.\n";
		message += "They will be reactivated when the necessary plugin is reinstalled.";
		ui->Push(new Dialog(message));
	}

	// Hire extra crew back if any were lost in-flight (i.e. boarding) or
	// some bunks were freed up upon landing (i.e. completed missions).
	if(Preferences::Has("Rehire extra crew when lost")
			&& (planet->GetPort().HasService(Port::ServicesType::HireCrew) && canUseServices) && flagship)
	{
		int added = desiredCrew - flagship->Crew();
		if(added > 0)
		{
			flagship->AddCrew(added);
			Messages::Add("You hire " + to_string(added) + (added == 1
					? " extra crew member to fill your now-empty bunk."
					: " extra crew members to fill your now-empty bunks."), Messages::Importance::High);
		}
	}

	freshlyLoaded = false;
	flagship.reset();
}



// Load the cargo back into your ships. This may require selling excess, in
// which case a message will be returned.
bool PlayerInfo::TakeOff(UI *ui, const bool distributeCargo)
{
	// This can only be done while landed.
	if(!system || !planet)
		return false;

	flagship = FlagshipPtr();
	if(!flagship)
		return false;

	shouldLaunch = false;
	Audio::Play(Audio::Get("takeoff"), SoundCategory::ENGINE);

	// Jobs are only available when you are landed.
	availableJobs.clear();
	availableMissions.clear();
	doneMissions.clear();
	stock.clear();

	// Special persons who appeared last time you left the planet, can appear again.
	GameData::ResetPersons();

	// Store the total cargo counts in case we need to adjust cost bases below.
	map<string, int> originalTotals = cargo.Commodities();

	// Move the flagship to the start of the list of ships and ensure that all
	// escorts know which ship is acting as flagship.
	SetFlagship(*flagship);

	// Recharge any ships that can be recharged, and load available cargo.
	const bool canUseServices = planet->CanUseServices();
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsParked() && !ship->IsDisabled())
		{
			// Recalculate the weapon cache in case a mass-less change had an effect.
			ship->UpdateCaches(true);
			if(ship->GetSystem() != system)
			{
				ship->Recharge(Port::RechargeType::None, false);
				continue;
			}
			else
				ship->Recharge(canUseServices ? planet->GetPort().GetRecharges() : Port::RechargeType::None,
					planet->GetPort().HasService(Port::ServicesType::HireCrew));
		}

	if(distributeCargo)
		DistributeCargo();

	if(cargo.Passengers())
	{
		int extra = min(cargo.Passengers(), flagship->Crew() - flagship->RequiredCrew());
		if(extra)
		{
			flagship->AddCrew(-extra);
			if(extra == 1)
				Messages::Add("You fired a crew member to free up a bunk for a passenger.", Messages::Importance::High);
			else
				Messages::Add("You fired " + to_string(extra) + " crew members to free up bunks for passengers.",
						Messages::Importance::High);
			flagship->Cargo().SetBunks(flagship->Attributes().Get("bunks") - flagship->Crew());
			cargo.TransferAll(flagship->Cargo());
		}
	}

	int extra = flagship->Crew() + flagship->Cargo().Passengers() - flagship->Attributes().Get("bunks");
	if(extra > 0)
	{
		flagship->AddCrew(-extra);
		if(extra == 1)
			Messages::Add("You fired a crew member because you have no bunk for them.", Messages::Importance::High);
		else
			Messages::Add("You fired " + to_string(extra) + " crew members because you have no bunks for them.",
					Messages::Importance::High);
		flagship->Cargo().SetBunks(flagship->Attributes().Get("bunks") - flagship->Crew());
	}

	// For each active, carriable ship you own, try to find an active ship that has a bay for it.
	auto carriers = vector<Ship *>{};
	auto toLoad = vector<shared_ptr<Ship>>{};
	for(auto &ship : ships)
		if(!ship->IsParked() && !ship->IsDisabled())
		{
			if(ship->CanBeCarried() && ship != flagship)
				toLoad.emplace_back(ship);
			else if(ship->HasBays())
				carriers.emplace_back(ship.get());
		}
	if(!toLoad.empty())
	{
		size_t uncarried = toLoad.size();
		if(!carriers.empty())
		{
			// Order carried ships such that those requiring bays are loaded first. For
			// jump-capable carried ships, prefer loading those with a shorter range.
			stable_sort(toLoad.begin(), toLoad.end(),
				[](const shared_ptr<Ship> &a, const shared_ptr<Ship> &b)
				{
					return a->JumpsRemaining() < b->JumpsRemaining();
				});
			// We are guaranteed that each carried `ship` is not parked and not disabled, and that
			// all possible parents are also not parked, not disabled, and not `ship`.
			for(auto &ship : toLoad)
				for(auto &parent : carriers)
					if(parent->GetSystem() == ship->GetSystem() && parent->Carry(ship))
					{
						--uncarried;
						break;
					}
		}

		if(uncarried)
		{
			// The remaining uncarried ships are launched alongside the player.
			string message = (uncarried > 1) ? "Some escorts were" : "One escort was";
			Messages::Add(message + " unable to dock with a carrier.", Messages::Importance::High);
		}
	}

	// By now, all cargo should have been divvied up among your ships. So, any
	// mission cargo or passengers left behind cannot be carried, and those
	// missions have aborted.
	vector<const Mission *> missionsToRemove;
	for(const auto &it : cargo.MissionCargo())
		if(it.second)
		{
			if(it.first->IsVisible())
				Messages::Add("Mission \"" + it.first->DisplayName()
					+ "\" aborted because you do not have space for the cargo."
						, Messages::Importance::Highest);
			missionsToRemove.push_back(it.first);
		}
	for(const auto &it : cargo.PassengerList())
		if(it.second)
		{
			if(it.first->IsVisible())
				Messages::Add("Mission \"" + it.first->DisplayName()
					+ "\" aborted because you do not have enough passenger bunks free."
						, Messages::Importance::Highest);
			missionsToRemove.push_back(it.first);

		}
	for(const Mission *mission : missionsToRemove)
		RemoveMission(Mission::ABORT, *mission, ui);

	// Any ordinary cargo left behind can be sold.
	int64_t income = 0;
	int day = date.DaysSinceEpoch();
	int64_t sold = cargo.Used();
	int64_t totalBasis = 0;
	double stored = 0.;
	if(sold)
	{
		for(const auto &commodity : cargo.Commodities())
		{
			if(!commodity.second)
				continue;

			// Figure out how much income you get for selling this cargo.
			int64_t value = commodity.second * static_cast<int64_t>(system->Trade(commodity.first));
			income += value;

			int original = originalTotals[commodity.first];
			auto it = costBasis.find(commodity.first);
			if(!original || it == costBasis.end() || !it->second)
				continue;

			// Now, figure out how much of that income is profit by calculating
			// the cost basis for this cargo (which is just the total cost basis
			// multiplied by the percent of the cargo you are selling).
			int64_t basis = it->second * commodity.second / original;
			it->second -= basis;
			totalBasis += basis;
		}
		if(!planet->HasOutfitter())
			for(const auto &outfit : cargo.Outfits())
			{
				// Compute the total value for each type of excess outfit.
				if(!outfit.second)
					continue;
				int64_t cost = depreciation.Value(outfit.first, day, outfit.second);
				for(int i = 0; i < outfit.second; ++i)
					stockDepreciation.Buy(outfit.first, day, &depreciation);
				income += cost;
			}
		else
			for(const auto &outfit : cargo.Outfits())
			{
				// Transfer the outfits from cargo to the storage on this planet.
				if(!outfit.second)
					continue;
				stored += outfit.first->Mass() * outfit.second;
				cargo.Transfer(outfit.first, outfit.second, Storage());
			}
	}
	accounts.AddCredits(income);
	cargo.Clear();
	stockDepreciation = Depreciation();
	sold -= ceil(stored);
	if(sold || stored)
	{
		// Report how much excess cargo was sold (and what profit you earned),
		// and how many tons of outfits were stored.
		ostringstream out;
		out << "You ";
		if(sold)
		{
			out << "sold " << Format::CargoString(sold, "excess cargo") << " for " << Format::CreditString(income);
			if(totalBasis && totalBasis != income)
				out << " (for a profit of " << Format::CreditString(income - totalBasis) << ")";
			if(stored)
				out << ", and ";
		}
		if(stored)
		{
			out << "stored " << Format::CargoString(stored, "outfits") << " you could not carry";
		}
		out << ".";
		Messages::Add(out.str(), Messages::Importance::High);
	}

	return true;
}



void PlayerInfo::PoolCargo()
{
	// This can only be done while landed.
	if(!planet)
		return;

	// To make sure all cargo and passengers get unloaded from each ship,
	// temporarily uncap the player's cargo and bunk capacity.
	cargo.SetSize(-1);
	cargo.SetBunks(-1);
	for(const shared_ptr<Ship> &ship : ships)
		if(ship->GetPlanet() == planet && !ship->IsParked())
			ship->Cargo().TransferAll(cargo);
	UpdateCargoCapacities();
}



const CargoHold &PlayerInfo::DistributeCargo()
{
	desiredCrew = flagship->Crew();
	flagship->Cargo().SetBunks(flagship->Attributes().Get("bunks") - desiredCrew);

	// First, try to transfer to the flagship depending on the priority preference.
	Preferences::FlagshipSpacePriority prioritySetting = Preferences::GetFlagshipSpacePriority();
	if(prioritySetting == Preferences::FlagshipSpacePriority::PASSENGERS)
		for(const auto &it : cargo.PassengerList())
			cargo.TransferPassengers(it.first, it.second, flagship->Cargo());
	else if(prioritySetting != Preferences::FlagshipSpacePriority::NONE)
		cargo.TransferAll(flagship->Cargo(), prioritySetting == Preferences::FlagshipSpacePriority::BOTH);

	// Distribute the remaining cargo among the escorts.
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsParked() && !ship->IsDisabled() && ship->GetPlanet() == planet && ship != flagship)
		{
			ship->Cargo().SetBunks(ship->Attributes().Get("bunks") - ship->RequiredCrew());
			cargo.TransferAll(ship->Cargo());
		}

	// If the escorts couldn't fit all of the cargo or passengers, try to move the rest to the flagship
	// regardless of the priority preference.
	cargo.TransferAll(flagship->Cargo());

	return cargo;
}



double PlayerInfo::GetPlayTime() const noexcept
{
	return playTime;
}



void PlayerInfo::AddPlayTime(chrono::nanoseconds timeVal)
{
	playTime += timeVal.count() * .000000001;
}



// Get the player's logbook.
const multimap<Date, string> &PlayerInfo::Logbook() const
{
	return logbook;
}



void PlayerInfo::AddLogEntry(const string &text)
{
	logbook.emplace(date, text);
}



const map<string, map<string, string>> &PlayerInfo::SpecialLogs() const
{
	return specialLogs;
}



void PlayerInfo::AddSpecialLog(const string &type, const string &name, const string &text)
{
	string &entry = specialLogs[type][name];
	if(!entry.empty())
		entry += "\n\t";
	entry += text;
}



void PlayerInfo::RemoveSpecialLog(const string &type, const string &name)
{
	auto it = specialLogs.find(type);
	if(it == specialLogs.end())
		return;
	auto &nameMap = it->second;
	auto eit = nameMap.find(name);
	if(eit != nameMap.end())
		nameMap.erase(eit);
}



void PlayerInfo::RemoveSpecialLog(const string &type)
{
	auto it = specialLogs.find(type);
	if(it != specialLogs.end())
		specialLogs.erase(it);
}



bool PlayerInfo::HasLogs() const
{
	return !logbook.empty() || !specialLogs.empty();
}



// Get the list of active missions.
const list<Mission> &PlayerInfo::Missions() const
{
	return missions;
}



// Get the list of ordinary jobs that are available on the job board.
const list<Mission> &PlayerInfo::AvailableJobs() const
{
	return availableJobs;
}



bool PlayerInfo::HasAvailableEnteringMissions() const
{
	return !availableEnteringMissions.empty();
}



void PlayerInfo::CalculateRemainingDeadlines()
{
	remainingDeadlines.clear();
	DistanceMap here(*this, system);
	for(const Mission &mission : missions)
		CalculateRemainingDeadline(mission, here);
}



void PlayerInfo::CalculateRemainingDeadline(const Mission &mission, DistanceMap &here)
{
	if(!mission.Deadline())
		return;

	int daysLeft = mission.Deadline() - GetDate() + 1;
	// If at any point a location can't be reached, it is ignored instead of treating
	// it as if it has an infinite distance.
	if(daysLeft > 0 && Preferences::Has("Deadline blink by distance")
		&& here.HasRoute(*mission.Destination()->GetSystem()))
	{
		set<const System *> toVisit;
		for(const Planet *stopover : mission.Stopovers())
		{
			if(here.HasRoute(*stopover->GetSystem()))
				toVisit.insert(stopover->GetSystem());
			// Stopovers require you to land on a planet, which takes an extra day.
			--daysLeft;
		}
		for(const System *waypoint : mission.Waypoints())
			if(here.HasRoute(*waypoint))
				toVisit.insert(waypoint);

		// This is a traveling salesman problem. Estimate the minimum number
		// of days that it would take to reach every point of interest by
		// traveling to the next closest location after each step.
		DistanceMap distance = here;
		int systemCount = toVisit.size();
		for(int i = 0; i < systemCount; ++i)
		{
			const System *closest;
			int minimalDist = numeric_limits<int>::max();
			for(const System *sys : toVisit)
				if(distance.Days(*sys) < minimalDist)
				{
					closest = sys;
					minimalDist = distance.Days(*sys);
				}
			daysLeft -= distance.Days(*closest);
			distance = DistanceMap(*this, closest);
			toVisit.erase(closest);
		}
		daysLeft -= distance.Days(*mission.Destination()->GetSystem());
	}
	remainingDeadlines[&mission] = daysLeft;
}



int PlayerInfo::RemainingDeadline(const Mission &mission) const
{
	auto it = remainingDeadlines.find(&mission);
	return it == remainingDeadlines.end() ? 0 : it->second;
}



const PlayerInfo::SortType PlayerInfo::GetAvailableSortType() const
{
	return availableSortType;
}



void PlayerInfo::NextAvailableSortType()
{
	availableSortType = static_cast<SortType>((availableSortType + 1) % (CONVENIENT + 1));
	SortAvailable();
}



const bool PlayerInfo::ShouldSortAscending() const
{
	return availableSortAsc;
}



void PlayerInfo::ToggleSortAscending()
{
	availableSortAsc = !availableSortAsc;
	SortAvailable();
}



const bool PlayerInfo::ShouldSortSeparateDeadline() const
{
	return sortSeparateDeadline;
}



void PlayerInfo::ToggleSortSeparateDeadline()
{
	sortSeparateDeadline = !sortSeparateDeadline;
	SortAvailable();
}



const bool PlayerInfo::ShouldSortSeparatePossible() const
{
	return sortSeparatePossible;
}



void PlayerInfo::ToggleSortSeparatePossible()
{
	sortSeparatePossible = !sortSeparatePossible;
	SortAvailable();
}



void PlayerInfo::SortAvailable()
{
	// Destinations: planets OR system. Only counting them, so the type doesn't matter.
	set<const void *> destinations;
	if(availableSortType == CONVENIENT)
	{
		for(const Mission &mission : Missions())
		{
			if(mission.IsVisible())
			{
				destinations.insert(mission.Destination());
				destinations.insert(mission.Destination()->GetSystem());

				for(const Planet *stopover : mission.Stopovers())
				{
					destinations.insert(stopover);
					destinations.insert(stopover->GetSystem());
				}

				for(const System *waypoint : mission.Waypoints())
					destinations.insert(waypoint);
			}
		}
	}
	availableJobs.sort([&](const Mission &lhs, const Mission &rhs) {
		// First, separate rush orders with deadlines, if wanted
		if(sortSeparateDeadline)
		{
			// availableSortAsc instead of true, to counter the reverse below
			if(!lhs.Deadline() && rhs.Deadline())
				return availableSortAsc;
			if(lhs.Deadline() && !rhs.Deadline())
				return !availableSortAsc;
		}
		// Then, separate greyed-out jobs you can't accept
		if(sortSeparatePossible)
		{
			if(lhs.CanAccept(*this) && !rhs.CanAccept(*this))
				return availableSortAsc;
			if(!lhs.CanAccept(*this) && rhs.CanAccept(*this))
				return !availableSortAsc;
		}
		// Sort by desired type:
		switch(availableSortType)
		{
			case CONVENIENT:
			{
				// Sorting by "convenience" means you already have a mission to a
				// planet. Missions at the same planet are sorted higher.
				// 0 : No convenient mission; 1: same system; 2: same planet (because both system+planet means 1+1 = 2)
				const int lConvenient = destinations.count(lhs.Destination()) + destinations.count(lhs.Destination()->GetSystem());
				const int rConvenient = destinations.count(rhs.Destination()) + destinations.count(rhs.Destination()->GetSystem());
				if(lConvenient < rConvenient)
					return true;
				if(lConvenient > rConvenient)
					return false;
			}
			// Tiebreaker for equal CONVENIENT is SPEED.
			case SPEED:
			{
				// A higher "Speed" means the mission takes less time, i.e. fewer
				// jumps.
				const int lJumps = lhs.ExpectedJumps();
				const int rJumps = rhs.ExpectedJumps();

				if(lJumps == rJumps)
				{
					// SPEED compares equal - follow through to tiebreaker 'case PAY' below
				}
				else if(lJumps > 0 && rJumps > 0)
				{
					// Lower values are better, so this '>' is not '<' as expected
					return lJumps > rJumps;
				}
				else
				{
					// Negative values indicate indeterminable mission paths.
					// e.g. through a wormhole, meaning lower values are worse.

					// A value of 0 indicates the mission destination is the
					// source, implying the actual path is complicated; consider
					// that slow, but not as bad as an indeterminable path.

					// Positive values are 'greater' because at least the number
					// of jumps is known. (Comparing two positive values is already
					// handled above, so the actual positive value doesn't matter.)

					// Compare the value when at least one value is not positive.
					return lJumps < rJumps;
				}
			}
			// Tiebreaker for equal SPEED is PAY.
			case PAY:
			{
				const int64_t lPay = lhs.DisplayedPayment();
				const int64_t rPay = rhs.DisplayedPayment();
				if(lPay < rPay)
					return true;
				else if(lPay > rPay)
					return false;
			}
			// Tiebreaker for equal PAY is ABC.
			case ABC:
			{
				if(lhs.DisplayName() < rhs.DisplayName())
					return true;
				else if(lhs.DisplayName() > rhs.DisplayName())
					return false;
			}
			// Tiebreaker fallback to keep sorting consistent is unique UUID:
			default:
				return lhs.UUID() < rhs.UUID();
		}
	});

	if(!availableSortAsc)
		availableJobs.reverse();
}



// Return a pointer to the mission that was most recently accepted while in-flight.
const Mission *PlayerInfo::ActiveInFlightMission() const
{
	return activeInFlightMission;
}



// Update mission NPCs with the player's current conditions.
void PlayerInfo::UpdateMissionNPCs()
{
	for(Mission &mission : missions)
		mission.UpdateNPCs(*this);
}



// Accept the given job.
void PlayerInfo::AcceptJob(const Mission &mission, UI *ui)
{
	for(auto it = availableJobs.begin(); it != availableJobs.end(); ++it)
		if(&*it == &mission)
		{
			cargo.AddMissionCargo(&mission);
			auto spliceIt = it->IsUnique() ? missions.begin() : missions.end();
			missions.splice(spliceIt, availableJobs, it);
			it->Do(Mission::OFFER, *this);
			it->Do(Mission::ACCEPT, *this, ui);
			if(it->IsFailed())
				RemoveMission(Mission::Trigger::FAIL, *it, ui);
			// Might not have cargo anymore, so some jobs can be sorted to end.
			SortAvailable();
			break;
		}
}



// Look at the list of available missions and see if any of them can be offered
// right now, in the given location. If there are no missions that can be accepted,
// return a null pointer.
Mission *PlayerInfo::MissionToOffer(Mission::Location location)
{
	if(ships.empty())
		return nullptr;

	// If a mission can be offered right now, move it to the start of the list
	// so we know what mission the callback is referring to, and return it.
	for(auto it = availableMissions.begin(); it != availableMissions.end(); ++it)
		if(it->IsAtLocation(location) && it->CanOffer(*this) && it->CanAccept(*this))
		{
			availableMissions.splice(availableMissions.begin(), availableMissions, it);
			return &availableMissions.front();
		}
	return nullptr;
}



// Check if any of the game's missions can be offered from this ship, given its
// relationship with the player. If none offer, return nullptr.
Mission *PlayerInfo::BoardingMission(const shared_ptr<Ship> &ship)
{
	// Do not create missions from existing mission NPC's, or the player's ships.
	if(ship->IsSpecial())
		return nullptr;
	// Ensure that boarding this NPC again does not create a mission.
	ship->SetIsSpecial();

	// "boardingMissions" is emptied by MissionCallback, but to be sure:
	availableBoardingMissions.clear();

	Mission::Location location = (ship->GetGovernment()->IsEnemy()
			? Mission::BOARDING : Mission::ASSISTING);

	// Check for available boarding or assisting missions.
	for(const auto &[name, mission] : GameData::Missions())
		if(mission.IsAtLocation(location) && mission.CanOffer(*this, ship))
		{
			availableBoardingMissions.push_back(mission.Instantiate(*this, ship));
			if(availableBoardingMissions.back().IsFailed())
				availableBoardingMissions.pop_back();
			else
				return &availableBoardingMissions.back();
		}

	return nullptr;
}



void PlayerInfo::CreateEnteringMissions()
{
	availableEnteringMissions.clear();

	bool hasPriorityMissions = false;
	unsigned nonBlockingMissions = 0;
	for(const auto &[name, mission] : GameData::Missions())
		if(mission.IsAtLocation(Mission::ENTERING) && mission.CanOffer(*this))
		{
			availableEnteringMissions.push_back(mission.Instantiate(*this));
			if(availableEnteringMissions.back().IsFailed())
				availableEnteringMissions.pop_back();
			else
			{
				hasPriorityMissions |= missions.back().HasPriority();
				nonBlockingMissions += missions.back().IsNonBlocking();
			}
		}

	SortMissions(availableMissions, hasPriorityMissions, nonBlockingMissions);
}



Mission *PlayerInfo::EnteringMission()
{
	if(!flagship)
		return nullptr;

	// If a mission can be offered right now, move it to the start of the list
	// so we know what mission the callback is referring to, and return it.
	for(auto it = availableEnteringMissions.begin(); it != availableEnteringMissions.end(); ++it)
		if(it->HasSpace(*flagship))
		{
			availableEnteringMissions.splice(availableEnteringMissions.begin(), availableEnteringMissions, it);
			return &availableEnteringMissions.front();
		}
	return nullptr;
}



bool PlayerInfo::CaptureOverriden(const shared_ptr<Ship> &ship) const
{
	if(ship->IsCapturable())
		return false;
	// Check if there's a boarding mission being offered which allows this ship to be captured. If the boarding
	// mission was declined, then this results in one-time capture access to the ship. If it was accepted, then
	// the next boarding attempt will have the boarding mission in the player's active missions list, checked below.
	const Mission *mission = availableBoardingMissions.empty() ? nullptr : &availableBoardingMissions.back();
	// Otherwise, check if there's an already active mission which grants access. This allows trying to board the
	// ship again after accepting the mission.
	if(!mission)
		for(const Mission &mission : Missions())
			if(mission.OverridesCapture() && !mission.IsFailed() && mission.SourceShip() == ship.get())
				return true;
	return mission && mission->OverridesCapture() && !mission->IsFailed() && mission->SourceShip() == ship.get();
}



// Engine calls this after placing the boarding/assisting/entering mission's NPCs.
void PlayerInfo::ClearActiveInFlightMission()
{
	activeInFlightMission = nullptr;
}



// If one of your missions cannot be offered because you do not have enough
// space for it, and it specifies a message to be shown in that situation,
// show that message.
void PlayerInfo::HandleBlockedMissions(Mission::Location location, UI *ui)
{
	list<Mission> &missionList = availableMissions.empty() ? availableBoardingMissions : availableMissions;
	if(ships.empty() || missionList.empty())
		return;

	for(auto &it : missionList)
		if(it.IsAtLocation(location) && it.CanOffer(*this) && !it.CanAccept(*this))
		{
			string message = it.BlockedMessage(*this);
			if(!message.empty())
			{
				ui->Push(new Dialog(message));
				return;
			}
		}
}



void PlayerInfo::HandleBlockedEnteringMissions(UI *ui)
{
	if(!flagship || availableEnteringMissions.empty())
		return;

	for(auto it = availableEnteringMissions.begin(); it != availableEnteringMissions.end(); )
	{
		if(!it->HasSpace(*flagship))
		{
			string message = it->BlockedMessage(*this);
			// Remove this mission from the list so that the MainPanel stops
			// trying to offer it.
			it = availableEnteringMissions.erase(it);
			if(!message.empty())
			{
				ui->Push(new Dialog(message));
				return;
			}
		}
		else
			++it;
	}
}



// Callback for accepting or declining whatever mission has been offered.
// Responses which would kill the player are handled before the on offer
// conversation ended.
void PlayerInfo::MissionCallback(int response)
{
	list<Mission> &missionList = availableMissions.empty() ?
		(availableEnteringMissions.empty() ? availableBoardingMissions : availableEnteringMissions) : availableMissions;
	if(missionList.empty())
		return;

	Mission &mission = missionList.front();

	// If landed, this conversation may require the player to immediately depart.
	shouldLaunch |= (GetPlanet() && Conversation::RequiresLaunch(response));
	if(response == Conversation::ACCEPT || response == Conversation::LAUNCH)
	{
		bool shouldAutosave = mission.RecommendsAutosave();
		if(planet)
		{
			cargo.AddMissionCargo(&mission);
			UpdateCargoCapacities();
		}
		else if(Flagship())
			flagship->Cargo().AddMissionCargo(&mission);
		else
			return;

		// Move this mission from the offering list into the "accepted"
		// list, viewable on the MissionPanel. Unique missions are moved
		// to the front, so they appear at the top of the list if viewed.
		auto spliceIt = mission.IsUnique() ? missions.begin() : missions.end();
		missions.splice(spliceIt, missionList, missionList.begin());
		mission.Do(Mission::ACCEPT, *this);
		if(shouldAutosave)
			Autosave();
		// If this is a mission offered in-flight, expose a pointer to it
		// so Engine::SpawnFleets can add its ships without requiring the
		// player to land.
		if(mission.IsAtLocation(Mission::BOARDING) || mission.IsAtLocation(Mission::ASSISTING)
				|| mission.IsAtLocation(Mission::ENTERING))
			activeInFlightMission = &*--spliceIt;
	}
	else if(response == Conversation::DECLINE || response == Conversation::FLEE)
	{
		mission.Do(Mission::DECLINE, *this);
		missionList.pop_front();
	}
	else if(response == Conversation::DEFER || response == Conversation::DEPART)
	{
		mission.Do(Mission::DEFER, *this);
		missionList.pop_front();
	}
}



// Basic callback, allowing conversations to force the player to depart from a
// planet without requiring a mission to offer.
void PlayerInfo::BasicCallback(int response)
{
	// If landed, this conversation may require the player to immediately depart.
	shouldLaunch |= (GetPlanet() && Conversation::RequiresLaunch(response));
}



// Mark a mission for removal, either because it was completed, or it failed,
// or because the player aborted it.
void PlayerInfo::RemoveMission(Mission::Trigger trigger, const Mission &mission, UI *ui)
{
	for(auto it = missions.begin(); it != missions.end(); ++it)
		if(&*it == &mission)
		{
			// Don't delete the mission yet, because the conversation or dialog
			// panel may still be showing. Instead, just mark it as done. Doing
			// this first avoids the possibility of an infinite loop, e.g. if a
			// mission's "on fail" fails the mission itself.
			doneMissions.splice(doneMissions.end(), missions, it);

			it->Do(trigger, *this, ui);
			cargo.RemoveMissionCargo(&mission);
			for(shared_ptr<Ship> &ship : ships)
				ship->Cargo().RemoveMissionCargo(&mission);
			return;
		}
}



// Mark a mission as failed, but do not remove it from the mission list yet.
void PlayerInfo::FailMission(const Mission &mission)
{
	for(auto &it : missions)
		if(&it == &mission)
		{
			it.Fail();
			return;
		}
}



// Update mission status based on an event.
void PlayerInfo::HandleEvent(const ShipEvent &event, UI *ui)
{
	// Combat rating increases when you disable an enemy ship.
	if(event.ActorGovernment() && event.ActorGovernment()->IsPlayer())
		if((event.Type() & ShipEvent::DISABLE) && event.Target() && !event.Target()->IsYours())
		{
			auto &rating = conditions["combat rating"];
			static const int64_t maxRating = 2000000000;
			rating = min(maxRating, rating + (event.Target()->Cost() + 250000) / 500000);
		}

	for(Mission &mission : missions)
		mission.Do(event, *this, ui);

	// If the player's flagship was destroyed, the player is dead.
	if((event.Type() & ShipEvent::DESTROY) && !ships.empty() && event.Target().get() == Flagship())
		Die();
}



// Get mutable access to the player's list of conditions.
ConditionsStore &PlayerInfo::Conditions()
{
	return conditions;
}



// Access the player's list of conditions.
const ConditionsStore &PlayerInfo::Conditions() const
{
	return conditions;
}



// Uuid for the gifted ships, with the ship class follow by the names they had when they were gifted to the player.
const map<string, EsUuid> &PlayerInfo::GiftedShips() const
{
	return giftedShips;
}



map<string, string> PlayerInfo::GetSubstitutions() const
{
	map<string, string> subs;
	GameData::GetTextReplacements().Substitutions(subs);
	AddPlayerSubstitutions(subs);
	return subs;
}



void PlayerInfo::AddPlayerSubstitutions(map<string, string> &subs) const
{
	subs["<first>"] = FirstName();
	subs["<last>"] = LastName();
	const Ship *flag = Flagship();
	if(flag)
	{
		subs["<ship>"] = flag->GivenName();
		subs["<model>"] = flag->DisplayModelName();
		subs["<flagship>"] = flag->GivenName();
		subs["<flagship model>"] = flag->DisplayModelName();
	}

	subs["<system>"] = GetSystem()->DisplayName();
	subs["<date>"] = GetDate().ToString();
	subs["<day>"] = GetDate().LongString();
}



bool PlayerInfo::SetTribute(const Planet *planet, int64_t payment)
{
	if(payment > 0)
	{
		tributeReceived[planet] = payment;
		// Properly connect this function to the dominated property of planets.
		GameData::GetPolitics().DominatePlanet(planet);
	}
	else
	{
		tributeReceived.erase(planet);
		// Properly connect this function to the (no longer) dominated property of planets.
		GameData::GetPolitics().DominatePlanet(planet, false);
	}

	return true;
}



bool PlayerInfo::SetTribute(const string &planetTrueName, int64_t payment)
{
	const Planet *planet = GameData::Planets().Find(planetTrueName);
	if(!planet)
		return false;

	return SetTribute(planet, payment);
}



// Get a list of all tribute that the player receives.
const map<const Planet *, int64_t> &PlayerInfo::GetTribute() const
{
	return tributeReceived;
}



// Get the total sum of the tribute the player receives.
int64_t PlayerInfo::GetTributeTotal() const
{
	return accumulate(
		tributeReceived.begin(),
		tributeReceived.end(),
		0,
		[](int64_t value, const map<const Planet *, int64_t>::value_type &tribute)
		{
			return value + tribute.second;
		}
	);
}



// Check if the player knows the location of the given system (whether or not
// they have actually visited it).
bool PlayerInfo::HasSeen(const System &system) const
{
	if(&system == this->system)
		return true;

	// Shrouded systems have special considerations as to whether they're currently seen or not.
	bool shrouded = system.Shrouded();
	if(!shrouded && seen.contains(&system))
		return true;

	auto usesSystem = [&system](const Mission &m) noexcept -> bool
	{
		if(!m.IsVisible())
			return false;
		if(m.Waypoints().contains(&system))
			return true;
		if(m.MarkedSystems().contains(&system))
			return true;
		for(auto &&p : m.Stopovers())
			if(p->IsInSystem(&system))
				return true;
		return m.Destination()->IsInSystem(&system);
	};
	if(any_of(availableJobs.begin(), availableJobs.end(), usesSystem))
		return true;
	if(any_of(missions.begin(), missions.end(), usesSystem))
		return true;

	if(shrouded)
	{
		// All systems linked to a system the player can view are visible.
		if(any_of(system.Links().begin(), system.Links().end(),
				[&](const System *s) noexcept -> bool { return CanView(*s); }))
			return true;
		// A shrouded system not linked to a viewable system must be visible from the current system.
		if(!system.VisibleNeighbors().contains(this->system))
			return false;
		// If a shrouded system is in visible range, then it can be seen if it is not also hidden.
		return !system.Hidden();
	}

	return KnowsName(system);
}



// Check if the player can view the contents of the given system.
bool PlayerInfo::CanView(const System &system) const
{
	// A player can always view the contents of the system they are in. Otherwise,
	// the system must have been visited before and not be shrouded.
	return (HasVisited(system) && !system.Shrouded()) || &system == this->system;
}



// Check if the player has visited the given system.
bool PlayerInfo::HasVisited(const System &system) const
{
	return visitedSystems.contains(&system);
}



// Check if the player has visited the given planet.
bool PlayerInfo::HasVisited(const Planet &planet) const
{
	return visitedPlanets.contains(&planet);
}



// Check if the player knows the name of a system, either from visiting there or
// because a job or active mission includes the name of that system.
bool PlayerInfo::KnowsName(const System &system) const
{
	if(CanView(system))
		return true;

	for(const Mission &mission : availableJobs)
		if(mission.Destination()->IsInSystem(&system))
			return true;

	for(const Mission &mission : missions)
		if(mission.IsVisible() && mission.Destination()->IsInSystem(&system))
			return true;

	return false;
}


// Mark the given system as visited, and mark all its neighbors as seen.
void PlayerInfo::Visit(const System &system)
{
	visitedSystems.insert(&system);
	seen.insert(&system);
	for(const System *neighbor : system.VisibleNeighbors())
		if(!neighbor->Hidden() || system.Links().contains(neighbor))
			seen.insert(neighbor);
}



// Mark the given planet as visited.
void PlayerInfo::Visit(const Planet &planet)
{
	visitedPlanets.insert(&planet);
}



// Mark a system as unvisited, even if visited previously.
void PlayerInfo::Unvisit(const System &system)
{
	visitedSystems.erase(&system);
	for(const StellarObject &object : system.Objects())
		if(object.GetPlanet())
			Unvisit(*object.GetPlanet());
}



void PlayerInfo::Unvisit(const Planet &planet)
{
	visitedPlanets.erase(&planet);
}



const set<const System *> &PlayerInfo::VisitedSystems() const
{
	return visitedSystems;
}



const set<const Planet *> &PlayerInfo::VisitedPlanets() const
{
	return visitedPlanets;
}



bool PlayerInfo::HasMapped(int mapSize, bool mapMinables) const
{
	DistanceMap distance(GetSystem(), mapSize);
	for(const System *system : distance.Systems())
	{
		if(!HasVisited(*system))
			return false;

		if(mapMinables)
			for(const Outfit *outfit : system->Payloads())
				if(!harvested.contains(make_pair(system, outfit)))
					return false;
	}

	return true;
}



void PlayerInfo::Map(int mapSize, bool mapMinables)
{
	DistanceMap distance(GetSystem(), mapSize);
	for(const System *system : distance.Systems())
	{
		if(!HasVisited(*system))
			Visit(*system);

		if(mapMinables)
			for(const Outfit *outfit : system->Payloads())
				harvested.insert(make_pair(system, outfit));
	}
}



// Check if the player has a hyperspace route set.
bool PlayerInfo::HasTravelPlan() const
{
	return !travelPlan.empty();
}



// Access the player's travel plan.
const vector<const System *> &PlayerInfo::TravelPlan() const
{
	return travelPlan;
}



vector<const System *> &PlayerInfo::TravelPlan()
{
	return travelPlan;
}



// This is called when the player enters the system that is their current
// hyperspace target.
void PlayerInfo::PopTravel()
{
	if(!travelPlan.empty())
	{
		Visit(*travelPlan.back());
		travelPlan.pop_back();
	}
}



// Get the planet to land on at the end of the travel path.
const Planet *PlayerInfo::TravelDestination() const
{
	return travelDestination;
}



// Set the planet to land on at the end of the travel path.
void PlayerInfo::SetTravelDestination(const Planet *planet)
{
	travelDestination = planet;
	if(planet && planet->IsInSystem(system) && Flagship())
		Flagship()->SetTargetStellar(system->FindStellar(planet));
}



// Check which secondary weapons the player has selected.
const set<const Outfit *> &PlayerInfo::SelectedSecondaryWeapons() const
{
	return selectedWeapons;
}



// Cycle through all available secondary weapons.
void PlayerInfo::SelectNextSecondary()
{
	if(!flagship || flagship->Outfits().empty())
		return;

	// If multiple weapons were selected, then switch to selecting none.
	if(selectedWeapons.size() > 1)
	{
		selectedWeapons.clear();
		return;
	}

	// If no weapon was selected, then we scan from the beginning.
	auto it = flagship->Outfits().begin();
	bool hadSingleWeaponSelected = (selectedWeapons.size() == 1);

	// If a single weapon was selected, then move the iterator to the
	// outfit directly after it.
	if(hadSingleWeaponSelected)
	{
		auto selectedOutfit = *(selectedWeapons.begin());
		it = flagship->Outfits().find(selectedOutfit);
		if(it != flagship->Outfits().end())
			++it;
	}

	// Find the next secondary weapon.
	for( ; it != flagship->Outfits().end(); ++it)
		if(it->first->Icon())
		{
			selectedWeapons.clear();
			selectedWeapons.insert(it->first);
			return;
		}

	// If no weapon was selected and we didn't find any weapons at this point,
	// then the player just doesn't have any secondary weapons.
	if(!hadSingleWeaponSelected)
		return;

	// Reached the end of the list. Select all possible secondary weapons here.
	it = flagship->Outfits().begin();
	for( ; it != flagship->Outfits().end(); ++it)
		if(it->first->Icon())
			selectedWeapons.insert(it->first);

	// If we have only one weapon selected at this point, then the player
	// only has a single secondary weapon. Clear the list, since the weapon
	// was selected when we entered this function.
	if(selectedWeapons.size() == 1)
		selectedWeapons.clear();
}



void PlayerInfo::DeselectAllSecondaries()
{
	selectedWeapons.clear();
}



void PlayerInfo::ToggleAnySecondary(const Outfit *outfit)
{
	if(!flagship)
		return;

	const auto it = selectedWeapons.insert(outfit);
	if(!it.second)
		selectedWeapons.erase(it.first);
}



// Escorts currently selected for giving orders.
const vector<weak_ptr<Ship>> &PlayerInfo::SelectedShips() const
{
	return selectedShips;
}



// Select any player ships in the given box or list. Return true if any were
// selected, so we know not to search further for a match.
bool PlayerInfo::SelectShips(const Rectangle &box, bool hasShift)
{
	// If shift is not held down, replace the current selection.
	if(!hasShift)
		selectedShips.clear();
	// If shift is not held, the first ship in the box will also become the
	// player's flagship's target.
	bool first = !hasShift;

	bool matched = false;
	for(const shared_ptr<Ship> &ship : ships)
		if(!ship->IsDestroyed() && !ship->IsParked() && ship->GetSystem() == system && ship.get() != Flagship()
				&& box.Contains(ship->Position()))
		{
			matched = true;
			SelectShip(ship, &first);
		}
	return matched;
}



bool PlayerInfo::SelectShips(const vector<const Ship *> &stack, bool hasShift)
{
	// If shift is not held down, replace the current selection.
	if(!hasShift)
		selectedShips.clear();
	// If shift is not held, the first ship in the stack will also become the
	// player's flagship's target.
	bool first = !hasShift;

	// Loop through all the player's ships and check which of them are in the
	// given stack.
	bool matched = false;
	for(const shared_ptr<Ship> &ship : ships)
	{
		auto it = find(stack.begin(), stack.end(), ship.get());
		if(it != stack.end())
		{
			matched = true;
			SelectShip(ship, &first);
		}
	}
	if(matched)
		UI::PlaySound(UI::UISound::TARGET);
	return matched;
}



void PlayerInfo::SelectShip(const Ship *ship, bool hasShift)
{
	// If shift is not held down, replace the current selection.
	if(!hasShift)
		selectedShips.clear();

	bool first = !hasShift;
	for(const shared_ptr<Ship> &it : ships)
		if(it.get() == ship)
			SelectShip(it, &first);
}



void PlayerInfo::DeselectShip(const Ship *ship)
{
	for(auto it = selectedShips.begin(); it != selectedShips.end(); ++it)
		if(it->lock().get() == ship)
		{
			selectedShips.erase(it);
			return;
		}
}



void PlayerInfo::SelectGroup(int group, bool hasShift)
{
	int bit = (1 << group);
	// If the shift key is held down and all the ships in the given group are
	// already selected, deselect them all. Otherwise, select them all. The easy
	// way to do this is first to remove all the ships that match in one pass,
	// then add them in a subsequent pass if any were not selected.
	const Ship *oldTarget = nullptr;
	if(Flagship() && Flagship()->GetTargetShip())
	{
		oldTarget = Flagship()->GetTargetShip().get();
		Flagship()->SetTargetShip(shared_ptr<Ship>());
	}
	if(hasShift)
	{
		bool allWereSelected = true;
		for(const shared_ptr<Ship> &ship : ships)
			if(groups[ship.get()] & bit)
			{
				auto it = selectedShips.begin();
				for( ; it != selectedShips.end(); ++it)
					if(it->lock() == ship)
						break;
				if(it != selectedShips.end())
					selectedShips.erase(it);
				else
					allWereSelected = false;
			}
		if(allWereSelected)
			return;
	}
	else
		selectedShips.clear();

	// Now, go through and add any ships in the group to the selection. Even if
	// shift is held they won't be added twice, because we removed them above.
	for(const shared_ptr<Ship> &ship : ships)
		if(groups[ship.get()] & bit)
		{
			selectedShips.push_back(ship);
			if(ship.get() == oldTarget)
				Flagship()->SetTargetShip(ship);
		}
}



void PlayerInfo::SetGroup(int group, const set<Ship *> *newShips)
{
	int bit = (1 << group);
	int mask = ~bit;
	// First, remove any of your ships that are in the group.
	for(const shared_ptr<Ship> &ship : ships)
		groups[ship.get()] &= mask;
	// Then, add all the currently selected ships to the group.
	if(newShips)
	{
		for(const Ship *ship : *newShips)
			groups[ship] |= bit;
	}
	else
	{
		for(const weak_ptr<Ship> &ptr : selectedShips)
		{
			shared_ptr<Ship> ship = ptr.lock();
			if(ship)
				groups[ship.get()] |= bit;
		}
	}
}



set<Ship *> PlayerInfo::GetGroup(int group)
{
	int bit = (1 << group);
	set<Ship *> result;

	for(const shared_ptr<Ship> &ship : ships)
	{
		auto it = groups.find(ship.get());
		if(it != groups.end() && (it->second & bit))
			result.insert(ship.get());
	}
	return result;
}



// Keep track of any outfits that you have sold since landing. These will be
// available to buy back until you take off.
const map<const Outfit *, int> &PlayerInfo::GetStock() const
{
	return stock;
}



int PlayerInfo::Stock(const Outfit *outfit) const
{
	auto it = stock.find(outfit);
	return (it == stock.end() ? 0 : it->second);
}



// Transfer outfits from the player to the planet or vice versa.
void PlayerInfo::AddStock(const Outfit *outfit, int count)
{
	// If you sell an individual outfit that is not sold here and that you
	// acquired by buying a ship here, have it appear as "in stock" in case you
	// change your mind about selling it. (On the other hand, if you sell an
	// entire ship right after buying it, its outfits will not be "in stock.")
	if(count > 0 && stock[outfit] < 0)
		stock[outfit] = 0;
	stock[outfit] += count;

	int day = date.DaysSinceEpoch();
	if(count > 0)
	{
		// Remember how depreciated these items are.
		for(int i = 0; i < count; ++i)
			stockDepreciation.Buy(outfit, day, &depreciation);
	}
	else
	{
		// If the count is negative, outfits are being transferred from stock
		// into the player's possession.
		for(int i = 0; i < -count; ++i)
			depreciation.Buy(outfit, day, &stockDepreciation);
	}
}



// Get depreciation information.
const Depreciation &PlayerInfo::FleetDepreciation() const
{
	return depreciation;
}



const Depreciation &PlayerInfo::StockDepreciation() const
{
	return stockDepreciation;
}



void PlayerInfo::Harvest(const Outfit *type)
{
	if(type && system)
		harvested.insert(make_pair(system, type));
}



const set<pair<const System *, const Outfit *>> &PlayerInfo::Harvested() const
{
	return harvested;
}



const pair<const System *, Point> &PlayerInfo::GetEscortDestination() const
{
	return interstellarEscortDestination;
}



// Set (or clear) the stored escort travel destination.
void PlayerInfo::SetEscortDestination(const System *system, Point pos)
{
	interstellarEscortDestination.first = system;
	interstellarEscortDestination.second = pos;
}



// Determine if a system and nonzero position were specified.
bool PlayerInfo::HasEscortDestination() const
{
	return interstellarEscortDestination.first && interstellarEscortDestination.second;
}



// Get what coloring is currently selected in the map.
int PlayerInfo::MapColoring() const
{
	return mapColoring;
}



// Set what the map is being colored by.
void PlayerInfo::SetMapColoring(int index)
{
	mapColoring = index;
}



// Get the map zoom level.
int PlayerInfo::MapZoom() const
{
	return mapZoom;
}



// Set the map zoom level.
void PlayerInfo::SetMapZoom(int level)
{
	mapZoom = level;
}



// Get the set of collapsed categories for the named panel.
set<string> &PlayerInfo::Collapsed(const string &name)
{
	return collapsed[name];
}



bool PlayerInfo::DisplayCarrierHelp() const
{
	return displayCarrierHelp;
}



// Apply any "changes" saved in this player info to the global game state.
void PlayerInfo::ApplyChanges()
{
	for(const auto &it : reputationChanges)
		it.first->SetReputation(it.second);
	reputationChanges.clear();
	AddChanges(dataChanges);
	GameData::ReadEconomy(economy);
	economy = DataNode();

	// Make sure all stellar objects are correctly positioned. This is needed
	// because EnterSystem() is not called the first time through.
	GameData::SetDate(GetDate());
	// SetDate() clears any bribes from yesterday, so restore any auto-clearance.
	for(const Mission &mission : Missions())
		if(mission.ClearanceMessage() == "auto")
		{
			mission.Destination()->Bribe(mission.HasFullClearance());
			for(const Planet *planet : mission.Stopovers())
				planet->Bribe(mission.HasFullClearance());
		}

	// Check if any special persons have been destroyed.
	GameData::DestroyPersons(destroyedPersons);
	destroyedPersons.clear();

	// Check which planets you have dominated.
	for(auto &it : tributeReceived)
		GameData::GetPolitics().DominatePlanet(it.first);

	// Issue warnings for any data which has been mentioned but not actually defined, and
	// ensure that all "undefined" data is appropriately named.
	GameData::CheckReferences();

	// Now that all outfits have names, we can finish loading the player's ships.
	for(auto &&ship : ships)
	{
		// Government changes may have changed the player's ship swizzles.
		ship->SetGovernment(GameData::PlayerGovernment());
		ship->FinishLoading(false);
	}

	// Recalculate jumps that the available jobs will need
	for(Mission &mission : availableJobs)
		mission.CalculateJumps(system);
}



// Make change's to the player's planet, system, & ship locations as needed, to ensure the player and
// their ships are in valid locations, even if the player did something drastic, such as remove a mod.
void PlayerInfo::ValidateLoad()
{
	// If a system was not specified in the player data, use the flagship's system.
	if(!planet && !ships.empty())
	{
		string warning = "Warning: no planet specified for player";
		auto it = find_if(ships.begin(), ships.end(), [](const shared_ptr<Ship> &ship) noexcept -> bool
			{ return ship->GetPlanet() && ship->GetPlanet()->IsValid() && !ship->IsParked() && ship->CanBeFlagship(); });
		if(it != ships.end())
		{
			planet = (*it)->GetPlanet();
			system = (*it)->GetSystem();
			warning += ". Defaulting to location of flagship \"" + (*it)->GivenName() + "\", " + planet->TrueName() + ".";
		}
		else
			warning += " (no ships could supply a valid player location).";

		Logger::LogError(warning);
	}

	// As a result of external game data changes (e.g. unloading a mod) it's possible the player ended up
	// with an undefined system or planet. In that case, move them to the starting system to avoid crashing.
	if(planet && !system)
	{
		system = planet->GetSystem();
		Logger::LogError("Warning: player system was not specified. Defaulting to the specified planet's system.");
	}
	if(!planet || !planet->IsValid() || !system || !system->IsValid())
	{
		system = &startData.GetSystem();
		planet = &startData.GetPlanet();
		Logger::LogError("Warning: player system and/or planet was not valid. Defaulting to the starting location.");
	}

	// Every ship ought to have specified a valid location, but if not,
	// move it to the player's location to avoid invalid states.
	for(auto &&ship : ships)
	{
		if(!ship->GetSystem() || !ship->GetSystem()->IsValid())
		{
			ship->SetSystem(system);
			Logger::LogError("Warning: player ship \"" + ship->GivenName()
				+ "\" did not specify a valid system. Defaulting to the player's system.");
		}
		// In-system ships that aren't on a valid planet should get moved to the player's planet
		// (but e.g. disabled ships or those that didn't have a planet should remain in space).
		if(ship->GetSystem() == system && ship->GetPlanet() && !ship->GetPlanet()->IsValid())
		{
			ship->SetPlanet(planet);
			Logger::LogError("Warning: in-system player ship \"" + ship->GivenName()
				+ "\" specified an invalid planet. Defaulting to the player's planet.");
		}
		// Owned ships that are not in the player's system always start in flight.
	}

	// Validate the travel plan.
	if(travelDestination && !travelDestination->IsValid())
	{
		Logger::LogError("Warning: removed invalid travel plan destination \"" + travelDestination->TrueName() + ".\"");
		travelDestination = nullptr;
	}
	if(!travelPlan.empty() && any_of(travelPlan.begin(), travelPlan.end(),
			[](const System *waypoint) noexcept -> bool { return !waypoint->IsValid(); }))
	{
		travelPlan.clear();
		travelDestination = nullptr;
		Logger::LogError("Warning: reset the travel plan due to use of invalid system(s).");
	}

	// For old saves, default to the first start condition (the default "Endless Sky" start).
	if(startData.Identifier().empty())
	{
		// It is possible that there are no start conditions defined (e.g. a bad installation or
		// incomplete total conversion plugin). In that case, it is not possible to continue.
		const auto startCount = GameData::StartOptions().size();
		if(startCount >= 1)
		{
			startData = GameData::StartOptions().front();
			// When necessary, record in the pilot file that the starting data is just an assumption.
			if(startCount >= 2)
				conditions["unverified start scenario"] = true;
		}
		else
			throw runtime_error("Unable to set a starting scenario for an existing pilot. (No valid \"start\" "
				"nodes were found in data files or loaded plugins--make sure you've installed the game properly.)");
	}

	// Validate the missions that were loaded. Active-but-invalid missions are removed from
	// the standard mission list, effectively pausing them until necessary data is restored.
	auto mit = stable_partition(missions.begin(), missions.end(), mem_fn(&Mission::IsValid));
	if(mit != missions.end())
		inactiveMissions.splice(inactiveMissions.end(), missions, mit, missions.end());

	// Invalid available jobs or missions are erased (since there is no guarantee
	// the player will be on the correct planet when a plugin is re-added).
	auto isInvalidMission = [](const Mission &m) noexcept -> bool { return !m.IsValid(); };
	availableJobs.remove_if(isInvalidMission);
	availableMissions.remove_if(isInvalidMission);
}



// Helper to register derived conditions.
void PlayerInfo::RegisterDerivedConditions()
{
	// Read-only date functions.
	conditions["day"].ProvideNamed([this](const ConditionEntry &ce) { return date.Day(); });
	conditions["month"].ProvideNamed([this](const ConditionEntry &ce) { return date.Month(); });
	conditions["year"].ProvideNamed([this](const ConditionEntry &ce) { return date.Year(); });
	conditions["weekday: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		string day = ce.NameWithoutPrefix();
		int number = date.WeekdayNumberOffset();
		if(day == "saturday")
			return number == 0;
		if(day == "sunday")
			return number == 1;
		if(day == "monday")
			return number == 2;
		if(day == "tuesday")
			return number == 3;
		if(day == "wednesday")
			return number == 4;
		if(day == "thursday")
			return number == 5;
		if(day == "friday")
			return number == 6;
		return 0;
	});
	conditions["days since year start"].ProvideNamed([this](const ConditionEntry &ce) {
		return date.DaysSinceYearStart(); });
	conditions["days until year end"].ProvideNamed([this](const ConditionEntry &ce) {
		return date.DaysUntilYearEnd(); });
	conditions["days since epoch"].ProvideNamed([this](const ConditionEntry &ce) {
		return date.DaysSinceEpoch(); });
	conditions["days since start"].ProvideNamed([this](const ConditionEntry &ce) {
		return date.DaysSinceEpoch() - StartData().GetDate().DaysSinceEpoch(); });

	// Read-only account conditions.
	// Bound financial conditions to +/- 4.6 x 10^18 credits, within the range of a 64-bit int.
	static constexpr int64_t limit = static_cast<int64_t>(1) << 62;

	conditions["net worth"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, max(-limit, accounts.NetWorth())); });
	conditions["credits"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.Credits()); });
	conditions["unpaid mortgages"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.TotalDebt("Mortgage")); });
	conditions["unpaid fines"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.TotalDebt("Fine")); });
	conditions["unpaid debts"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.TotalDebt("Debt")); });
	conditions["unpaid salaries"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.CrewSalariesOwed()); });
	conditions["unpaid maintenance"].ProvideNamed([this](const ConditionEntry &ce) {
		return min(limit, accounts.MaintenanceDue()); });
	conditions["credit score"].ProvideNamed([this](const ConditionEntry &ce) {
		return accounts.CreditScore(); });

	// Read/write assets and debts.
	conditions["salary: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const map<string, int64_t> &si = accounts.SalariesIncome();
		auto it = si.find(ce.NameWithoutPrefix());
		if(it == si.end())
			return 0;
		return it->second;
	}, [this](ConditionEntry &ce, int64_t value) -> void {
		accounts.SetSalaryIncome(ce.NameWithoutPrefix(), value);
	});
	conditions["tribute: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Planet *planet = GameData::Planets().Find(ce.NameWithoutPrefix());
		if(!planet)
			return 0;

		auto it = tributeReceived.find(planet);
		if(it == tributeReceived.end())
			return 0;

		return it->second;
	}, [this](ConditionEntry &ce, int64_t value) -> void {
		SetTribute(ce.NameWithoutPrefix(), value);
	});

	conditions["license: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		return HasLicense(ce.NameWithoutPrefix());
	}, [this](ConditionEntry &ce, int64_t value) -> void {
		if(!value)
			RemoveLicense(ce.NameWithoutPrefix());
		else
			AddLicense(ce.NameWithoutPrefix());
	});

	// Read-only flagship conditions.
	conditions["flagship crew"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->Crew() : 0; });
	conditions["flagship required crew"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->RequiredCrew() : 0; });
	conditions["flagship bunks"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->Attributes().Get("bunks") : 0; });
	conditions["flagship model: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		if(!flagship)
			return false;
		return !ce.NameWithoutPrefix().compare(flagship->TrueModelName()); });
	conditions["flagship disabled"].ProvideNamed([this](const ConditionEntry &ce) -> bool {
		return flagship && flagship->IsDisabled(); });

	auto shipAttributeHelper = [](const Ship *ship, const string &attribute, bool base) -> int64_t
	{
		if(!ship)
			return 0;

		const Outfit &attributes = base ? ship->BaseAttributes() : ship->Attributes();
		if(attribute == "cost")
			return attributes.Cost();
		if(attribute == "mass")
			return round(attributes.Mass() * 1000.);
		return round(attributes.Get(attribute) * 1000.);
	};
	conditions["flagship base attribute: "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) ->
		int64_t { return shipAttributeHelper(this->Flagship(), ce.NameWithoutPrefix(), true); });
	conditions["flagship attribute: "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) -> int64_t {
		return shipAttributeHelper(this->Flagship(), ce.NameWithoutPrefix(), false); });
	conditions["flagship bays: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->BaysTotal(ce.NameWithoutPrefix()); });

	// The behaviour of this condition while landed is not stable and may change in the future.
	// It should only be used while in-flight.
	conditions["flagship bays free: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		if(GetPlanet())
			Logger::LogError("Warning: Use of \"flagship bays free: <category>\""
				" condition while landed is unstable behavior.");
		return flagship->BaysFree(ce.NameWithoutPrefix()); });
	conditions["flagship bays"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->Bays().size(); });
	// The behaviour of this condition while landed is not stable and may change in the future.
	// It should only be used while in-flight.
	conditions["flagship bays free"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		if(GetPlanet())
			Logger::LogError("Warning: Use of \"flagship bays free\" condition while landed is unstable behavior.");
		const vector<Ship::Bay> &bays = flagship->Bays();
		return count_if(bays.begin(), bays.end(), [](const Ship::Bay &bay) { return !bay.ship; }); });

	conditions["flagship mass"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->Mass() : 0; });
	conditions["flagship shields"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->ShieldLevel() : 0; });
	conditions["flagship hull"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->HullLevel() : 0; });
	conditions["flagship fuel"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->FuelLevel() : 0; });

	conditions["ship base attribute: "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) ->
	int64_t {
		string attribute = ce.NameWithoutPrefix();
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			// Destroyed and parked ships aren't checked.
			// If not on a planet, the ship's system must match.
			// If on a planet, the ship's planet must match.
			if(ship->IsDestroyed() || ship->IsParked()
					|| (planet && ship->GetPlanet() != planet)
					|| (!planet && ship->GetActualSystem() != system))
				continue;
			retVal += shipAttributeHelper(ship.get(), attribute, true);
		}
		return retVal; });
	conditions["ship base attribute (all): "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) ->
	int64_t {
		string attribute = ce.NameWithoutPrefix();
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			if(ship->IsDestroyed())
				continue;
			retVal += shipAttributeHelper(ship.get(), attribute, true);
		}
		return retVal; });
	conditions["ship base attribute (parked): "].ProvidePrefixed(
		[this, shipAttributeHelper](const ConditionEntry &ce) -> int64_t {
			// If the player isn't landed then there can be no parked ships local to them.
			if(!planet)
				return 0;
			string attribute = ce.NameWithoutPrefix();
			int64_t retVal = 0;
			for(const shared_ptr<Ship> &ship : ships)
			{
				if(!ship->IsParked() || ship->GetPlanet() != planet)
					continue;
				retVal += shipAttributeHelper(ship.get(), attribute, true);
			}
			return retVal; });
	conditions["ship attribute: "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) -> int64_t {
		string attribute = ce.NameWithoutPrefix();
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			// Destroyed and parked ships aren't checked.
			// If not on a planet, the ship's system must match.
			// If on a planet, the ship's planet must match.
			if(ship->IsDestroyed() || ship->IsParked()
					|| (planet && ship->GetPlanet() != planet)
					|| (!planet && ship->GetActualSystem() != system))
				continue;
			retVal += shipAttributeHelper(ship.get(), attribute, false);
		}
		return retVal; });
	conditions["ship attribute (all): "].ProvidePrefixed([this, shipAttributeHelper](const ConditionEntry &ce) -> int64_t {
		string attribute = ce.NameWithoutPrefix();
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			if(ship->IsDestroyed())
				continue;
			retVal += shipAttributeHelper(ship.get(), attribute, false);
		}
		return retVal; });
	conditions["ship attribute (parked): "].ProvidePrefixed(
		[this, shipAttributeHelper](const ConditionEntry &ce) -> int64_t {
			// If the player isn't landed then there can be no parked ships local to them.
			if(!planet)
				return 0;
			string attribute = ce.NameWithoutPrefix();
			int64_t retVal = 0;
			for(const shared_ptr<Ship> &ship : ships)
			{
				if(!ship->IsParked() || ship->GetPlanet() != planet)
					continue;
				retVal += shipAttributeHelper(ship.get(), attribute, false);
			}
			return retVal; });

	conditions["name: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		return !ce.NameWithoutPrefix().compare(firstName + " " + lastName); });
	conditions["first name: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		return !ce.NameWithoutPrefix().compare(firstName); });
	conditions["last name: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		return !ce.NameWithoutPrefix().compare(lastName); });

	// Conditions for your fleet's attractiveness to pirates.
	conditions["cargo attractiveness"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return RaidFleetFactors().first; });
	conditions["armament deterrence"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return RaidFleetFactors().second; });
	conditions["pirate attraction"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		auto rff = RaidFleetFactors();
		return rff.first - rff.second; });
	conditions["raid chance in system: "].ProvidePrefixed([this](const ConditionEntry &ce) -> double {
		const System *system = GameData::Systems().Find(ce.NameWithoutPrefix());
		if(!system)
			return 0.;

		// This variable represents the probability of no raid fleets spawning.
		double safeChance = 1.;
		for(const auto &raidFleet : system->RaidFleets())
		{
			// The attraction is the % chance for a single instance of this fleet to appear.
			double attraction = RaidFleetAttraction(raidFleet, system);
			// Calculate the % chance for no instances to appear from 10 rolls.
			double noFleetProb = pow(1. - attraction, 10.);
			// The chance of neither of two fleets appearing is the chance of the first not appearing
			// times the chance of the second not appearing.
			safeChance *= noFleetProb;
		}
		// The probability of any single fleet appearing is 1 - chance.
		return round((1. - safeChance) * 1000.); });

	// Special conditions about combat power.
	conditions["flagship strength"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return flagship ? flagship->Strength() : 0;
	});
	conditions["player strength"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t strength = 0;
		for(const shared_ptr<Ship> &ship : ships)
			strength += ship->Strength();
		return strength;
	});

	// Special conditions for cargo and passenger space.
	conditions["cargo space"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system)
				retVal += ship->Attributes().Get("cargo space");
		return retVal; });
	conditions["passenger space"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system)
				retVal += ship->Attributes().Get("bunks") - ship->RequiredCrew();
		return retVal; });
	conditions["cargo space free"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system)
				retVal += ship->Cargo().Free();
		return retVal; });
	conditions["passenger space free"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system)
				retVal += ship->Cargo().BunksFree();
		return retVal; });

	conditions["flagship: cargo space"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->Attributes().Get("cargo space"); });
	conditions["flagship: passenger space"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->Attributes().Get("bunks") - flagship->RequiredCrew(); });
	conditions["flagship: cargo space free"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->Cargo().Free(); });
	conditions["flagship: passenger space free"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		return flagship->Cargo().BunksFree(); });

	// The number of active, present ships the player has of the given category
	// (e.g. Heavy Warships).
	conditions["ships: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		string category = ce.NameWithoutPrefix();
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system
					&& !category.compare(ship->Attributes().Category()))
				++retVal;
		return retVal; });
	// The number of ships the player has of the given category anywhere in their fleet.
	conditions["ships (all): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		string category = ce.NameWithoutPrefix();
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsDestroyed() && !category.compare(ship->Attributes().Category()))
				++retVal;
		return retVal; });
	// The number of ships the player has of the given model active and present.
	conditions["ship model: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		string model = ce.NameWithoutPrefix();
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system
					&& !model.compare(ship->TrueModelName()))
				++retVal;
		return retVal; });
	// The number of ships that the player has of the given model anywhere in their fleet.
	conditions["ship model (all): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		string model = ce.NameWithoutPrefix();
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsDestroyed() && !model.compare(ship->TrueModelName()))
				++retVal;
		return retVal; });
	// The total number of ships the player has active and present.
	conditions["total ships"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsParked() && !ship->IsDisabled() && ship->GetActualSystem() == system)
				++retVal;
		return retVal; });
	// The total number of ships the player has anywhere.
	conditions["total ships (all)"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsDestroyed())
				++retVal;
		return retVal; });

	// The following condition checks all sources of outfits which are present with the player.
	// If in orbit, this means checking all ships in-system for installed and in cargo outfits.
	// If landed, this means checking all landed ships for installed outfits, the pooled cargo
	// hold, and the planetary storage of the planet. Excludes parked ships.
	conditions["outfit: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		if(planet)
		{
			retVal += Cargo().Get(outfit);
			auto it = planetaryStorage.find(planet);
			if(it != planetaryStorage.end())
				retVal += it->second.Get(outfit);
		}
		for(const shared_ptr<Ship> &ship : ships)
		{
			// Destroyed and parked ships aren't checked.
			// If not on a planet, the ship's system must match.
			// If on a planet, the ship's planet must match.
			if(ship->IsDestroyed() || ship->IsParked()
					|| (planet && ship->GetPlanet() != planet)
					|| (!planet && ship->GetActualSystem() != system))
				continue;
			retVal += ship->OutfitCount(outfit);
			retVal += ship->Cargo().Get(outfit);
		}
		return retVal;
	});

	// Conditions to determine what outfits the player owns, with various possible locations to check.
	// The following condition checks all possible locations for outfits in the player's possession.
	conditions["outfit (all): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = Cargo().Get(outfit);
		for(const shared_ptr<Ship> &ship : ships)
		{
			if(ship->IsDestroyed())
				continue;
			retVal += ship->OutfitCount(outfit);
			retVal += ship->Cargo().Get(outfit);
		}
		for(const auto &storage : planetaryStorage)
			retVal += storage.second.Get(outfit);
		return retVal;
	});

	// The following condition checks the player's fleet for installed outfits on active
	// escorts local to the player.
	conditions["outfit (installed): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			// Destroyed and parked ships aren't checked.
			// If not on a planet, the ship's system must match.
			// If on a planet, the ship's planet must match.
			if(ship->IsDestroyed() || ship->IsParked()
					|| (planet && ship->GetPlanet() != planet)
					|| (!planet && ship->GetActualSystem() != system))
				continue;
			retVal += ship->OutfitCount(outfit);
		}
		return retVal;
	});

	// The following condition checks the player's fleet for installed outfits on parked escorts
	// which are local to the player.
	conditions["outfit (parked): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		// If the player isn't landed then there can be no parked ships local to them.
		if(!planet)
			return 0;
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
		{
			if(!ship->IsParked() || ship->GetPlanet() != planet)
				continue;
			retVal += ship->OutfitCount(outfit);
		}
		return retVal;
	});

	// The following condition checks the player's entire fleet for installed outfits.
	conditions["outfit (all installed): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsDestroyed())
				retVal += ship->OutfitCount(outfit);
		return retVal;
	});

	// The following condition checks the flagship's installed outfits.
	conditions["outfit (flagship installed): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		if(!flagship)
			return 0;
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		return flagship->OutfitCount(outfit);
	});

	// The following condition checks the player's fleet for outfits in the cargo of escorts
	// local to the player.
	conditions["outfit (cargo): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		if(planet)
			retVal += Cargo().Get(outfit);
		for(const shared_ptr<Ship> &ship : ships)
		{
			// If not on a planet, parked ships in system don't count.
			// If on a planet, the ship's planet must match.
			if(ship->IsDestroyed() || (planet && ship->GetPlanet() != planet)
					|| (!planet && (ship->GetActualSystem() != system || ship->IsParked())))
				continue;
			retVal += ship->Cargo().Get(outfit);
		}
		return retVal;
	});

	// The following condition checks all cargo locations in the player's fleet.
	conditions["outfit (all cargo): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		if(planet)
			retVal += Cargo().Get(outfit);
		for(const shared_ptr<Ship> &ship : ships)
			if(!ship->IsDestroyed())
				retVal += ship->Cargo().Get(outfit);
		return retVal;
	});

	// The following condition checks the flagship's cargo or the pooled cargo if landed.
	conditions["outfit (flagship cargo): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		return (flagship ? flagship->Cargo().Get(outfit) : 0) + (planet ? Cargo().Get(outfit) : 0);
	});

	// The following condition checks planetary storage on the current planet, or on
	// planets in the current system if in orbit.
	conditions["outfit (storage): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		if(planet)
		{
			auto it = planetaryStorage.find(planet);
			return it != planetaryStorage.end() ? it->second.Get(outfit) : 0;
		}
		else
		{
			int64_t retVal = 0;
			for(const StellarObject &object : system->Objects())
			{
				auto it = planetaryStorage.find(object.GetPlanet());
				if(object.HasValidPlanet() && it != planetaryStorage.end())
					retVal += it->second.Get(outfit);
			}
			return retVal;
		}
	});

	// The following condition checks all planetary storage.
	conditions["outfit (all storage): "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Outfit *outfit = GameData::Outfits().Find(ce.NameWithoutPrefix());
		if(!outfit)
			return 0;
		int64_t retVal = 0;
		for(const auto &storage : planetaryStorage)
			retVal += storage.second.Get(outfit);
		return retVal;
	});

	// This condition corresponds to the method by which the flagship entered the current system.
	conditions["entered system by: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		return !ce.NameWithoutPrefix().compare(EntryToString(entry)); });
	// This condition corresponds to the last system the flagship was in.
	conditions["previous system: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		if(!previousSystem)
			return false;
		return !ce.NameWithoutPrefix().compare(previousSystem->TrueName()); });

	// Conditions to determine if flagship is in a system and on a planet.
	conditions["flagship system: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		if(!flagship || !flagship->GetSystem())
			return false;
		return !ce.NameWithoutPrefix().compare(flagship->GetSystem()->TrueName()); });
	conditions["flagship landed"].ProvideNamed([this](const ConditionEntry &ce) -> bool {
		return (flagship && flagship->GetPlanet()); });
	conditions["flagship planet: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		if(!flagship || !flagship->GetPlanet())
			return false;
		return !ce.NameWithoutPrefix().compare(flagship->GetPlanet()->TrueName()); });
	conditions["flagship planet attribute: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		if(!flagship || !flagship->GetPlanet())
			return false;
		string attribute = ce.NameWithoutPrefix();
		return flagship->GetPlanet()->Attributes().contains(attribute); });

	// Read only exploration conditions.
	conditions["visited planet: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		const Planet *planet = GameData::Planets().Find(ce.NameWithoutPrefix());
		return planet ? HasVisited(*planet) : false; });
	conditions["visited system: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		const System *system = GameData::Systems().Find(ce.NameWithoutPrefix());
		return system ? HasVisited(*system) : false; });
	conditions["landing access: "].ProvidePrefixed([this](const ConditionEntry &ce) -> bool {
		const Planet *planet = GameData::Planets().Find(ce.NameWithoutPrefix());
		return (planet && flagship) ? planet->CanLand(*flagship) : false; });

	conditions["installed plugin: "].ProvidePrefixed([](const ConditionEntry &ce) -> bool {
		const Plugin *plugin = Plugins::Get().Find(ce.NameWithoutPrefix());
		return plugin ? plugin->IsValid() && plugin->enabled : false; });

	conditions["person destroyed: "].ProvidePrefixed([](const ConditionEntry &ce) -> bool {
		const Person *person = GameData::Persons().Find(ce.NameWithoutPrefix());
		return person ? person->IsDestroyed() : false; });

	// Read-only navigation conditions.
	auto HyperspaceTravelDays = [](const System *origin, const System *destination) -> int
	{
		if(!origin)
			return -1;

		auto distanceMap = DistanceMap(origin);
		if(!distanceMap.HasRoute(*destination))
			return -1;
		return distanceMap.Days(*destination);
	};

	conditions["hyperjumps to system: "].ProvidePrefixed([this, HyperspaceTravelDays](const ConditionEntry &ce) -> int {
		const System *system = GameData::Systems().Find(ce.NameWithoutPrefix());
		if(!system)
		{
			Logger::LogError("Warning: System \"" + ce.NameWithoutPrefix()
					+ "\" referred to in condition is not valid.");
			return -1;
		}
		return HyperspaceTravelDays(this->GetSystem(), system);
	});

	conditions["hyperjumps to planet: "].ProvidePrefixed([this, HyperspaceTravelDays](const ConditionEntry &ce) -> int {
		const Planet *planet = GameData::Planets().Find(ce.NameWithoutPrefix());
		if(!planet)
		{
			Logger::LogError("Warning: Planet \"" + ce.NameWithoutPrefix()
					+ "\" referred to in condition is not valid.");
			return -1;
		}
		const System *system = planet->GetSystem();
		if(!system)
		{
			Logger::LogError("Warning: Planet \"" + ce.NameWithoutPrefix()
					+ "\" referred to in condition is not in any system.");
			return -1;
		}
		return HyperspaceTravelDays(this->GetSystem(), system);
	});

	// Read/write government reputation conditions.
	// The erase function is still default (since we cannot erase government conditions).
	conditions["reputation: "].ProvidePrefixed([](const ConditionEntry &ce) -> int64_t {
		string govName = ce.NameWithoutPrefix();
		auto gov = GameData::Governments().Get(govName);
		if(!gov)
			return 0;
		return gov->Reputation();
	}, [](ConditionEntry &ce, int64_t value) -> void
	{
		string govName = ce.NameWithoutPrefix();
		auto gov = GameData::Governments().Get(govName);
		if(!gov)
			return;
		gov->SetReputation(value);
	});

	// A condition for returning a random integer in the range [0, 100).
	conditions["random"].ProvideNamed([](const ConditionEntry &ce) -> int64_t {
		return Random::Int(100); });

	// A condition for returning a random integer in the range [0, input). Input may be a number,
	// or it may be the name of a condition. For example, "roll: 100" would roll a random
	// integer in the range [0, 100), but if you had a condition "max roll" with a value of 100,
	// calling "roll: max roll" would provide a value from the same range.
	// Returns 0 if the input condition's value is <= 1.
	conditions["roll: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		string input = ce.NameWithoutPrefix();
		int64_t value = 0;
		if(DataNode::IsNumber(input))
			value = static_cast<int64_t>(DataNode::Value(input));
		else
			value = conditions.Get(input);
		if(value <= 1)
			return 0;
		return Random::Int(value);
	});

	// Gamerule condition getter:
	conditions["gamerule: "].ProvidePrefixed([](const ConditionEntry &ce) -> int64_t {
		return GameData::GetGamerules().GetValue(ce.NameWithoutPrefix());
	});

	// Global conditions setters and getters:
	conditions["global: "].ProvidePrefixed([](const ConditionEntry &ce) -> int64_t {
		string globalCondition = ce.NameWithoutPrefix();
		return GameData::GlobalConditions().Get(globalCondition);
	}, [](ConditionEntry &ce, int64_t value)
	{
		GameData::GlobalConditions().Set(ce.NameWithoutPrefix(), value);
	});
}



// New missions are generated each time you land on a planet.
void PlayerInfo::CreateMissions()
{
	availableBoardingMissions.clear();
	availableEnteringMissions.clear();

	// Check for available missions.
	bool skipJobs = planet && !planet->GetPort().HasService(Port::ServicesType::JobBoard);
	bool hasPriorityMissions = false;
	unsigned nonBlockingMissions = 0;
	for(const auto &[name, mission] : GameData::Missions())
	{
		if(mission.IsAtLocation(Mission::BOARDING) || mission.IsAtLocation(Mission::ASSISTING)
				|| mission.IsAtLocation(Mission::ENTERING))
			continue;
		if(skipJobs && mission.IsAtLocation(Mission::JOB))
			continue;

		if(mission.CanOffer(*this))
		{
			list<Mission> &missions =
				mission.IsAtLocation(Mission::JOB) ? availableJobs : availableMissions;

			missions.push_back(mission.Instantiate(*this));
			if(missions.back().IsFailed())
				missions.pop_back();
			else if(!mission.IsAtLocation(Mission::JOB))
			{
				hasPriorityMissions |= missions.back().HasPriority();
				nonBlockingMissions += missions.back().IsNonBlocking();
			}
		}
	}

	SortMissions(availableMissions, hasPriorityMissions, nonBlockingMissions);
}



// Updates each mission upon landing, to perform landing actions (Stopover,
// Visit, Complete, Fail), and remove now-complete or now-failed missions.
void PlayerInfo::StepMissions(UI *ui)
{
	// Check for NPCs that have been destroyed without their destruction
	// being registered, e.g. by self-destruct:
	for(Mission &mission : missions)
		for(const NPC &npc : mission.NPCs())
			for(const shared_ptr<Ship> &ship : npc.Ships())
				if(ship->IsDestroyed())
					mission.Do(ShipEvent(nullptr, ship, ShipEvent::DESTROY), *this, ui);

	// Check missions for status changes from landing.
	string visitText;
	int missionVisits = 0;
	auto substitutions = map<string, string>{
		{"<first>", firstName},
		{"<last>", lastName}
	};
	const Ship *flag = Flagship();
	if(flag)
	{
		substitutions["<ship>"] = flag->GivenName();
		substitutions["<model>"] = flag->DisplayModelName();
		substitutions["<flagship>"] = flag->GivenName();
		substitutions["<flagship model>"] = flag->DisplayModelName();
	}

	auto mit = missions.begin();
	while(mit != missions.end())
	{
		Mission &mission = *mit;
		++mit;

		// If this is a stopover for the mission, perform the stopover action.
		mission.Do(Mission::STOPOVER, *this, ui);

		if(mission.IsFailed())
			RemoveMission(Mission::FAIL, mission, ui);
		else if(mission.CanComplete(*this))
			RemoveMission(Mission::COMPLETE, mission, ui);
		else if(mission.Destination() == GetPlanet() && !freshlyLoaded)
		{
			mission.Do(Mission::VISIT, *this, ui);
			if(mission.IsUnique() || !mission.IsVisible())
				continue;

			// On visit dialogs are handled separately as to avoid a player
			// getting spammed by on visit dialogs if they are stacking jobs
			// from the same destination.
			if(visitText.empty())
			{
				const auto &text = mission.GetAction(Mission::VISIT).DialogText();
				if(!text.empty())
					visitText = Format::Replace(text, substitutions);
			}
			++missionVisits;
		}
	}
	if(!visitText.empty())
	{
		if(missionVisits > 1)
			visitText += "\n\t(You have " + Format::Number(missionVisits - 1) + " other unfinished "
				+ ((missionVisits > 2) ? "missions" : "mission") + " at this location.)";
		ui->Push(new Dialog(visitText));
	}
	// One mission's actions may influence another mission, so loop through one
	// more time to see if any mission is now completed or failed due to a change
	// that happened in another mission the first time through.
	mit = missions.begin();
	while(mit != missions.end())
	{
		Mission &mission = *mit;
		++mit;

		if(mission.IsFailed())
			RemoveMission(Mission::FAIL, mission, ui);
		else if(mission.CanComplete(*this))
			RemoveMission(Mission::COMPLETE, mission, ui);
	}

	// Search for any missions that have failed but for which we are still
	// holding on to some cargo.
	set<const Mission *> active;
	for(const Mission &it : missions)
		active.insert(&it);

	vector<const Mission *> missionsToRemove;
	for(const auto &it : cargo.MissionCargo())
		if(!active.contains(it.first))
			missionsToRemove.push_back(it.first);
	for(const auto &it : cargo.PassengerList())
		if(!active.contains(it.first))
			missionsToRemove.push_back(it.first);
	for(const Mission *mission : missionsToRemove)
		cargo.RemoveMissionCargo(mission);
}



void PlayerInfo::Autosave() const
{
	if(!CanBeSaved() || filePath.length() < 4)
		return;

	string path = filePath.substr(0, filePath.length() - 4) + "~autosave.txt";
	Save(path);
}



void PlayerInfo::Save(const string &filePath) const
{
	if(transactionSnapshot)
		transactionSnapshot->SaveToPath(filePath);
	else
	{
		DataWriter out(filePath);
		Save(out);
	}
}



void PlayerInfo::Save(DataWriter &out) const
{
	// Basic player information and persistent UI settings:

	// Pilot information:
	out.Write("pilot", firstName, lastName);
	out.Write("date", date.Day(), date.Month(), date.Year());
	out.Write("system entry method", EntryToString(entry));
	if(previousSystem)
		out.Write("previous system", previousSystem->TrueName());
	if(system)
		out.Write("system", system->TrueName());
	if(planet)
		out.Write("planet", planet->TrueName());
	if(planet && planet->CanUseServices())
		out.Write("clearance");
	out.Write("playtime", playTime);
	// This flag is set if the player must leave the planet immediately upon
	// entering their ship (i.e. because a mission forced them to take off).
	if(shouldLaunch)
		out.Write("launching");
	for(const System *system : travelPlan)
		out.Write("travel", system->TrueName());
	if(travelDestination)
		out.Write("travel destination", travelDestination->TrueName());
	// Detect which ship number is the current flagship, for showing on LoadPanel.
	if(flagship)
	{
		for(auto it = ships.begin(); it != ships.end(); ++it)
			if(*it == flagship)
			{
				out.Write("flagship index", distance(ships.begin(), it));
				break;
			}
	}
	else
		out.Write("flagship index", -1);

	// Save the current setting for the map coloring;
	out.Write("map coloring", mapColoring);
	out.Write("map zoom", mapZoom);
	// Remember what categories are collapsed.
	for(const auto &it : collapsed)
	{
		// Skip panels where nothing was collapsed.
		if(it.second.empty())
			continue;

		out.Write("collapsed", it.first);
		out.BeginChild();
		{
			for(const auto &cit : it.second)
				out.Write(cit);
		}
		out.EndChild();
	}

	out.Write("reputation with");
	out.BeginChild();
	{
		for(const auto &it : GameData::Governments())
			if(!it.second.IsPlayer())
				out.Write(it.first, it.second.Reputation());
	}
	out.EndChild();

	out.Write("tribute received");
	out.BeginChild();
	{
		for(const auto &it : tributeReceived)
			if(it.second > 0)
				out.Write((it.first)->TrueName(), it.second);
	}
	out.EndChild();

	// Records of things you own:
	out.Write();
	out.WriteComment("What you own:");

	// Save all the data for all the player's ships.
	for(const shared_ptr<Ship> &ship : ships)
	{
		ship->Save(out);
		auto it = groups.find(ship.get());
		if(it != groups.end() && it->second)
			out.Write("groups", it->second);
	}
	if(!planetaryStorage.empty())
	{
		out.Write("storage");
		out.BeginChild();
		{
			for(const auto &it : planetaryStorage)
				if(!it.second.IsEmpty())
				{
					out.Write("planet", it.first->TrueName());
					out.BeginChild();
					{
						it.second.Save(out);
					}
					out.EndChild();
				}
		}
		out.EndChild();
	}
	if(!licenses.empty())
	{
		out.Write("licenses");
		out.BeginChild();
		{
			for(const string &license : licenses)
				out.Write(license);
		}
		out.EndChild();
	}

	// Save accounting information, cargo, and cargo cost bases.
	accounts.Save(out);
	cargo.Save(out);
	if(!costBasis.empty())
	{
		out.Write("basis");
		out.BeginChild();
		{
			for(const auto &it : costBasis)
				if(it.second)
					out.Write(it.first, it.second);
		}
		out.EndChild();
	}

	if(!stock.empty())
	{
		out.Write("stock");
		out.BeginChild();
		{
			using StockElement = pair<const Outfit *const, int>;
			WriteSorted(stock,
				[](const StockElement *lhs, const StockElement *rhs)
					{ return lhs->first->TrueName() < rhs->first->TrueName(); },
				[&out](const StockElement &it)
				{
					if(it.second)
						out.Write(it.first->TrueName(), it.second);
				});
		}
		out.EndChild();
	}
	depreciation.Save(out, date.DaysSinceEpoch());
	stockDepreciation.Save(out, date.DaysSinceEpoch());


	// Records of things you have done or are doing, or have happened to you:
	out.Write();
	out.WriteComment("What you've done:");

	// Save all missions (accepted, accepted-but-invalid, and available).
	for(const Mission &mission : missions)
		mission.Save(out);
	for(const Mission &mission : inactiveMissions)
		mission.Save(out);
	map<string, map<string, int>> offWorldMissionCargo;
	map<string, map<string, int>> offWorldMissionPassengers;
	for(const auto &it : ships)
	{
		const Ship &ship = *it;
		// If the ship is at the player's planet, its mission cargo allocation does not need to be saved.
		if(ship.GetPlanet() == planet)
			continue;
		for(const auto &cargo : ship.Cargo().MissionCargo())
			offWorldMissionCargo[cargo.first->UUID().ToString()][ship.UUID().ToString()] = cargo.second;
		for(const auto &passengers : ship.Cargo().PassengerList())
			offWorldMissionPassengers[passengers.first->UUID().ToString()][ship.UUID().ToString()] = passengers.second;
	}
	auto SaveMissionCargoDistribution = [&out](const map<string, map<string, int>> &toSave, bool passengers) -> void
	{
		if(passengers)
			out.Write("mission passengers");
		else
			out.Write("mission cargo");
		out.BeginChild();
		{
			out.Write("player ships");
			out.BeginChild();
			{
				for(const auto &it : toSave)
					for(const auto &sit : it.second)
						out.Write(it.first, sit.first, sit.second);
			}
			out.EndChild();
		}
		out.EndChild();
	};
	if(!offWorldMissionCargo.empty())
		SaveMissionCargoDistribution(offWorldMissionCargo, false);
	if(!offWorldMissionPassengers.empty())
		SaveMissionCargoDistribution(offWorldMissionPassengers, true);

	for(const Mission &mission : availableJobs)
		mission.Save(out, "available job");
	for(const Mission &mission : availableMissions)
		mission.Save(out, "available mission");
	out.Write("sort type", static_cast<int>(availableSortType));
	if(!availableSortAsc)
		out.Write("sort descending");
	if(sortSeparateDeadline)
		out.Write("separate deadline");
	if(sortSeparatePossible)
		out.Write("separate possible");

	// Save any "primary condition" flags that are set.
	conditions.Save(out);

	// Save the UUID of any ships given to the player with a specified name, and ship class.
	if(!giftedShips.empty())
	{
		out.Write("gifted ships");
		out.BeginChild();
		{
			for(const auto &it : giftedShips)
				out.Write(it.first, it.second.ToString());
		}
		out.EndChild();
	}

	// Save pending events, and changes that have happened due to past events.
	for(const GameEvent &event : gameEvents)
		event.Save(out);
	if(!dataChanges.empty())
	{
		out.Write("changes");
		out.BeginChild();
		{
			for(const DataNode &node : dataChanges)
				out.Write(node);
		}
		out.EndChild();
	}
	GameData::WriteEconomy(out);

	// Check which persons have been captured or destroyed.
	for(const auto &it : GameData::Persons())
		if(it.second.IsDestroyed())
			out.Write("destroyed", it.first);


	// Records of things you have discovered:
	out.Write();
	out.WriteComment("What you know:");

	// Save a list of systems the player has visited.
	WriteSorted(visitedSystems,
		[](const System *const *lhs, const System *const *rhs)
			{ return (*lhs)->TrueName() < (*rhs)->TrueName(); },
		[&out](const System *system)
		{
			out.Write("visited", system->TrueName());
		});

	// Save a list of planets the player has visited.
	WriteSorted(visitedPlanets,
		[](const Planet *const *lhs, const Planet *const *rhs)
			{ return (*lhs)->TrueName() < (*rhs)->TrueName(); },
		[&out](const Planet *planet)
		{
			out.Write("visited planet", planet->TrueName());
		});

	if(!harvested.empty())
	{
		out.Write("harvested");
		out.BeginChild();
		{
			using HarvestLog = pair<const System *, const Outfit *>;
			WriteSorted(harvested,
				[](const HarvestLog *lhs, const HarvestLog *rhs) -> bool
				{
					// Sort by system name and then by outfit name.
					if(lhs->first != rhs->first)
						return lhs->first->TrueName() < rhs->first->TrueName();
					else
						return lhs->second->TrueName() < rhs->second->TrueName();
				},
				[&out](const HarvestLog &it)
				{
					out.Write(it.first->TrueName(), it.second->TrueName());
				});
		}
		out.EndChild();
	}

	out.Write("logbook");
	out.BeginChild();
	{
		for(auto &&it : logbook)
		{
			out.Write(it.first.Day(), it.first.Month(), it.first.Year());
			out.BeginChild();
			{
				// Break the text up into paragraphs.
				for(const string &line : Format::Split(it.second, "\n\t"))
					out.Write(line);
			}
			out.EndChild();
		}
		for(auto &&it : specialLogs)
			for(auto &&eit : it.second)
			{
				out.Write(it.first, eit.first);
				out.BeginChild();
				{
					// Break the text up into paragraphs.
					for(const string &line : Format::Split(eit.second, "\n\t"))
						out.Write(line);
				}
				out.EndChild();
			}
	}
	out.EndChild();

	out.Write();
	out.WriteComment("How you began:");
	startData.Save(out);

	// Write plugins to player's save file for debugging.
	out.Write();
	out.WriteComment("Installed plugins:");
	out.Write("plugins");
	out.BeginChild();
	for(const auto &it : Plugins::Get())
	{
		const auto &plugin = it.second;
		if(plugin.IsValid() && plugin.enabled)
			out.Write(plugin.name);
	}
	out.EndChild();
}



// Check (and perform) any fines incurred by planetary security. If the player
// has dominated the planet, or was given clearance to this planet by a mission,
// planetary security is avoided. Infiltrating implies evasion of security.
void PlayerInfo::Fine(UI *ui)
{
	const Planet *planet = GetPlanet();
	// Dominated planets should never fine you.
	// By default, uninhabited planets should not fine the player.
	if(GameData::GetPolitics().HasDominated(planet)
		|| !(planet->IsInhabited() || planet->HasCustomSecurity()))
		return;

	// Planets should not fine you if you have mission clearance or are infiltrating.
	for(const Mission &mission : missions)
		if(mission.HasClearance(planet) || (!mission.HasFullClearance() &&
					(mission.Destination() == planet || mission.Stopovers().contains(planet))))
			return;

	// The planet's government must have the authority to enforce laws.
	const Government *gov = planet->GetGovernment();
	if(!gov->CanEnforce(planet))
		return;

	string message = gov->Fine(*this, 0, nullptr, planet->Security());
	if(!message.empty())
	{
		if(message == "atrocity")
		{
			const Conversation *conversation = gov->DeathSentence();
			if(conversation)
				ui->Push(new ConversationPanel(*this, *conversation));
			else
			{
				message = "Before you can leave your ship, the " + gov->DisplayName()
					+ " authorities show up and begin scanning it. They say, \"Captain "
					+ LastName()
					+ ", we detect highly illegal material on your ship.\""
					"\n\tYou are sentenced to lifetime imprisonment on a penal colony."
					" Your days of traveling the stars have come to an end.";
				ui->Push(new Dialog(message));
			}
			// All ships belonging to the player should be removed.
			Die();
		}
		else
			ui->Push(new Dialog(message));
	}
}



// Set the flagship (on departure or during flight).
void PlayerInfo::SetFlagship(Ship &other)
{
	// Remove active data in the old flagship.
	if(flagship && flagship.get() != &other)
		flagship->ClearTargetsAndOrders();

	// Set the new flagship pointer.
	flagship = other.shared_from_this();

	// Make sure your ships all know who the flagship is.
	for(const shared_ptr<Ship> &ship : ships)
	{
		bool shouldFollowFlagship = (ship != flagship && !ship->IsParked());
		ship->SetParent(shouldFollowFlagship ? flagship : shared_ptr<Ship>());
	}

	// Move the flagship to the beginning to the list of ships.
	MoveFlagshipBegin(ships, flagship);

	// Make sure your flagship is not included in the escort selection.
	for(auto it = selectedShips.begin(); it != selectedShips.end(); )
	{
		shared_ptr<Ship> ship = it->lock();
		if(!ship || ship == flagship)
			it = selectedShips.erase(it);
		else
			++it;
	}
}



void PlayerInfo::HandleFlagshipParking(Ship *oldFirstShip, Ship *newFirstShip)
{
	if(Preferences::Has("Automatically unpark flagship") && newFirstShip != oldFirstShip
		&& newFirstShip->CanBeFlagship() && newFirstShip->GetSystem() == system && newFirstShip->IsParked())
	{
		newFirstShip->SetIsParked(false);
		oldFirstShip->SetIsParked(true);
		UpdateCargoCapacities();
	}
}



// Helper function to update the ship selection.
void PlayerInfo::SelectShip(const shared_ptr<Ship> &ship, bool *first)
{
	// Make sure this ship is not already selected.
	auto it = selectedShips.begin();
	for( ; it != selectedShips.end(); ++it)
		if(it->lock() == ship)
			break;
	if(it == selectedShips.end())
	{
		// This ship is not yet selected.
		selectedShips.push_back(ship);
		Ship *flagship = Flagship();
		if(*first && flagship && ship.get() != flagship)
		{
			flagship->SetTargetShip(ship);
			*first = false;
		}
	}
}



// Instantiate the given model and add it to the player's fleet.
void PlayerInfo::AddStockShip(const Ship *model, const string &name)
{
	ships.push_back(make_shared<Ship>(*model));
	ships.back()->SetGivenName(!name.empty() ? name : GameData::Phrases().Get("civilian")->Get());
	ships.back()->SetSystem(system);
	ships.back()->SetPlanet(planet);
	ships.back()->SetIsSpecial();
	ships.back()->SetIsYours();
	ships.back()->SetGovernment(GameData::PlayerGovernment());
}



// When we remove a ship, forget its stored ID.
void PlayerInfo::ForgetGiftedShip(const Ship &oldShip, bool failsMissions)
{
	const EsUuid &id = oldShip.UUID();
	auto shipToForget = find_if(giftedShips.begin(), giftedShips.end(),
		[&id](const pair<const string, EsUuid> &shipId) { return shipId.second == id; });
	if(shipToForget != giftedShips.end())
	{
		if(failsMissions)
			for(auto &mission : missions)
				if(mission.RequiresGiftedShip(shipToForget->first))
					mission.Fail();
		giftedShips.erase(shipToForget);
	}
}



// Check that this player's current state can be saved.
bool PlayerInfo::CanBeSaved() const
{
	return (!isDead && planet && system && !firstName.empty() && !lastName.empty());
}



// Handle the daily salaries and payments.
void PlayerInfo::DoAccounting()
{
	// Check what salaries and tribute the player receives.
	map<string, int64_t> income;
	int64_t salariesIncome = accounts.SalariesIncomeTotal();
	if(salariesIncome)
		income["salary"] = salariesIncome;
	int64_t tributeIncome = GetTributeTotal();
	if(tributeIncome)
		income["in tribute"] = tributeIncome;
	FleetBalance balance = MaintenanceAndReturns();
	if(balance.assetsReturns)
		income["based on outfits and ships"] = balance.assetsReturns;
	if(!income.empty())
	{
		string message = "You receive " + Format::List<map, string, int64_t>(income,
			[](const pair<string, int64_t> &it)
			{
				return Format::CreditString(it.second) + ' ' + it.first;
			}) + '.';
		Messages::Add(message, Messages::Importance::High, true);
		accounts.AddCredits(salariesIncome + tributeIncome + balance.assetsReturns);
	}

	// For accounting, keep track of the player's net worth. This is for
	// calculation of yearly income to determine maximum mortgage amounts.
	int64_t assets = depreciation.Value(ships, date.DaysSinceEpoch());
	for(const shared_ptr<Ship> &ship : ships)
		assets += ship->Cargo().Value(system);

	// Have the player pay salaries, mortgages, etc. and print a message that
	// summarizes the payments that were made.
	string message = accounts.Step(assets, Salaries(), balance.maintenanceCosts);
	if(!message.empty())
		Messages::Add(message, Messages::Importance::High, true);
}



bool PlayerInfo::HasClearance() const
{
	return any_of(missions.begin(), missions.end(),
		[this](const Mission &mission) -> bool {
			return mission.HasClearance(planet);
		});
}