File: ui.cpp

package info (click to toggle)
freespace2 24.0.2%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: trixie
  • size: 43,188 kB
  • sloc: cpp: 583,107; ansic: 21,729; python: 1,174; sh: 464; makefile: 248; xml: 181
file content (2483 lines) | stat: -rw-r--r-- 67,719 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
//
//
#include "ui.h"

#include "freespace.h"

#include "globalincs/alphacolors.h"

#include "cmdline/cmdline.h"
#include "cutscene/cutscenes.h"
#include "gamesnd/eventmusic.h"
#include "gamesequence/gamesequence.h"
#include "io/key.h"
#include "menuui/barracks.h"
#include "menuui/credits.h"
#include "menuui/mainhallmenu.h"
#include "menuui/optionsmenu.h"
#include "menuui/playermenu.h"
#include "menuui/readyroom.h"
#include "mission/missionmessage.h"
#include "mission/missiongoals.h"
#include "mission/missionbriefcommon.h"
#include "mission/missionparse.h"
#include "missionui/fictionviewer.h"
#include "missionui/missionbrief.h"
#include "mission/missioncampaign.h"
#include "missionui/missionscreencommon.h"
#include "missionui/missiondebrief.h"
#include "mission/missiongoals.h"
#include "mission/missioncampaign.h"
#include "mission/missionhotkey.h"
#include "missionui/redalert.h"
#include "missionui/missionpause.h"
#include "mod_table/mod_table.h"
#include "network/multi.h"
#include "network/multiteamselect.h"
#include "network/multi_pxo.h"
#include "pilotfile/pilotfile.h"
#include "playerman/managepilot.h"
#include "radar/radarsetup.h"
#include "ship/ship.h"
#include "weapon/weapon.h"
#include "scpui/SoundPlugin.h"
#include "scpui/rocket_ui.h"
#include "scripting/api/objs/control_config.h"
#include "scripting/api/objs/techroom.h"
#include "scripting/api/objs/loop_brief.h"
#include "scripting/api/objs/redalert.h"
#include "scripting/api/objs/fictionviewer.h"
#include "scripting/api/objs/cmd_brief.h"
#include "scripting/api/objs/briefing.h"
#include "scripting/api/objs/debriefing.h"
#include "scripting/api/objs/shipwepselect.h"
#include "scripting/api/objs/missionhotkey.h"
#include "scripting/api/objs/gamehelp.h"
#include "scripting/api/objs/missionlog.h"
#include "scripting/api/objs/hudconfig.h"
#include "scripting/api/objs/color.h"
#include "scripting/api/objs/enums.h"
#include "scripting/api/objs/player.h"
#include "scripting/api/objs/medals.h"
#include "scripting/api/objs/rank.h"
#include "scripting/api/objs/texture.h"
#include "scripting/api/objs/vecmath.h"
#include "scripting/lua/LuaTable.h"
#include "sound/audiostr.h"
#include "stats/medals.h"
#include "stats/stats.h"

// Our Assert conflicts with the definitions inside libRocket
#pragma push_macro("Assert")
#undef Assert

#include <Rocket/Core/Lua/LuaType.h>

#pragma pop_macro("Assert")

namespace scripting {
namespace api {

//*************************Global UI stuff*************************
ADE_LIB(l_UserInterface, "UserInterface", "ui", "Functions for managing the \"SCPUI\" user interface system.");

ADE_FUNC(setOffset, l_UserInterface, "number x, number y",
         "Sets the offset from the top left corner at which <b>all</b> rocket contexts will be rendered", "boolean",
         "true if the operation was successful, false otherwise")
{
	float x;
	float y;

	if (!ade_get_args(L, "ff", &x, &y)) {
		return ADE_RETURN_FALSE;
	}

	scpui::setOffset(x, y);

	return ADE_RETURN_TRUE;
}

ADE_FUNC(enableInput,
	l_UserInterface,
	"any context /* A libRocket Context value */",
	"Enables input for the specified libRocket context",
	"boolean",
	"true if successful")
{
	using namespace Rocket::Core;

	// Check parameter number
	if (!ade_get_args(L, "*")) {
		return ADE_RETURN_FALSE;
	}

	auto ctx = Lua::LuaType<Context>::check(L, 1);

	if (ctx == nullptr) {
		LuaError(L, "Parameter 1 is not a valid context handle!");
		return ADE_RETURN_FALSE;
	}

	scpui::enableInput(ctx);
	game_flush();
	Main_hall_poll_key = false;

	return ADE_RETURN_TRUE;
}

ADE_FUNC(disableInput, l_UserInterface, "", "Disables UI input", "boolean", "true if successful")
{
	scpui::disableInput();
	game_flush();
	Main_hall_poll_key = true;

	return ADE_RETURN_TRUE;
}

ADE_VIRTVAR(ColorTags,
	l_UserInterface,
	nullptr,
	"The available tagged colors",
	"{ string => color ... }",
	"A mapping from tag string to color value")
{
	using namespace luacpp;

	LuaTable mapping = LuaTable::create(L);

	for (const auto& tagged : Tagged_Colors) {
		SCP_string tag;
		tag.resize(1, tagged.first);

		mapping.addValue(tag, l_Color.Set(*tagged.second));
	}

	return ade_set_args(L, "t", mapping);
}

ADE_FUNC(DefaultTextColorTag,
	l_UserInterface,
	"number UiScreen",
	"Gets the default color tag string for the specified state. 1 for Briefing, 2 for CBriefing, 3 for Debriefing, "
	"4 for Fiction Viewer, 5 for Red Alert, 6 for Loop Briefing, 7 for Recommendation text. Defaults to 1. Index into ColorTags.",
	"string",
	"The default color tag")
{
	int UiScreen;

	if (!ade_get_args(L, "i", &UiScreen)) {
		UiScreen = 1;
	}
	
	SCP_string tagStr;
	char defaultColor = default_briefing_color;

	switch (UiScreen) {
		case 1:
			defaultColor = default_briefing_color;
			break;
		case 2:
			defaultColor = default_command_briefing_color;
			break;
		case 3:
			defaultColor = default_debriefing_color;
			break;
		case 4:
			defaultColor = default_fiction_viewer_color;
			break;
		case 5:
			defaultColor = default_redalert_briefing_color;
			break;
		case 6:
			defaultColor = default_loop_briefing_color;
			break;
		case 7:
			defaultColor = default_recommendation_color;
			break;
	}

	if (defaultColor == '\0' || !brief_verify_color_tag(defaultColor)) {
		defaultColor = Color_Tags[0];
	}
	tagStr.resize(1, defaultColor);

	return ade_set_args(L, "s", tagStr);
}

ADE_FUNC(playElementSound,
	l_UserInterface,
	"any element /* A libRocket element */, string event, string state = \"\"",
	"Plays an element specific sound with an optional state for differentiating different UI states.",
	"boolean",
	"true if a sound was played, false otherwise")
{
	using namespace Rocket::Core;
	const char* event;
	const char* state = "";
	if (!ade_get_args(L, "*s|s", &event, &state)) {
		return ADE_RETURN_FALSE;
	}

	auto el = Lua::LuaType<Element>::check(L, 1);

	if (el == nullptr) {
		return ADE_RETURN_FALSE;
	}

	return ade_set_args(L, "b", scpui::SoundPlugin::instance()->PlayElementSound(el, event, state));
}

ADE_FUNC(maybePlayCutscene, l_UserInterface, "enumeration MovieType, boolean RestartMusic, number ScoreIndex", "Plays a cutscene, if one exists, for the appropriate state transition.  If RestartMusic is true, then the music score at ScoreIndex will be started after the cutscene plays.", nullptr, "Returns nothing")
{
	enum_h movie_type;
	bool restart_music = false;
	int score_index = 0;

	if (!ade_get_args(L, "obi", l_Enum.Get(&movie_type), &restart_music, &score_index))
		return ADE_RETURN_NIL;

	if (!movie_type.IsValid() || movie_type.index < LE_MOVIE_PRE_FICTION || movie_type.index > LE_MOVIE_END_CAMPAIGN)
	{
		Warning(LOCATION, "Invalid movie type index %d", movie_type.index);
		return ADE_RETURN_NIL;
	}

	common_maybe_play_cutscene(movie_type.index - LE_MOVIE_PRE_FICTION, restart_music, score_index);
	return ADE_RETURN_NIL;
}

ADE_FUNC(playCutscene, l_UserInterface, "string Filename, boolean RestartMusic, number ScoreIndex", "Plays a cutscene.  If RestartMusic is true, then the music score at ScoreIndex will be started after the cutscene plays.", nullptr, "Returns nothing")
{
	const char* filename;
	bool restart_music = false;
	int score_index = 0;

	if (!ade_get_args(L, "sbi", &filename, &restart_music, &score_index))
		return ADE_RETURN_NIL;

	common_play_cutscene(filename, restart_music, score_index);
	return ADE_RETURN_NIL;
}

ADE_FUNC(isCutscenePlaying, l_UserInterface, nullptr, "Checks if a cutscene is playing.", "boolean", "Returns true if cutscene is playing, false otherwise")
{
	return ade_set_args(L, "b", Movie_active);
}

ADE_FUNC(launchURL, l_UserInterface, "string url", "Launches the given URL in a web browser", nullptr, nullptr)
{
	const char* url;
	if (!ade_get_args(L, "s", &url))
		return ADE_RETURN_NIL;

	multi_pxo_url(url);

	return ADE_RETURN_NIL;
}

ADE_FUNC(linkTexture, l_UserInterface, "texture texture", "Links a texture directly to librocket.", "string", "The url string for librocket, or an empty string if invalid.")
{
	texture_h* tex;

	if (!ade_get_args(L, "o", l_Texture.GetPtr(&tex)))
		return ade_set_error(L, "s", "");

	if(tex == nullptr || !tex->isValid())
		return ade_set_error(L, "s", "");
	
	return ade_set_args(L, "s", "data:image/bmpman," + std::to_string(tex->handle));
}

//**********SUBLIBRARY: UserInterface/PilotSelect
ADE_LIB_DERIV(l_UserInterface_PilotSelect, "PilotSelect", nullptr,
              "API for accessing values specific to the Pilot Select UI.",
              l_UserInterface);

ADE_VIRTVAR(MAX_PILOTS, l_UserInterface_PilotSelect, nullptr, "Gets the maximum number of possible pilots.", "number",
            "The maximum number of pilots")
{
	return ade_set_args(L, "i", MAX_PILOTS);
}
ADE_VIRTVAR(WarningCount, l_UserInterface_PilotSelect, nullptr, "The amount of warnings caused by the mod while loading.", "number",
            "The maximum number of pilots")
{
	return ade_set_args(L, "i", Global_warning_count);
}
ADE_VIRTVAR(ErrorCount, l_UserInterface_PilotSelect, nullptr, "The amount of errors caused by the mod while loading.", "number",
            "The maximum number of pilots")
{
	return ade_set_args(L, "i", Global_error_count);
}

ADE_FUNC(enumeratePilots, l_UserInterface_PilotSelect, nullptr,
         "Lists all pilots available for the pilot selection<br>", "string[]",
         "A table containing the pilots (without a file extension) or nil on error")
{
	using namespace luacpp;

	auto table = LuaTable::create(L);

	auto pilots = player_select_enumerate_pilots();
	for (size_t i = 0; i < pilots.size(); ++i) {
		table.addValue(i + 1, pilots[i]);
	}

	return ade_set_args(L, "t", &table);
}

ADE_FUNC(getLastPilot, l_UserInterface_PilotSelect, nullptr,
         "Reads the last active pilot from the config file and returns some information about it. callsign is the name "
         "of the player and is_multi indicates whether the pilot was last active as a multiplayer pilot.",
         "string", "The pilot name or nil if there was no last pilot")
{
	using namespace luacpp;

	auto callsign = player_get_last_player();
	if (callsign.empty()) {
		return ADE_RETURN_NIL;
	}

	return ade_set_args(L, "s", callsign.c_str());
}

ADE_FUNC(checkPilotLanguage, l_UserInterface_PilotSelect, "string callsign",
         "Checks if the pilot with the specified callsign has the right language.", "boolean",
         "true if pilot is valid, false otherwise")
{
	const char* callsign;
	if (!ade_get_args(L, "s", &callsign)) {
		return ADE_RETURN_FALSE;
	}

	return ade_set_args(L, "b", valid_pilot(callsign, true));
}

ADE_FUNC(selectPilot, l_UserInterface_PilotSelect, "string callsign, boolean is_multi",
         "Selects the pilot with the specified callsign and advances the game to the main menu.", nullptr, "nothing")
{
	const char* callsign;
	bool is_multi;
	if (!ade_get_args(L, "sb", &callsign, &is_multi)) {
		return ADE_RETURN_NIL;
	}

	player_finish_select(callsign, is_multi);

	return ADE_RETURN_NIL;
}

ADE_FUNC(deletePilot, l_UserInterface_PilotSelect, "string callsign",
         "Deletes the pilot with the specified callsign. This is not reversible!", "boolean",
         "true on success, false otherwise")
{
	const char* callsign;
	if (!ade_get_args(L, "s", &callsign)) {
		return ADE_RETURN_NIL;
	}

	return ade_set_args(L, "b", delete_pilot_file(callsign));
}

ADE_FUNC(
    createPilot, l_UserInterface_PilotSelect, "string callsign, boolean is_multi, [string copy_from]",
    "Creates a new pilot in either single or multiplayer mode and optionally copies settings from an existing pilot.",
    "boolean", "true on success, false otherwise")
{
	const char* callsign;
	bool is_multi;
	const char* copy_from = nullptr;
	if (!ade_get_args(L, "sb|s", &callsign, &is_multi, &copy_from)) {
		return ADE_RETURN_NIL;
	}

	return ade_set_args(L, "b", player_create_new_pilot(callsign, is_multi, copy_from));
}

ADE_FUNC(unloadPilot,
	l_UserInterface_PilotSelect,
	nullptr,
	"Unloads a player file & associated campaign file. Can not be used outside of pilot select!",
	"boolean",
	"Returns true if successful, false otherwise")
{
	if (gameseq_get_state() == GS_STATE_INITIAL_PLAYER_SELECT) {
		Player = nullptr;
		Campaign.filename[0] = '\0';

		return ADE_RETURN_TRUE;
	}

	return ADE_RETURN_FALSE;
}

ADE_FUNC(isAutoselect, l_UserInterface_PilotSelect, nullptr,
         "Determines if the pilot selection screen should automatically select the default user.", "boolean",
         "true if autoselect is enabled, false otherwise")
{
	return ade_set_args(L, "b", Cmdline_benchmark_mode || Cmdline_pilot);
}

ADE_VIRTVAR(CmdlinePilot, l_UserInterface_PilotSelect, nullptr,
			"The pilot chosen from commandline, if any.", "string",
			"The name if specified, nil otherwise")
{
	if (Cmdline_pilot)
		return ade_set_args(L, "s", Cmdline_pilot);
	else
		return ADE_RETURN_NIL;
}

//**********SUBLIBRARY: UserInterface/MainHall
ADE_LIB_DERIV(l_UserInterface_MainHall, "MainHall", nullptr,
              "API for accessing values specific to the Main Hall UI.",
              l_UserInterface);

ADE_FUNC(startAmbientSound, l_UserInterface_MainHall, nullptr, "Starts the ambient mainhall sound.", nullptr, "nothing")
{
	SCP_UNUSED(L);
	main_hall_start_ambient();
	return ADE_RETURN_NIL;
}

ADE_FUNC(stopAmbientSound, l_UserInterface_MainHall, nullptr, "Stops the ambient mainhall sound.", nullptr, "nothing")
{
	SCP_UNUSED(L);
	main_hall_stop_ambient();
	return ADE_RETURN_NIL;
}

ADE_FUNC(startMusic, l_UserInterface_MainHall, nullptr, "Starts the mainhall music.", nullptr, "nothing")
{
	SCP_UNUSED(L);
	main_hall_start_music();
	return ADE_RETURN_NIL;
}

ADE_FUNC(toggleHelp,
	l_UserInterface_MainHall,
	"boolean",
	"Sets the mainhall F1 help overlay to display. True to display, false to hide",
	nullptr,
	"nothing")
{
	bool toggle;
	if (!ade_get_args(L, "b", &toggle))
		return ADE_RETURN_NIL;

	main_hall_toggle_help(toggle);


	return ADE_RETURN_NIL;
}

//**********SUBLIBRARY: UserInterface/Barracks
ADE_LIB_DERIV(l_UserInterface_Barracks, "Barracks", nullptr,
              "API for accessing values specific to the Barracks UI.",
              l_UserInterface);

ADE_FUNC(listPilotImages, l_UserInterface_Barracks, nullptr, "Lists the names of the available pilot images.",
         "string[]", "The list of pilot filenames or nil on error")
{
	pilot_load_pic_list();

	using namespace luacpp;

	LuaTable out = LuaTable::create(L);
	for (auto i = 0; i < Num_pilot_images; ++i) {
		out.addValue(i + 1, Pilot_image_names[i]);
	}
	return ade_set_args(L, "t", &out);
}

ADE_FUNC(listSquadImages, l_UserInterface_Barracks, nullptr, "Lists the names of the available squad images.",
         "string[]", "The list of squad filenames or nil on error")
{
	pilot_load_squad_pic_list();

	using namespace luacpp;

	LuaTable out = LuaTable::create(L);
	for (auto i = 0; i < Num_pilot_squad_images; ++i) {
		out.addValue(i + 1, Pilot_squad_image_names[i]);
	}
	return ade_set_args(L, "t", &out);
}

ADE_FUNC(acceptPilot, l_UserInterface_Barracks, "player selection", "Accept the given player as the current player",
         "boolean", "true on success, false otherwise")
{
	player_h* plh;
	if (!ade_get_args(L, "o", l_Player.GetPtr(&plh))) {
		return ADE_RETURN_FALSE;
	}

	barracks_accept_pilot(plh->get());
	return ADE_RETURN_TRUE;
}

//**********SUBLIBRARY: UserInterface/OptionsMenu
// This needs a slightly different name since there is already a type called "Options"
ADE_LIB_DERIV(l_UserInterface_Options,
	"OptionsMenu",
	nullptr,
	"API for accessing values specific to the Options UI.",
	l_UserInterface);

ADE_FUNC(playVoiceClip,
	l_UserInterface_Options,
	nullptr,
	"Plays the example voice clip used for checking the voice volume",
	"boolean",
	"true on success, false otherwise")
{
	options_play_voice_clip();
	return ADE_RETURN_TRUE;
}

ADE_FUNC(savePlayerData,
	l_UserInterface_Options,
	nullptr,
	"Saves all player data. This includes the player file and campaign file.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	Pilot.save_player();
	Pilot.save_savefile();

	return ADE_RETURN_NIL;
}

//**********SUBLIBRARY: UserInterface/CampaignMenu
ADE_LIB_DERIV(l_UserInterface_Campaign,
	"CampaignMenu",
	nullptr,
	"API for accessing data related to the Campaign UI.",
	l_UserInterface);

ADE_FUNC(loadCampaignList,
	l_UserInterface_Campaign,
	nullptr,
	"Loads the list of available campaigns",
	"boolean",
	// ade_type_info({ade_type_array("string"), ade_type_array("string")}),
	"false if something failed while loading the list, true otherwise")
{
	return ade_set_args(L, "b", !campaign_build_campaign_list());
}

ADE_FUNC(getCampaignList,
	l_UserInterface_Campaign,
	nullptr,
	"Get the campaign name and description lists",
	"string[], string[], string[]",
	"Three tables with the names, file names, and descriptions of the campaigns")
{
	luacpp::LuaTable nameTable        = luacpp::LuaTable::create(L);
	luacpp::LuaTable fileNameTable    = luacpp::LuaTable::create(L);
	luacpp::LuaTable descriptionTable = luacpp::LuaTable::create(L);

	for (int i = 0; i < Num_campaigns; ++i) {
		nameTable.addValue(i + 1, Campaign_names[i]);
		fileNameTable.addValue(i + 1, Campaign_file_names[i]);

		auto description = Campaign_descs[i];
		descriptionTable.addValue(i + 1, description ? description : "");
	}

	// We actually do not need this anymore now so free it immediately
	mission_campaign_free_list();

	return ade_set_args(L, "ttt", nameTable, fileNameTable, descriptionTable);
}

ADE_FUNC(selectCampaign,
	l_UserInterface_Campaign,
	"string campaign_file",
	"Selects the specified campaign file name",
	"boolean",
	"true if successful, false otherwise")
{
	const char* filename = nullptr;
	if (!ade_get_args(L, "s", &filename)) {
		return ADE_RETURN_FALSE;
	}

	campaign_select_campaign(filename);
	Pilot.save_player();

	return ADE_RETURN_TRUE;
}

ADE_FUNC(resetCampaign,
	l_UserInterface_Campaign,
	"string campaign_file",
	"Resets the campaign with the specified file name",
	"boolean",
	"true if successful, false otherwise")
{
	const char* filename = nullptr;
	if (!ade_get_args(L, "s", &filename)) {
		return ADE_RETURN_FALSE;
	}

	campaign_reset(filename);

	return ADE_RETURN_TRUE;
}

//**********SUBLIBRARY: UserInterface/Briefing
ADE_LIB_DERIV(l_UserInterface_Brief,
	"Briefing",
	nullptr,
	"API for accessing data related to the Briefing UI.",
	l_UserInterface);

ADE_FUNC(getBriefingMusicName,
	l_UserInterface_Brief,
	nullptr,
	"Gets the file name of the music file to play for the briefing.",
	"string",
	"The file name or empty if no music")
{
	return ade_set_args(L, "s", common_music_get_filename(SCORE_BRIEFING));
}

ADE_FUNC(runBriefingStageHook,
	l_UserInterface_Brief,
	"number oldStage, number newStage",
	"Run $On Briefing Stage: hooks.",
	nullptr,
	nullptr)
{
	int oldStage = -1, newStage = -1;
	if (ade_get_args(L, "ii", &oldStage, &newStage) == 2) {
		// Subtract 1 to convert from Lua conventions to C conventions
		common_fire_stage_script_hook(oldStage - 1, newStage - 1);
	} else {
		LuaError(L, "Bad arguments given to ui.runBriefingStageHook!");
	}
	return ADE_RETURN_NIL;
}

ADE_FUNC(initBriefing,
	l_UserInterface_Brief,
	nullptr,
	"Initializes the briefing and prepares the map for drawing.  Also handles various non-UI housekeeping tasks "
	"and compacts the stages to remove those that should not be shown.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	brief_api_init();

	return ADE_RETURN_NIL;
}

ADE_FUNC(closeBriefing,
	l_UserInterface_Brief,
	nullptr,
	"Closes the briefing and pauses the map. Required after using the briefing API!",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);
	brief_api_close();
	return ADE_RETURN_NIL;
}

ADE_FUNC(getBriefing,
	l_UserInterface_Brief,
	nullptr,
	"Get the briefing",
	"briefing",
	"The briefing data")
{
	// get a pointer to the appropriate briefing structure
	if (MULTI_TEAM) {
		return ade_set_args(L, "o", l_Brief.Set(Net_player->p_info.team));
	} else {
		return ade_set_args(L, "o", l_Brief.Set(0));
	}

}

ADE_FUNC(exitLoop,
	l_UserInterface_Brief,
	nullptr,
	"Skips the current mission, exits the campaign loop, and loads the next non-loop mission in a campaign. Returns to the main hall if the player is not in a campaign.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	if (!(Game_mode & GM_CAMPAIGN_MODE)) {
		gameseq_post_event(GS_EVENT_MAIN_MENU);
	}

	mission_campaign_exit_loop();

	return ADE_RETURN_NIL;
}

ADE_FUNC(skipMission,
	l_UserInterface_Brief,
	nullptr,
	"Skips the current mission, and loads the next mission in a campaign. Returns to the main hall if the player is not in a campaign.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	if (!(Game_mode & GM_CAMPAIGN_MODE)) {
		gameseq_post_event(GS_EVENT_MAIN_MENU);
	}

	mission_campaign_skip_to_next();

	return ADE_RETURN_NIL;
}

ADE_FUNC(skipTraining,
	l_UserInterface_Brief,
	nullptr,
	"Skips the current training mission, and loads the next mission in a campaign. Returns to the main hall if the player is not in a campaign.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	if (!(Game_mode & GM_CAMPAIGN_MODE)) {
		gameseq_post_event(GS_EVENT_MAIN_MENU);
	}

	// tricky part.  Need to move to the next mission in the campaign.
	mission_goal_mark_objectives_complete();
	mission_goal_fail_incomplete();
	mission_campaign_store_goals_and_events_and_variables();

	mission_campaign_eval_next_mission();
	mission_campaign_mission_over();

	if (Campaign.next_mission == -1 || (The_mission.flags[Mission::Mission_Flags::End_to_mainhall])) {
		gameseq_post_event(GS_EVENT_MAIN_MENU);
	} else {
		gameseq_post_event(GS_EVENT_START_GAME);
	}

	return ADE_RETURN_NIL;
}

ADE_FUNC(commitToMission,
	l_UserInterface_Brief,
	nullptr,
	"Commits to the current mission with current loadout data, and starts the mission. Returns an integer to represent "
	"built-in errors or 0 if successful. 1 = general error, 2 = a player ship has no weapons, 3 = the required weapon was not found "
	"loaded on a ship, 4 = 2 or more required weapons were not found loaded on a ship, 5 = a gap in a ship's weapon banks was discovered "
	"and all empty banks must be at the bottom of the list, 6 = a player has no ship selected",
	"number error",
	"the error value")
{
	return ade_set_args(L, "i", static_cast<int>(commit_pressed(true)));
}

ADE_FUNC(renderBriefingModel,
	l_UserInterface_Brief,
	"string PofName, number CloseupZoom, vector CloseupPos, number X1, number Y1, number X2, number Y2, [number RotationPercent =0, number PitchPercent =0, "
	"number "
	"BankPercent=40, number Zoom=1.3, boolean Lighting=true, boolean Jumpnode=false]",
	"Draws a pof. True for regular lighting, false for flat lighting.",
	"boolean",
	"Whether pof was rendered")
{
	int x1, y1, x2, y2;
	angles rot_angles = {0.0f, 0.0f, 40.0f};
	const char* pof;
	float closeup_zoom;
	vec3d closeup_pos;
	float zoom = 1.3f;
	bool lighting = true;
	bool jumpNode = false;
	if (!ade_get_args(L,
			"sfoiiii|ffffbb",
			&pof,
			&closeup_zoom,
			l_Vector.Get(&closeup_pos),
			&x1,
			&y1,
			&x2,
			&y2,
			&rot_angles.h,
			&rot_angles.p,
			&rot_angles.b,
			&zoom,
			&lighting,
			&jumpNode))
		return ade_set_error(L, "b", false);

	if (x2 < x1 || y2 < y1)
		return ade_set_args(L, "b", false);

	CLAMP(rot_angles.p, 0.0f, 100.0f);
	CLAMP(rot_angles.b, 0.0f, 100.0f);
	CLAMP(rot_angles.h, 0.0f, 100.0f);

	// Handle angles
	matrix orient = vmd_identity_matrix;
	angles view_angles = {-0.6f, 0.0f, 0.0f};
	vm_angles_2_matrix(&orient, &view_angles);

	rot_angles.p = (rot_angles.p * 0.01f) * PI2;
	rot_angles.b = (rot_angles.b * 0.01f) * PI2;
	rot_angles.h = (rot_angles.h * 0.01f) * PI2;
	vm_rotate_matrix_by_angles(&orient, &rot_angles);

	tech_render_type thisType = TECH_POF;

	if (jumpNode) {
		thisType = TECH_JUMP_NODE;
	}

	return ade_set_args(L, "b", render_tech_model(thisType, x1, y1, x2, y2, zoom, lighting, -1, &orient, pof, closeup_zoom, &closeup_pos));
}

ADE_FUNC(drawBriefingMap,
	l_UserInterface_Brief,
	"number x, number y, [number width = 888, number height = 371]",
	"Draws the briefing map for the current mission at the specified coordinates. Note that the "
	"width and height must be a specific aspect ratio to match retail. If changed then some icons "
	"may be clipped from view unexpectedly. Must be called On Frame.",
	nullptr,
	nullptr)
{

	int x1;
	int y1;
	int x2 = 888;
	int y2 = 371;

	if (!ade_get_args(L, "ii|ii", &x1, &y1, &x2, &y2)) {
		LuaError(L, "X and Y coordinates not provided!");
		return ADE_RETURN_NIL;
	}

	// Saving retail coords here for posterity
	//  GR_640 - 19, 147, 555, 232
	//  GR_1024 - 30, 235, 888, 371

	bscreen.map_x1 = x1;
	bscreen.map_x2 = x1 + x2;
	bscreen.map_y1 = y1;
	bscreen.map_y2 = y1 + y2;
	bscreen.resize = GR_RESIZE_NONE;

	brief_api_do_frame(flRealframetime);

	return ADE_RETURN_NIL;
}

ADE_FUNC(checkStageIcons,
	l_UserInterface_Brief,
	"number xPos, number yPos",
	"Sends the mouse position to the brief map rendering functions to properly highlight icons.",
	"string, number, vector, string, number",
	"If an icon is highlighted then this will return the ship name for ships or the pof to render for asteroid, jumpnode, or unknown icons. "
	"also returns the closeup zoom, the closeup position, the closeup label, and the icon id. Otherwise it returns nil")
{
	int x;
	int y;

	if (!ade_get_args(L, "ii", &x, &y)) {
		LuaError(L, "X and Y coordinates not provided!");
		return ADE_RETURN_NIL;
	}

	brief_check_for_anim(true, x, y);

	if (Closeup_icon == nullptr) {
		return ADE_RETURN_NIL;
	} else {
		return ade_set_args(L, "sfosi", Closeup_type_name, Closeup_zoom, l_Vector.Set(Closeup_cam_pos), Closeup_icon->closeup_label, Closeup_icon->id);
	}
}

ADE_FUNC(callNextMapStage,
	l_UserInterface_Brief,
	nullptr,
	"Sends the briefing map to the next stage.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);
	brief_do_next_pressed(0);
	return ADE_RETURN_NIL;
}

ADE_FUNC(callPrevMapStage,
	l_UserInterface_Brief,
	nullptr,
	"Sends the briefing map to the previous stage.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);
	brief_do_prev_pressed();
	return ADE_RETURN_NIL;
}

ADE_FUNC(callFirstMapStage,
	l_UserInterface_Brief,
	nullptr,
	"Sends the briefing map to the first stage.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);
	brief_do_start_pressed();
	return ADE_RETURN_NIL;
}

ADE_FUNC(callLastMapStage,
	l_UserInterface_Brief,
	nullptr,
	"Sends the briefing map to the last stage.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);
	brief_do_end_pressed();
	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_Briefing_Goals, "Objectives", nullptr, nullptr, l_UserInterface_Brief);
ADE_INDEXER(l_Briefing_Goals,
	"number Index",
	"Array of goals",
	"mission_goal",
	"goal handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "s", "");

	// convert from lua index
	idx--;

	if ((idx < 0) || idx >= (int)Mission_goals.size())
		return ade_set_args(L, "o", l_Goals.Set(-1));

	return ade_set_args(L, "o", l_Goals.Set(idx));
}

ADE_FUNC(__len, l_Briefing_Goals, nullptr, "The number of goals in the mission", "number", "The number of goals.")
{
	return ade_set_args(L, "i", (int)Mission_goals.size());
}

//**********SUBLIBRARY: UserInterface/CommandBriefing
ADE_LIB_DERIV(l_UserInterface_CmdBrief,
	"CommandBriefing",
	nullptr,
	"API for accessing data related to the Command Briefing UI.",
	l_UserInterface);

ADE_FUNC(getCmdBriefing,
	l_UserInterface_CmdBrief,
	nullptr,
	"Get the command briefing.",
	"cmd_briefing",
	"The briefing data")
{
	// The cmd briefing code has support for specifying the team but only sets the index to 0
	return ade_set_args(L, "o", l_CmdBrief.Set(0));
}

//**********SUBLIBRARY: UserInterface/Debriefing
ADE_LIB_DERIV(l_UserInterface_Debrief,
	"Debriefing",
	nullptr,
	"API for accessing data related to the Debriefing UI.",
	l_UserInterface);

ADE_FUNC(initDebriefing,
	l_UserInterface_Debrief,
	nullptr,
	"Builds the debriefing, the stats, sets the next campaign mission, and makes all relevant data accessible",
	"number",
	"Returns true when completed")
{
	
	// stop all looping mission sounds
	game_stop_looped_sounds();

	 // fail all incomplete goals before entering debriefing
	mission_goal_fail_incomplete();
	hud_config_as_player();
	debrief_init(true);
	
	return ade_set_args(L, "b", true);
}

ADE_FUNC(getDebriefingMusicName,
	l_UserInterface_Debrief,
	nullptr,
	"Gets the file name of the music file to play for the debriefing.",
	"string",
	"The file name or empty if no music")
{
	return ade_set_args(L, "s", common_music_get_filename(debrief_select_music()));
}

ADE_FUNC(getDebriefing, l_UserInterface_Debrief, nullptr, "Get the debriefing", "debriefing", "The debriefing data")
{
	// get a pointer to the appropriate debriefing structure
	if (MULTI_TEAM) {
		return ade_set_args(L, "o", l_Debrief.Set(Net_player->p_info.team));
	} else {
		return ade_set_args(L, "o", l_Debrief.Set(0));
	}
}

ADE_FUNC(getEarnedMedal,
	l_UserInterface_Debrief,
	nullptr,
	"Get the earned medal name and bitmap",
	"string, string",
	"The name and bitmap or NIL if not earned")
{
	char filename[80];
	SCP_string displayname;

	if (Player->stats.m_medal_earned != -1) {
		debrief_choose_medal_variant(filename,
			Player->stats.m_medal_earned,
			Player->stats.medal_counts[Player->stats.m_medal_earned] - 1);
		displayname = Medals[Player->stats.m_medal_earned].get_display_name();

		return ade_set_args(L, "ss", displayname, filename);
	} else {
		return ADE_RETURN_NIL;
	}
}

ADE_FUNC(getEarnedPromotion,
	l_UserInterface_Debrief,
	nullptr,
	"Get the earned promotion stage, name, and bitmap",
	"debriefing_stage, string, string",
	"The promotion stage, name and bitmap or NIL if not earned")
{
	char filename[80];
	SCP_string displayname;

	if (Player->stats.m_promotion_earned != -1) {
		Promoted = Player->stats.m_promotion_earned;
		debrief_choose_medal_variant(filename, Rank_medal_index, Promoted);
		displayname = get_rank_display_name(&Ranks[Promoted]).c_str();

		return ade_set_args(L, "oss", l_DebriefStage.Set(debrief_stage_h(&Promotion_stage)), displayname, filename);
	} else {
		return ADE_RETURN_NIL;
	}
}

ADE_FUNC(getEarnedBadge,
	l_UserInterface_Debrief,
	nullptr,
	"Get the earned badge stage, name, and bitmap",
	"debriefing_stage, string, string",
	"The badge stage, name and bitmap or NIL if not earned")
{
	char filename[80];
	SCP_string displayname;

	if (Player->stats.m_badge_earned.size()) {
		debrief_choose_medal_variant(filename,
			Player->stats.m_badge_earned.back(),
			Player->stats.medal_counts[Player->stats.m_badge_earned.back()] - 1);
		displayname = Medals[Player->stats.m_badge_earned.back()].get_display_name();

		return ade_set_args(L, "oss", l_DebriefStage.Set(debrief_stage_h(&Badge_stage)), displayname, filename);
	} else {
		return ADE_RETURN_NIL;
	}
}

ADE_FUNC(clearMissionStats,
	l_UserInterface_Debrief,
	nullptr,
	"Clears out the player's mission stats.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L); // unused parameter
	Player->flags &= ~PLAYER_FLAGS_PROMOTED;
	scoring_level_init(&Player->stats);
	return ADE_RETURN_NIL;
}

ADE_FUNC(getTraitor,
	l_UserInterface_Debrief,
	nullptr,
	"Get the traitor stage",
	"debriefing_stage",
	"The traitor stage or nil if the player is not traitor. Should be coupled with clearMissionStats if true")
{
	if (Turned_traitor) {
		return ade_set_args(L, "o", l_DebriefStage.Set(debrief_stage_h(&Traitor_debriefing.stages[0])));
	} else {
		return ADE_RETURN_NIL;
	}
}

ADE_FUNC(mustReplay,
	l_UserInterface_Debrief,
	nullptr,
	"Gets whether or not the player must replay the mission. Should be coupled with clearMissionStats if true",
	"boolean",
	"true if must replay, false otherwise")
{

	if (Must_replay_mission) {
		return ade_set_args(L, "b", true);
	} else {
		return ade_set_args(L, "b", false);
	}
}

ADE_FUNC(canSkip,
	l_UserInterface_Debrief,
	nullptr,
	"Gets whether or not the player has failed enough times to trigger a skip dialog",
	"boolean",
	"true if can skip, false otherwise")
{

	if (Player->failures_this_session >= PLAYER_MISSION_FAILURE_LIMIT) {
		return ade_set_args(L, "b", true);
	} else {
		return ade_set_args(L, "b", false);
	}
}

ADE_FUNC(replayMission,
	l_UserInterface_Debrief,
	"[boolean restart = true]",
	"Resets the mission outcome, and optionally restarts the mission at the briefing; "
	"true to restart the mission, false to stay at current UI. Defaults to true.",
	nullptr,
	nullptr)
{

	bool restart = true;

	ade_get_args(L, "|b", &restart);

	debrief_close(true);

	if (restart) {
		gameseq_post_event(GS_EVENT_START_GAME);
	}

	return ADE_RETURN_NIL;
}

ADE_FUNC(acceptMission,
	l_UserInterface_Debrief,
	"[boolean start = true]",
	"Accepts the mission outcome, saves the stats, and optionally begins the next mission if in campaign; "
	"true to start the next mission, false to stay at current UI. Defaults to true.",
	nullptr,
	nullptr)
{
	bool start = true;

	ade_get_args(L, "|b", &start);

	if (start) {
		debrief_accept(1, true);
	} else {
		debrief_accept(0, true);
	};

	debrief_close(true);

	return ADE_RETURN_NIL;
}

//**********SUBLIBRARY: UserInterface/LoopBrief
ADE_LIB_DERIV(l_UserInterface_LoopBrief,
	"LoopBrief",
	nullptr,
	"API for accessing data related to the Loop Brief UI.",
	l_UserInterface);

ADE_FUNC(getLoopBrief,
	l_UserInterface_LoopBrief,
	nullptr,
	"Get the loop brief.",
	"loop_brief_stage",
	"The loop brief data")
{
	return ade_set_args(L, "o", l_LoopBriefStage.Set(cmission_h(Campaign.current_mission)));
}

ADE_FUNC(setLoopChoice, l_UserInterface_LoopBrief, "boolean", "Accepts mission outcome and then True to go to loop, False to skip", nullptr, nullptr)
{
	bool choice = false;
	ade_get_args(L, "|b", &choice);

	if (choice) {
		// select the loop mission
		Campaign.loop_enabled = 1;
		Campaign.loop_reentry = Campaign.next_mission; // save reentry pt, so we can break out of loop
		Campaign.next_mission = Campaign.loop_mission;

		mission_campaign_mission_over();
	} else {
		mission_campaign_mission_over();
	}

	return ADE_RETURN_NIL;
}

//**********SUBLIBRARY: UserInterface/RedAlert
ADE_LIB_DERIV(l_UserInterface_RedAlert,
	"RedAlert",
	nullptr,
	"API for accessing data related to the Red Alert UI.",
	l_UserInterface);

 ADE_FUNC(getRedAlert,
	l_UserInterface_RedAlert,
	nullptr,
	"Get the red alert brief.",
	"red_alert_stage",
	"The red-alert data")
{
	 if (Briefings[0].num_stages) {
		return ade_set_args(L, "o", l_RedAlertStage.Set(redalert_stage_h(0,0)));
	 } else {
		 return ADE_RETURN_NIL;
	 }
}

ADE_FUNC(replayPreviousMission,
	l_UserInterface_RedAlert,
	nullptr,
	"Loads the previous mission of the campaign, does nothing if not in campaign",
	"boolean",
	"Returns true if the operation was successful, false otherwise")
{
	if (!mission_campaign_previous_mission()) {
		return ADE_RETURN_FALSE;
	} else {
		return ADE_RETURN_TRUE;
	}
}

//**********SUBLIBRARY: UserInterface/FictionViewer
ADE_LIB_DERIV(l_UserInterface_FictionViewer,
	"FictionViewer",
	nullptr,
	"API for accessing data related to the Fiction Viewer UI.",
	l_UserInterface);

ADE_FUNC(getFiction, l_UserInterface_FictionViewer, nullptr, "Get the fiction.", "fiction_viewer_stage", "The fiction data")
{
	if (Fiction_viewer_active_stage >= 0) {
		return ade_set_args(L, "o", l_FictionViewerStage.Set(fiction_viewer_stage_h(Fiction_viewer_active_stage)));
	} else {
		return ADE_RETURN_NIL;
	}
}

ADE_FUNC(getFictionMusicName, l_UserInterface_FictionViewer, nullptr,
	"Gets the file name of the music file to play for the fiction viewer.",
	"string",
	"The file name or empty if no music")
{
	return ade_set_args(L, "s", common_music_get_filename(SCORE_FICTION_VIEWER));
}

//**********SUBLIBRARY: UserInterface/ShipWepSelect
ADE_LIB_DERIV(l_UserInterface_ShipWepSelect,
	"ShipWepSelect",
	nullptr,
	"API for accessing data related to the Ship and Weapon Select UIs.",
	l_UserInterface);

ADE_FUNC(initSelect,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Initializes selection data including wing slots, ship and weapon pool, and loadout information. "
	"Must be called before every mission regardless if ship or weapon select is actually used! "
	"Should also be called on initialization of relevant briefing UIs such as briefing and red alert "
	"to ensure that the ships and weapons are properly set for the current mission.",
	nullptr,
	nullptr)
{
	//Note this does all the things from common_select_init() in missionscreencommon.cpp except load UI
	//elements into memory - Mjn
	
	SCP_UNUSED(L); // unused parameter

	Common_team = 0;

	if ((Game_mode & GM_MULTIPLAYER) && IS_MISSION_MULTI_TEAMS)
		Common_team = Net_player->p_info.team;

	common_set_team_pointers(Common_team);

	ship_select_common_init(true);
	weapon_select_common_init(true);

	if ( Game_mode & GM_MULTIPLAYER ) {
		multi_ts_common_init();
	}

	// restore loadout from Player_loadout if this is the same mission as the one previously played
	if ( !(Game_mode & GM_MULTIPLAYER) ) {
		if ( !stricmp(Player_loadout.filename, Game_current_mission_filename) ) {
			wss_maybe_restore_loadout();
			ss_synch_interface();
			wl_synch_interface();
		}
	}

	return ADE_RETURN_NIL;
}

ADE_FUNC(saveLoadout,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Saves the current loadout to the player file. Only should be used when a mission is loaded but has not been started.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L); // unused parameter

	// This could be requested before Common_team has been initialized, so let's check.
	// Freespace.cpp will clear Common_select_inited if the player ever leaves a valid
	// "briefing" game state, so this should be a pretty safe check to avoid the assert
	// contained within. - Mjn
	if (Common_select_inited) {
		wss_save_loadout();
	} else {
		return ADE_RETURN_NIL;
	}

	return ADE_RETURN_NIL;
}

ADE_FUNC(get3dShipChoices,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Gets the 3d select choices from game_settings.tbl relating to ships.",
	"boolean, number, boolean",
	"3d ship select choice(true for on, false for off), default ship select effect(0 = off, 1 = FS1, 2 = FS2), 3d ship "
	"icons choice(true for on, false for off)")
{

	return ade_set_args(L,
		"bib",
		Use_3d_ship_select,
		Default_ship_select_effect,
		Use_3d_ship_icons);
}

ADE_FUNC(get3dWeaponChoices,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Gets the 3d select choices from game_settings.tbl relating to weapons.",
	"boolean, number, boolean",
	"3d weapon select choice(true for on, false for off), default weapon select effect(0 = off, 1 = FS1, 2 = FS2), 3d weapon "
	"icons choice(true for on, false for off)")
{

	return ade_set_args(L,
		"bib",
		Use_3d_weapon_select,
		Default_weapon_select_effect,
		Use_3d_weapon_icons);
}

ADE_FUNC(get3dOverheadChoices,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Gets the 3d select choices from game_settings.tbl relating to weapon select overhead view.",
	"boolean, number",
	"3d overhead select choice(true for on, false for off), default overhead style(0 for top view, 1 for rotate)")
{

	return ade_set_args(L,
		"bi",
		Use_3d_overhead_ship,
		(int)Default_overhead_ship_style);
}

ADE_LIB_DERIV(l_Ship_Pool, "Ship_Pool", nullptr, nullptr, l_UserInterface_ShipWepSelect);
ADE_INDEXER(l_Ship_Pool,
	"number Index, number amount",
	"Array of ship amounts available in the pool for selection in the current mission. Index is index into Ship Classes.",
	"number",
	"Amount of the ship that's available")
{
	int idx;
	int amount;
	if (!ade_get_args(L, "*i|i", &idx, &amount))
		return ADE_RETURN_NIL;

	if (idx < 0 || idx > ship_info_size()) {
		return ADE_RETURN_NIL;
	};

	idx--; // Convert to Lua's 1 based index system

	if (ADE_SETTING_VAR) {
		if (amount < 0) {
			Ss_pool[idx] = 0;
		} else {
			Ss_pool[idx] = amount;
		}
	}

	return ade_set_args(L, "i", Ss_pool[idx]);
}

ADE_FUNC(__len, l_Ship_Pool, nullptr, "The number of ship classes in the pool", "number", "The number of ship classes.")
{
	return ade_set_args(L, "i", ship_info_size());
}

ADE_LIB_DERIV(l_Weapon_Pool, "Weapon_Pool", nullptr, nullptr, l_UserInterface_ShipWepSelect);
ADE_INDEXER(l_Weapon_Pool,
	"number Index, number amount",
	"Array of weapon amounts available in the pool for selection in the current mission. Index is index into Weapon Classes.",
	"number",
	"Amount of the weapon that's available")
{
	int idx;
	int amount;
	if (!ade_get_args(L, "*i|i", &idx, &amount))
		return ADE_RETURN_NIL;

	if (idx < 0 || idx > weapon_info_size()) {
		return ADE_RETURN_NIL;
	};

	idx--; // Convert to Lua's 1 based index system

	if (ADE_SETTING_VAR) {
		if (amount < 0) {
			Wl_pool[idx] = 0;
		} else {
			Wl_pool[idx] = amount;
		}
	}

	return ade_set_args(L, "i", Wl_pool[idx]);
}

ADE_FUNC(__len,
	l_Weapon_Pool, nullptr, "The number of weapon classes in the pool", "number", "The number of weapon classes.")
{
	return ade_set_args(L, "i", weapon_info_size());
}

ADE_FUNC(resetSelect,
	l_UserInterface_ShipWepSelect,
	nullptr,
	"Resets selection data to mission defaults including wing slots, ship and weapon pool, and loadout information",
	nullptr,
	nullptr)
{
	// Note this does all the things from ss_reset_to_default() in missionshipchoice.cpp except
	// resetting UI elements. It also resets the weapon pool. - Mjn

	SCP_UNUSED(L); // unused parameter

	//Reset ships pool
	ss_init_pool(&Team_data[Common_team]);
	ss_init_units();

	//Reset weapons pool
	wl_init_pool(&Team_data[Common_team]);

	if (!(Game_mode & GM_MULTIPLAYER)) {
		wl_fill_slots();
	}

	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_Loadout_Wings, "Loadout_Wings", nullptr, nullptr, l_UserInterface_ShipWepSelect);
ADE_INDEXER(l_Loadout_Wings,
	"number Index",
	"Array of loadout wing data",
	"loadout_wing",
	"loadout handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Loadout_Wing.Set(ss_wing_info_h()));
	idx--; //Convert to Lua's 1 based index system
	return ade_set_args(L, "o", l_Loadout_Wing.Set(ss_wing_info_h(idx)));
}

ADE_FUNC(__len, l_Loadout_Wings, nullptr, "The number of loadout wings", "number", "The number of loadout wings.")
{
	int count = 0;

	for (int i = 0; i < MAX_STARTING_WINGS; i++) {
		if (Ss_wings[i].ss_slots[0].in_mission)
			count++;
	};

	return ade_set_args(L, "i", count);
}

ADE_LIB_DERIV(l_Loadout_Ships, "Loadout_Ships", nullptr, nullptr, l_UserInterface_ShipWepSelect);
ADE_INDEXER(l_Loadout_Ships,
	"number Index",
	"Array of loadout ship data. Slots are 1-12 where 1-4 is wing 1, 5-8 is wing 2, 9-12 is wing 3. "
	"This is the array that is used to actually build the mission loadout on Commit.",
	"loadout_ship",
	"loadout handle, or nil if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ADE_RETURN_NIL;
	idx--; // Convert to Lua's 1 based index system
	return ade_set_args(L, "o", l_Loadout_Ship.Set(idx));
}

ADE_FUNC(__len, l_Loadout_Ships, nullptr, "The number of loadout ships", "number", "The number of loadout ships.")
{
	return ade_set_args(L, "i", MAX_WING_BLOCKS*MAX_WING_SLOTS);
}

//**********SUBLIBRARY: UserInterface/TechRoom
ADE_LIB_DERIV(l_UserInterface_TechRoom,
	"TechRoom",
	nullptr,
	"API for accessing data related to the Tech Room UIs.",
	l_UserInterface);

ADE_FUNC(buildMissionList,
	l_UserInterface_TechRoom,
	nullptr,
	"Builds the mission list for display. Must be called before the sim_mission handle will have data",
	"number",
	"Returns 1 when completed")
{
	Sim_Missions.clear();
	Sim_CMissions.clear();

	api_sim_room_build_mission_list(true);

	mprintf(("Building mission lists for scripting API is complete!\n"));

	return ade_set_args(L, "i", 1);
}

ADE_FUNC(buildCredits,
	l_UserInterface_TechRoom,
	nullptr,
	"Builds the credits for display. Must be called before the credits_info handle will have data",
	"number",
	"Returns 1 when completed")
{
	credits_parse(false);
	credits_scp_position();

	size_t count = Credit_text_parts.size();
	credits_complete.clear();

	for (size_t i = 0; i < count; i++) {
		credits_complete.append(Credit_text_parts[i]);
	}

	//Make sure we clean up after ourselves
	Credit_text_parts.clear();

	mprintf(("Building credits for scripting API is complete!\n"));

	return ade_set_args(L, "i", 1);
}

ADE_LIB_DERIV(l_UserInterface_SingleMissions, "SingleMissions", nullptr, nullptr, l_UserInterface_TechRoom);
ADE_INDEXER(l_UserInterface_SingleMissions, "number Index", "Array of simulator missions", "sim_mission", "Mission handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "s", "");
	
	return ade_set_args(L, "o", l_TechRoomMission.Set(sim_mission_h(idx, false)));
}

ADE_FUNC(__len, l_UserInterface_SingleMissions, nullptr, "The number of single missions", "number", "The number of single missions")
{
	return ade_set_args(L, "i", Sim_Missions.size());
}

ADE_LIB_DERIV(l_UserInterface_CampaignMissions, "CampaignMissions", nullptr, nullptr, l_UserInterface_TechRoom);
ADE_INDEXER(l_UserInterface_CampaignMissions, "number Index", "Array of campaign missions", "sim_mission", "Mission handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "s", "");
	
	return ade_set_args(L, "o", l_TechRoomMission.Set(sim_mission_h(idx, true)));
}

ADE_FUNC(__len, l_UserInterface_CampaignMissions, nullptr, "The number of campaign missions", "number", "The number of campaign missions")
{
	return ade_set_args(L, "i", Sim_CMissions.size());
}

ADE_LIB_DERIV(l_UserInterface_Cutscenes, "Cutscenes", nullptr, nullptr, l_UserInterface_TechRoom);
ADE_INDEXER(l_UserInterface_Cutscenes,
	"number Index",
	"Array of cutscenes",
	"cutscene_info",
	"Cutscene handle, or invalid handle if index is invalid")
{
	const char* name;
	if (!ade_get_args(L, "*s", &name))
		return ade_set_error(L, "o", l_TechRoomCutscene.Set(cutscene_info_h(-1)));

	int idx = get_cutscene_index_by_name(name);

	if (idx < 0) {
		try {
			idx = std::stoi(name);
			idx--; // Lua->FS2
		} catch (const std::exception&) {
			// Not a number
			return ade_set_error(L, "o", l_TechRoomCutscene.Set(cutscene_info_h(-1)));
		}

		if (!SCP_vector_inbounds(Cutscenes, idx)) {
			return ade_set_error(L, "o", l_TechRoomCutscene.Set(cutscene_info_h(-1)));
		}
	}

	return ade_set_args(L, "o", l_TechRoomCutscene.Set(cutscene_info_h(idx)));
}

ADE_FUNC(__len, l_UserInterface_Cutscenes, nullptr, "The number of cutscenes", "number", "The number of cutscenes")
{
	return ade_set_args(L, "i", Cutscenes.size());
}

ADE_LIB_DERIV(l_UserInterface_Credits, "Credits", nullptr, nullptr, l_UserInterface_TechRoom);
ADE_VIRTVAR(Music, l_UserInterface_Credits, nullptr, "The credits music filename", "string", "The music filename")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "s", credits_get_music_filename(Credits_music_name));
}

ADE_VIRTVAR(NumImages, l_UserInterface_Credits, nullptr, "The total number of credits images", "number", "The number of images")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "i", Credits_num_images);
}

ADE_VIRTVAR(StartIndex, l_UserInterface_Credits, nullptr, "The image index to begin with", "number", "The index")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	int retv = Credits_artwork_index;
	if (retv < 0) {
		retv = Random::next(Credits_num_images);
	}

	return ade_set_args(L, "i", retv);
}

ADE_VIRTVAR(DisplayTime, l_UserInterface_Credits, nullptr, "The display time for each image", "number", "The display time")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "f", Credits_artwork_display_time);
}

ADE_VIRTVAR(FadeTime, l_UserInterface_Credits, nullptr, "The crossfade time for each image", "number", "The fade time")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "f", Credits_artwork_fade_time);
}

ADE_VIRTVAR(ScrollRate, l_UserInterface_Credits, nullptr, "The scroll rate of the text", "number", "The scroll rate")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "f", Credits_scroll_rate);
}

ADE_VIRTVAR(Complete, l_UserInterface_Credits, nullptr, "The complete credits string", "string", "The credits")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "s", credits_complete);
}

//**********SUBLIBRARY: UserInterface/Medals
ADE_LIB_DERIV(l_UserInterface_Medals,
	"Medals",
	nullptr,
	"API for accessing data related to the Medals UI.",
	l_UserInterface);

ADE_LIB_DERIV(l_Medals, "Medals_List", nullptr, nullptr, l_UserInterface_Medals);
ADE_INDEXER(l_Medals,
	"number Index",
	"Array of Medals",
	"medal",
	"medal handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Medal.Set(medal_h()));
	idx--; // Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Medals.size()))
		return ade_set_error(L, "o", l_Medal.Set(medal_h()));

	return ade_set_args(L, "o", l_Medal.Set(medal_h(idx)));
}

ADE_FUNC(__len, l_Medals, nullptr, "The number of valid medals", "number", "The number of valid medals.")
{
	return ade_set_args(L, "i", Medals.size());
}

ADE_LIB_DERIV(l_Ranks, "Ranks_List", nullptr, nullptr, l_UserInterface_Medals);
ADE_INDEXER(l_Ranks, "number Index", "Array of Ranks", "rank", "rank handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Rank.Set(rank_h()));
	idx--; // Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Ranks.size()))
		return ade_set_error(L, "o", l_Rank.Set(rank_h()));

	return ade_set_args(L, "o", l_Rank.Set(rank_h(idx)));
}

ADE_FUNC(__len, l_Ranks, nullptr, "The number of valid ranks", "number", "The number of valid ranks.")
{
	return ade_set_args(L, "i", Ranks.size());
}

//**********SUBLIBRARY: UserInterface/Hotkeys
ADE_LIB_DERIV(l_UserInterface_Hotkeys,
	"MissionHotkeys",
	nullptr,
	"API for accessing data related to the Mission Hotkeys UI.",
	l_UserInterface);

ADE_FUNC(initHotkeysList,
	l_UserInterface_Hotkeys,
	nullptr,
	"Initializes the hotkeys list. Must be used before the hotkeys list is accessed.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	reset_hotkeys();
	hotkey_set_selected_line(1);
	hotkey_build_listing();

	// We want to allow the API to handle expanding wings on its own,
	// so lets expand every wing in the list and not try to handle it after that.
	for (int i = 0; i < MAX_LINES; i++) {
		auto item = Hotkey_lines[i];
		if (item.type == HotkeyLineType::WING) {
			expand_wing(i, true);
		}
	}

	// Reset the selected line back to 1
	hotkey_set_selected_line(1);

	return ADE_RETURN_NIL;
}

ADE_FUNC(resetHotkeys,
	l_UserInterface_Hotkeys,
	nullptr,
	"Resets the hotkeys list to previous setting, removing anything that wasn't saved. Returns nothing.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	reset_hotkeys();

	return ADE_RETURN_NIL;
}

ADE_FUNC(saveHotkeys,
	l_UserInterface_Hotkeys,
	nullptr,
	"Saves changes to the hotkey list. Returns nothing.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	save_hotkeys();

	return ADE_RETURN_NIL;
}

// This is not a retail UI feature, but it's just good design to allow it.
// This will allow SCPUI to create a restore to mission defaults button.
ADE_FUNC(resetHotkeysDefault,
	l_UserInterface_Hotkeys,
	nullptr,
	"Resets the hotkeys list to the default mission setting. Returns nothing.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	// argument to false, because if we're doing this we explicitely do not want
	// to restore player's saved values
	mission_hotkey_set_defaults(false);

	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_Hotkeys, "Hotkeys_List", nullptr, nullptr, l_UserInterface_Hotkeys);
ADE_INDEXER(l_Hotkeys,
	"number Index",
	"Array of Hotkey'd ships",
	"hotkey_ship",
	"hotkey ship handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Hotkey.Set(hotkey_h()));
	idx--; // Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= MAX_LINES))
		return ade_set_error(L, "o", l_Hotkey.Set(hotkey_h()));

	return ade_set_args(L, "o", l_Hotkey.Set(hotkey_h(idx)));
}

ADE_FUNC(__len, l_Hotkeys, nullptr, "The number of valid hotkey ships", "number", "The number of valid hotkey ships.")
{
	int s = 0;

	// this is dumb, but whatever
	for (int i = 0; i < MAX_LINES; i++) {
		auto item = Hotkey_lines[i];
		if (item.type == HotkeyLineType::NONE) {
			s = i;
			break;
		}
	}
	
	return ade_set_args(L, "i", s);
}

//**********SUBLIBRARY: UserInterface/GameHelp
ADE_LIB_DERIV(l_UserInterface_GameHelp,
	"GameHelp",
	nullptr,
	"API for accessing data related to the Game Help UI.",
	l_UserInterface);

ADE_FUNC(initGameHelp, l_UserInterface_GameHelp, nullptr, "Initializes the Game Help data. Must be used before Help Sections is accessed.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	Help_text.clear(); // Make sure the vector is empty before we start
	Help_text = gameplay_help_init_text();

	return ADE_RETURN_NIL;
}

ADE_FUNC(closeGameHelp, l_UserInterface_GameHelp, nullptr, "Clears the Game Help data. Should be used when finished accessing Help Sections.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	Help_text.clear();

	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_Help_Sections, "Help_Sections", nullptr, nullptr, l_UserInterface_GameHelp);
ADE_INDEXER(l_Help_Sections,
	"number Index",
	"Array of help sections",
	"help_section",
	"help section handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Help_Section.Set(help_section_h()));
	idx--; //Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Help_text.size()))
		return ade_set_error(L, "o", l_Help_Section.Set(help_section_h()));

	return ade_set_args(L, "o", l_Help_Section.Set(help_section_h(idx)));
}

ADE_FUNC(__len, l_Help_Sections, nullptr, "The number of help sections", "number", "The number of help sections.")
{
	return ade_set_args(L, "i", (int)Help_text.size());
}




//**********SUBLIBRARY: UserInterface/MissionLog
ADE_LIB_DERIV(l_UserInterface_MissionLog,
	"MissionLog",
	nullptr,
	"API for accessing data related to the Mission Log UI.",
	l_UserInterface);

ADE_FUNC(initMissionLog, l_UserInterface_MissionLog, nullptr, "Initializes the Mission Log data. Must be used before Mission Log is accessed.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	Log_scrollback_vec.clear(); // Make sure the vector is empty before we start

	//explicitely do not split lines!
	message_log_init_scrollback(0, false);

	return ADE_RETURN_NIL;
}

ADE_FUNC(closeMissionLog, l_UserInterface_MissionLog, nullptr, "Clears the Mission Log data. Should be used when finished accessing Mission Log Entries.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	message_log_shutdown_scrollback();

	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_Log_Entries, "Log_Entries", nullptr, nullptr, l_UserInterface_MissionLog);
ADE_INDEXER(l_Log_Entries,
	"number Index",
	"Array of mission log entries",
	"log_entry",
	"log entry handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Log_Entry.Set(log_entry_h()));
	idx--; //Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Log_scrollback_vec.size()))
		return ade_set_error(L, "o", l_Log_Entry.Set(log_entry_h()));

	return ade_set_args(L, "o", l_Log_Entry.Set(log_entry_h(idx)));
}

ADE_FUNC(__len, l_Log_Entries, nullptr, "The number of mission log entries", "number", "The number of log entries.")
{
	return ade_set_args(L, "i", (int)Log_scrollback_vec.size());
}

ADE_LIB_DERIV(l_Log_Messages, "Log_Messages", nullptr, nullptr, l_UserInterface_MissionLog);
ADE_INDEXER(l_Log_Messages,
	"number Index",
	"Array of message log entries",
	"message_entry",
	"message entry handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Message_Entry.Set(message_entry_h()));
	idx--; //Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Msg_scrollback_vec.size()))
		return ade_set_error(L, "o", l_Message_Entry.Set(message_entry_h()));

	return ade_set_args(L, "o", l_Message_Entry.Set(message_entry_h(idx)));
}

ADE_FUNC(__len, l_Log_Messages, nullptr, "The number of mission message entries", "number", "The number of message entries.")
{
	return ade_set_args(L, "i", (int)Msg_scrollback_vec.size());
}

//**********SUBLIBRARY: UserInterface/ControlConfig
ADE_LIB_DERIV(l_UserInterface_ControlConfig,
	"ControlConfig",
	nullptr,
	"API for accessing data related to the Control Config UI.",
	l_UserInterface);

ADE_FUNC(initControlConfig,
	l_UserInterface_ControlConfig,
	nullptr,
	"Inits the control config UI elements. Must be used before accessing control config elements!",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	control_config_init(true);
	
	return ADE_RETURN_NIL;
}

ADE_FUNC(closeControlConfig,
	l_UserInterface_ControlConfig,
	nullptr,
	"Closes the control config UI elements. Must be used when finished accessing control config elements!",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	control_config_close(true);

	return ADE_RETURN_NIL;
}

ADE_FUNC(clearAll,
	l_UserInterface_ControlConfig,
	nullptr,
	"Clears all control bindings.",
	"boolean",
	"Returns true if successful, false otherwise")
{
	SCP_UNUSED(L);

	return ade_set_args(L, "b", control_config_clear_all(true));
}

ADE_FUNC(resetToPreset,
	l_UserInterface_ControlConfig,
	nullptr,
	"Resets all control bindings to the current preset defaults.",
	"boolean",
	"Returns true if successful, false otherwise")
{
	SCP_UNUSED(L);

	return ade_set_args(L, "b", control_config_do_reset(false, true));
}

ADE_FUNC(usePreset,
	l_UserInterface_ControlConfig,
	"string PresetName",
	"Uses a defined preset if it can be found.",
	"boolean",
	"Returns true if successful, false otherwise")
{
	const char* preset = nullptr;
	if (!ade_get_args(L, "s", &preset)) {
		return ADE_RETURN_FALSE;
	}

	SCP_string name = preset;

	return ade_set_args(L, "b", control_config_use_preset_by_name(name));
}

ADE_FUNC(createPreset,
	l_UserInterface_ControlConfig,
	"string Name",
	"Creates a new preset with the given name. Returns true if successful, false otherwise.",
	"boolean",
	"The return status")
{
	const char* preset;
	ade_get_args(L, "s", &preset);

	SCP_string name = preset;

	return ade_set_args(L, "b", std::move(control_config_create_new_preset(name)));
}

ADE_FUNC(undoLastChange,
	l_UserInterface_ControlConfig,
	nullptr,
	"Reverts the last change to the control bindings",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	control_config_do_undo(true);

	return ADE_RETURN_NIL;
}

ADE_FUNC(searchBinds,
	l_UserInterface_ControlConfig,
	nullptr,
	"Waits for a keypress to search for. Returns index into Control Configs if the key matches a bind. Should run On Frame.",
	"number",
	"Control Config index, or 0 if no key was found. Returns -1 if Escape was pressed.")
{
	SCP_UNUSED(L);

	int idx = control_config_search_key_on_frame(true);
	idx++; //convert to lua

	return ade_set_args(L, "i", idx);
}

ADE_FUNC(acceptBinding,
	l_UserInterface_ControlConfig,
	nullptr,
	"Accepts changes to the keybindings. Returns true if successful, false if there are key conflicts or the preset needs to be saved.",
	"boolean",
	"The return status")
{
	SCP_UNUSED(L);

	return ade_set_args(L, "b", control_config_accept(true));
}

ADE_FUNC(cancelBinding,
	l_UserInterface_ControlConfig,
	nullptr,
	"Cancels changes to the keybindings, reverting changes to the state it was when initControlConfig was called.",
	nullptr,
	nullptr)
{
	SCP_UNUSED(L);

	control_config_cancel_exit(true);

	return ADE_RETURN_NIL;
}

ADE_FUNC(getCurrentPreset,
	l_UserInterface_ControlConfig,
	nullptr,
	"Returns the name of the current controls preset.",
	"string",
	"The name of the preset or nil if the current binds do not match a preset")
{
	SCP_UNUSED(L);

	auto it = control_config_get_current_preset();

	if (it == Control_config_presets.end()) {
		return ADE_RETURN_NIL;
	}

	return ade_set_args(L, "s", it->name.c_str());
}

ADE_LIB_DERIV(l_Presets, "ControlPresets", nullptr, nullptr, l_UserInterface_ControlConfig);
ADE_INDEXER(l_Presets,
	"number Index",
	"Array of control presets",
	"preset",
	"control preset handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Preset.Set(preset_h()));
	idx--; // Convert to Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Control_config.size()))
		return ade_set_error(L, "o", l_Preset.Set(preset_h()));

	return ade_set_args(L, "o", l_Preset.Set(preset_h(idx)));
}

ADE_FUNC(__len, l_Presets, nullptr, "The number of control presets", "number", "The number of control presets.")
{
	return ade_set_args(L, "i", (int)Control_config_presets.size());
}

ADE_LIB_DERIV(l_Controls, "ControlConfigs", nullptr, nullptr, l_UserInterface_ControlConfig);
ADE_INDEXER(l_Controls,
	"number Index",
	"Array of controls",
	"control",
	"control handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Control.Set(control_h()));
	idx--; // Convert from Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)Control_config.size()))
		return ade_set_error(L, "o", l_Control.Set(control_h()));

	return ade_set_args(L, "o", l_Control.Set(control_h(idx)));
}

ADE_FUNC(__len, l_Controls, nullptr, "The number of controls", "number", "The number of controls.")
{
	return ade_set_args(L, "i", (int)Control_config.size());
}

//**********SUBLIBRARY: UserInterface/HUDConfig
ADE_LIB_DERIV(l_UserInterface_HUDConfig,
	"HudConfig",
	nullptr,
	"API for accessing data related to the HUD Config UI.",
	l_UserInterface);

ADE_FUNC(initHudConfig,
	l_UserInterface_HUDConfig,
	"[number X, number Y, number Width]",
	"Initializes the HUD Configuration data. Must be used before HUD Configuration data accessed. "
	"X and Y are the coordinates where the HUD preview will be drawn when drawHudConfig is used. "
	"Width is the pixel width to draw the gauges preview.",
	nullptr,
	nullptr)
{
	int x = 0;
	int y = 0;
	int w = 0;
	ade_get_args(L, "|iii", &x, &y, &w);

	hud_config_init(true, x, y, w);

	return ADE_RETURN_NIL;
}

ADE_FUNC(closeHudConfig,
	l_UserInterface_HUDConfig,
	"boolean Save",
	"If True then saves the gauge configuration, discards if false. Defaults to false. Then cleans up memory. Should be used when finished accessing HUD Configuration.",
	nullptr,
	nullptr)
{
	bool save = false;
	ade_get_args(L, "|b", &save);

	if (save) {
		Pilot.save_savefile();
	} else {
		hud_config_cancel(false);
	}

	hud_config_close(true);

	return ADE_RETURN_NIL;
}

ADE_FUNC(drawHudConfig,
	l_UserInterface_HUDConfig,
	"[number MouseX, number MouseY]",
	"Draws the HUD for the HUD Config UI. Should be called On Frame.",
	"gauge_config",
	"Returns the gauge currently being hovered over, or empty handle if nothing is hovered")
{
	int mx = 0;
	int my = 0;
	ade_get_args(L, "|ii", &mx, &my);

	hud_config_do_frame(0.0f, true, mx, my);

	if (HC_gauge_hot >= 0) {
		return ade_set_args(L, "o", l_Gauge_Config.Set(gauge_config_h(HC_gauge_hot)));
	} else {
		return ade_set_error(L, "o", l_Gauge_Config.Set(gauge_config_h()));
	}
}

ADE_FUNC(selectAllGauges,
	l_UserInterface_HUDConfig,
	"boolean Toggle",
	"Sets all gauges as selected. True for select all, False to unselect all. Defaults to False.",
	nullptr,
	nullptr)
{
	bool toggle = false;
	ade_get_args(L, "|b", &toggle);

	hud_config_select_all_toggle(toggle, true);

	return ADE_RETURN_NIL;
}

ADE_FUNC(setToDefault,
	l_UserInterface_HUDConfig,
	"string Filename",
	"Sets all gauges to the defined default. If no filename is provided then 'hud_3.hcf' is used.",
	nullptr,
	nullptr)
{
	const char* filename = "hud_3.hcf";
	ade_get_args(L, "|s", &filename);

	hud_config_select_all_toggle(0, true);
	hud_set_default_hud_config(Player, filename);
	HUD_init_hud_color_array();

	return ADE_RETURN_NIL;
}

ADE_FUNC(saveToPreset,
	l_UserInterface_HUDConfig,
	"string Filename",
	"Saves all gauges to the file with the name provided. Filename should not include '.hcf' extension and not be longer than 28 characters.",
	nullptr,
	nullptr)
{
	const char* filename;
	ade_get_args(L, "s", &filename);

	SCP_string name = filename;

	// trim filename length to leave room for adding the extension
	if (name.size() > MAX_FILENAME_LEN - 4) {
		name.resize(MAX_FILENAME_LEN - 4);
	}

	// add extension
	name += ".hcf";

	hud_config_color_save(name.c_str());

	// reload the preset list for sorting
	hud_config_preset_init();

	return ADE_RETURN_NIL;
}

ADE_FUNC(usePresetFile,
	l_UserInterface_HUDConfig,
	"string Filename",
	"Sets all gauges to the provided preset file settings.",
	nullptr,
	nullptr)
{
	const char* filename;
	ade_get_args(L, "s", &filename);

	hud_config_color_load(filename);
	HUD_init_hud_color_array();

	return ADE_RETURN_NIL;
}

ADE_LIB_DERIV(l_HUD_Gauges, "GaugeConfigs", nullptr, nullptr, l_UserInterface_HUDConfig);
ADE_INDEXER(l_HUD_Gauges,
	"number Index",
	"Array of built-in gauge configs",
	"gauge_config",
	"gauge_config handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_Gauge_Config.Set(gauge_config_h()));
	idx--; // Convert from Lua's 1 based index system

	if ((idx < 0) || (idx >= NUM_HUD_GAUGES))
		return ade_set_error(L, "o", l_Gauge_Config.Set(gauge_config_h()));

	return ade_set_args(L, "o", l_Gauge_Config.Set(gauge_config_h(idx)));
}

ADE_FUNC(__len, l_HUD_Gauges, nullptr, "The number of gauge configs", "number", "The number of gauge configs.")
{
	return ade_set_args(L, "i", NUM_HUD_GAUGES);
}

ADE_LIB_DERIV(l_HUD_Presets, "GaugePresets", nullptr, nullptr, l_UserInterface_HUDConfig);
ADE_INDEXER(l_HUD_Presets,
	"number Index",
	"Array of HUD Preset files",
	"hud_preset",
	"hud_preset handle, or invalid handle if index is invalid")
{
	int idx;
	if (!ade_get_args(L, "*i", &idx))
		return ade_set_error(L, "o", l_HUD_Preset.Set(hud_preset_h()));
	idx--; // Convert from Lua's 1 based index system

	if ((idx < 0) || (idx >= (int)HC_preset_filenames.size()))
		return ade_set_error(L, "o", l_HUD_Preset.Set(hud_preset_h()));

	return ade_set_args(L, "o", l_HUD_Preset.Set(hud_preset_h(idx)));
}

ADE_FUNC(__len, l_HUD_Presets, nullptr, "The number of hud presets", "number", "The number of hud presets.")
{
	return ade_set_args(L, "i", HC_preset_filenames.size());
}

//**********SUBLIBRARY: UserInterface/PauseScreen
ADE_LIB_DERIV(l_UserInterface_PauseScreen,
	"PauseScreen",
	nullptr,
	"API for accessing data related to the Pause Screen UI.",
	l_UserInterface);

ADE_VIRTVAR(isPaused, l_UserInterface_PauseScreen, nullptr, "Returns true if the game is paused, false otherwise", "boolean", "true if paused, false if unpaused")
{
	if (ADE_SETTING_VAR) {
		LuaError(L, "This property is read only.");
	}

	return ade_set_args(L, "b", Paused);
}

ADE_FUNC(initPause, l_UserInterface_PauseScreen, nullptr, "Makes sure everything is done correctly to pause the game.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	weapon_pause_sounds();
	audiostream_pause_all();
	message_pause_all();

	Paused = true;

	return ADE_RETURN_NIL;
}

ADE_FUNC(closePause, l_UserInterface_PauseScreen, nullptr, "Makes sure everything is done correctly to unpause the game.", nullptr, nullptr)
{
	SCP_UNUSED(L);

	weapon_unpause_sounds();
	audiostream_unpause_all();
	message_resume_all();

	// FSO can run pause_init() before the actual games state change when the game loses focus
	// so this is required to make sure that the saved screen is cleared if SCPUI takes over
	// after the game state change
	gr_free_screen(Pause_saved_screen);
	Pause_saved_screen = -1;

	Paused = false;

	return ADE_RETURN_NIL;
}

} // namespace api
} // namespace scripting