forked from N00byKing/APCpp
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArchipelago.cpp
More file actions
1627 lines (1444 loc) · 62.7 KB
/
Archipelago.cpp
File metadata and controls
1627 lines (1444 loc) · 62.7 KB
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
#include "Archipelago.h"
#include "ixwebsocket/IXNetSystem.h"
#include "ixwebsocket/IXWebSocket.h"
#include "ixwebsocket/IXUserAgent.h"
#include "unzip.h"
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <json/json.h>
#include <json/reader.h>
#include <json/value.h>
#include <json/writer.h>
#include <deque>
#include <set>
#include <string>
#include <chrono>
#include <functional>
#include <utility>
#include <vector>
#include <filesystem>
#include <mutex>
constexpr int AP_OFFLINE_SLOT = 1;
#define AP_OFFLINE_NAME "You"
//Setup Stuff
// PRIV Func Declarations Start
void AP_Init_Generic(AP_State* state);
bool parse_response(AP_State* state, std::string msg, std::string &request);
void AP_GetServerData(AP_State* state, AP_GetServerDataRequest* request);
void APSend(AP_State* state, std::string req);
void WriteFileJSON(AP_State* state, Json::Value val, const std::filesystem::path& path);
std::string getItemName(AP_State* state, std::string game, int64_t id);
std::string getLocationName(AP_State* state, std::string game, int64_t id);
void parseDataPkg(AP_State* state, Json::Value new_datapkg);
void parseDataPkg(AP_State* state);
AP_NetworkPlayer* getPlayer(AP_State* state, int team, int slot);
// PRIV Func Declarations End
#define MAX_RETRIES 1
extern "C"
{
struct AP_State
{
bool init = false;
bool auth = false;
bool refused = false;
bool multiworld = true;
bool isSSL = true;
bool ssl_success = false;
bool connected = false;
bool skip_first_receive = false;
bool scouted = false;
bool notfound = false;
bool datapkg_received = false;
bool queue_all_locations;
bool scout_queued_locations;
bool scout_all_locations;
bool manage_memory = true;
int ping_interval = 5;
int scout_queued_locations_hint;
int scout_all_locations_hint;
int ap_team_id;
int ap_player_id;
std::string ap_player_name;
size_t ap_player_name_hash;
std::string ap_ip;
std::string ap_game;
std::string ap_passwd;
std::uint64_t ap_uuid = 0;
std::mt19937 rando;
AP_NetworkVersion client_version = {0,5,0};
// Deathlink Stuff
bool deathlinkstat = false;
bool deathlinksupported = false;
bool enable_deathlink = false;
int deathlink_amnesty = 0;
int cur_deathlink_amnesty = 0;
// Message System
std::deque<AP_Message*> messageQueue;
bool queueitemrecvmsg = true;
// Data Maps
std::map<int64_t, AP_NetworkPlayer> map_players;
std::map<std::pair<std::string,int64_t>, std::string> map_location_id_name;
std::map<std::pair<std::string,int64_t>, std::string> map_item_id_name;
std::map<int64_t, std::string> player_id_to_game_name;
std::map<int64_t, std::string> item_to_name;
std::map<int64_t, int64_t> location_to_item;
std::map<int64_t, bool> location_has_local_item;
std::map<int64_t, AP_ItemType> location_item_type;
std::map<int64_t, std::string> location_item_name;
std::map<int64_t, std::string> location_item_player;
std::map<int64_t, int64_t> location_item_player_id;
std::map<std::string, std::string> slot_data;
std::map<std::string, Json::Value> slot_data_raw;
// Sets
std::set<int64_t> all_items;
std::set<int64_t> all_locations;
std::set<int64_t> queued_scout_locations;
std::set<int64_t> removed_scout_locations;
std::set<int64_t> checked_locations;
std::set<int64_t> pending_locations;
// Vectors
std::vector<int64_t> received_items;
std::vector<int64_t> received_item_locations;
std::vector<int64_t> received_item_types;
std::vector<int64_t> sending_player_ids;
// Mutexes
std::mutex cache_mutex;
// Callback function pointers
void (*resetItemValues)();
void (*getitemfunc)(int64_t,int,bool);
void (*checklocfunc)(int64_t);
void (*locinfofunc)(std::vector<AP_NetworkItem>) = nullptr;
void (*recvdeath)() = nullptr;
void (*setreplyfunc)(AP_SetReply) = nullptr;
// Serverdata Management
std::map<std::string, AP_DataType> map_serverdata_typemanage;
std::map<std::string, AP_RequestStatus> map_serverdata_set_status;
AP_GetServerDataRequest resync_serverdata_request;
size_t last_item_idx = 0;
// Singleplayer Seed Info
std::filesystem::path sp_save_path;
Json::Value sp_save_root;
// Misc Data for Clients
AP_RoomInfo lib_room_info;
// Server Data Stuff
std::map<std::string, AP_GetServerDataRequest*> map_server_data;
// Slot Data Stuff
std::map<std::string, void (*)(int)> map_slotdata_callback_int;
std::map<std::string, void (*)(std::string)> map_slotdata_callback_raw;
std::map<std::string, void (*)(std::map<int,int>)> map_slotdata_callback_mapintint;
std::vector<std::string> slotdata_strings;
// Datapackage Stuff
std::filesystem::path datapkg_cache_path = "APCpp_datapkg.cache";
Json::Value datapkg_cache;
std::set<std::string> datapkg_outdated_games;
ix::WebSocket webSocket;
Json::Reader reader;
Json::FastWriter writer;
Json::Value sp_ap_root;
};
AP_State* AP_New() {
AP_State* state = new AP_State();
return state;
}
void AP_Free(AP_State* state) {
delete state;
}
void AP_SetPingInterval(AP_State* state, int interval) {
state->ping_interval = interval;
if (state->init) {
state->webSocket.setPingInterval(interval);
}
}
bool firstInit = false;
void AP_Init(AP_State* state, const char* ip, const char* game, const char* player_name, const char* passwd) {
state->multiworld = true;
state->notfound = false;
state->refused = false;
state->queue_all_locations = false;
state->scout_queued_locations = false;
state->scout_all_locations = false;
uint64_t milliseconds_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
state->rando = std::mt19937((uint32_t) milliseconds_since_epoch);
if (!strcmp(ip,"")) {
ip = "archipelago.gg:38281";
//printf("AP: Using default Server Adress: '%s'\n", ip);
} else {
//printf("AP: Using Server Adress: '%s'\n", ip);
}
state->ap_ip = ip;
state->ap_game = game;
state->ap_player_name = player_name;
state->ap_passwd = passwd;
//printf("AP: Initializing...\n");
//Connect to server
if (!firstInit) {
ix::initNetSystem();
firstInit = true;
}
state->webSocket.setUrl("wss://" + state->ap_ip);
state->webSocket.setOnMessageCallback([=](const ix::WebSocketMessagePtr& msg)
{
if (msg->errorInfo.retries >= MAX_RETRIES) {
if (/*msg->errorInfo.retries-1 >= 1 && */state->isSSL) {
//printf("AP: SSL connection failed. Attempting encrypted...\n");
state->webSocket.setUrl("ws://" + state->ap_ip);
state->isSSL = false;
} else if (msg->errorInfo.retries >= 2*MAX_RETRIES) {
state->notfound = true;
}
}
if (msg->type == ix::WebSocketMessageType::Message)
{
std::string request;
if (parse_response(state, msg->str, request)) {
APSend(state, request);
}
}
else if (msg->type == ix::WebSocketMessageType::Open)
{
//printf("AP: Connected to Archipelago\n");
}
else if (msg->type == ix::WebSocketMessageType::Error || msg->type == ix::WebSocketMessageType::Close)
{
state->datapkg_received = false;
state->auth = false;
state->skip_first_receive = true;
for (std::pair<std::string, AP_GetServerDataRequest*> itr : state->map_server_data) {
itr.second->status = AP_RequestStatus::Error;
state->map_server_data.erase(itr.first);
}
//printf("AP: Error connecting to Archipelago. Retries: %d\n", msg->errorInfo.retries-1);
}
}
);
state->webSocket.enablePerMessageDeflate();
state->webSocket.setPingInterval(state->ping_interval);
AP_NetworkPlayer archipelago {
-1,
0,
"Archipelago",
"Archipelago",
"__Server"
};
state->map_players[0] = archipelago;
AP_Init_Generic(state);
}
struct zip_mem_data {
std::vector<char> data;
size_t cur_offset;
};
zip_mem_data load_zip_file(const std::filesystem::path& path) {
zip_mem_data ret{};
std::ifstream stream{path, std::ios::binary};
stream.seekg(0, std::ios::end);
ret.data.resize(stream.tellg());
stream.seekg(0, std::ios::beg);
stream.read(ret.data.data(), ret.data.size());
return ret;
}
// Functions for reading an in-memory zip with minizip.
void fill_mem_filefunc(zlib_filefunc_def* pzlib_filefunc_def, zip_mem_data* data) {
pzlib_filefunc_def->zopen_file = [](voidpf opaque, const char* unused, int mode) {
(void) unused;
(void) mode;
zip_mem_data *mem = reinterpret_cast<zip_mem_data*>(opaque);
mem->cur_offset = 0;
return static_cast<void*>(mem);
};
pzlib_filefunc_def->zread_file = [](voidpf opaque, voidpf stream, void* buf, uLong size) {
(void) opaque;
zip_mem_data *mem = reinterpret_cast<zip_mem_data*>(stream);
if (size > mem->data.size() - mem->cur_offset) {
size = mem->data.size() - mem->cur_offset;
}
memcpy(buf, mem->data.data() + mem->cur_offset, size);
mem->cur_offset += size;
return size;
};
pzlib_filefunc_def->zwrite_file = [](voidpf, voidpf, const void*, uLong) {
// Writing not supported.
return uLong{0};
};
pzlib_filefunc_def->ztell_file = [](voidpf opaque, voidpf stream) {
(void) opaque;
zip_mem_data *mem = reinterpret_cast<zip_mem_data*>(stream);
return static_cast<long>(mem->cur_offset);
};
pzlib_filefunc_def->zseek_file = [](voidpf opaque, voidpf stream, uLong offset, int origin) {
(void) opaque;
zip_mem_data *mem = reinterpret_cast<zip_mem_data*>(stream);
uLong new_pos;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR:
new_pos = mem->cur_offset + offset;
break;
case ZLIB_FILEFUNC_SEEK_END:
new_pos = mem->data.size() + offset;
break;
case ZLIB_FILEFUNC_SEEK_SET:
new_pos = offset;
break;
default:
return -1L;
}
if (new_pos > mem->data.size()) {
return 1L; /* Failed to seek that far */
}
mem->cur_offset = new_pos;
return 0L;
};
pzlib_filefunc_def->zclose_file = [](voidpf, voidpf) {
// Nothing to do.
return 0;
};
pzlib_filefunc_def->zerror_file = [](voidpf, voidpf) {
// Nothing to do.
return 0;
};
pzlib_filefunc_def->opaque = static_cast<void*>(data);
}
bool load_solo_zip(AP_State* state, const std::filesystem::path& zip_path, const char* seed) {
// Read the zip into memory and pull the multidata json file from it.
zlib_filefunc_def zlib_funcs{};
zip_mem_data zip_data = load_zip_file(zip_path);
if (zip_data.data.size() == 0) {
// Failed to open
return false;
}
// printf("Found zip\n");
// Open the zip in miniunzip.
fill_mem_filefunc(&zlib_funcs, &zip_data);
unzFile gen_zip = unzOpen2(nullptr, &zlib_funcs);
// Look for the multidata file in the zip.
int result = unzLocateFile(gen_zip, ("AP_" + std::string{seed} + ".archipelago").c_str(), 0);
if (result != UNZ_OK) {
// Failed to find save bin
return false;
}
// printf("Found multidata file\n");
// Get the multidata file info.
unz_file_info multidata_file_info;
unzGetCurrentFileInfo(gen_zip, &multidata_file_info, nullptr, 0, nullptr, 0, nullptr, 0);
// printf("Got multidata file info, size %lu\n", multidata_file_info.uncompressed_size);
// Open the file.
int open_result = unzOpenCurrentFile(gen_zip);
// printf("Open multidata result: %d\n", open_result);
if (open_result != UNZ_OK) {
return false;
}
// Read the multidata file into a vector.
std::vector<char> multidata{};
multidata.resize(multidata_file_info.uncompressed_size);
int bytes_read = unzReadCurrentFile(gen_zip, multidata.data(), multidata.size());
// printf("Read multidata file, bytes read %d\n", bytes_read);
if (bytes_read <= 0) {
return false;
}
// Close the minizip handle.
unzCloseCurrentFile(gen_zip);
unzClose(gen_zip);
// Parse the multidata file, skipping the first byte (since it's an identifier byte written during generation).
bool parse_result = state->reader.parse(multidata.data() + 1, multidata.data() + multidata.size(), state->sp_ap_root);
// printf("Parse result: %d\n", (int)parse_result);
return parse_result;
}
void AP_InitSolo(AP_State* state, const char* filename, const char* seed) {
state->multiworld = false;
state->notfound = false;
state->queue_all_locations = false;
state->scout_queued_locations = false;
state->scout_all_locations = false;
std::filesystem::path mwfile_path{ std::u8string{ reinterpret_cast<const char8_t*>(filename) } };
if (!load_solo_zip(state, mwfile_path, seed)) {
state->auth = false;
state->notfound = false;
}
state->sp_save_path = mwfile_path;
state->sp_save_path.replace_extension("save.json");
if (std::filesystem::exists(state->sp_save_path)) {
std::ifstream savefile{ state->sp_save_path };
state->reader.parse(savefile, state->sp_save_root);
savefile.close();
}
else {
state->sp_save_root = {};
}
WriteFileJSON(state, state->sp_save_root, state->sp_save_path);
state->ap_player_name = AP_OFFLINE_NAME;
AP_Init_Generic(state);
}
void AP_Start(AP_State* state) {
state->init = true;
if (state->multiworld) {
state->webSocket.start();
} else {
if (!state->sp_save_root.get("init", false).asBool()) {
state->sp_save_root["init"] = true;
state->sp_save_root["checked_locations"] = Json::arrayValue;
state->sp_save_root["store"] = Json::objectValue;
}
// Only game in the data package is our game
state->ap_game = state->sp_ap_root["datapackage"].getMemberNames()[0];
Json::Value fake_msg;
fake_msg[0]["cmd"] = "Connected";
fake_msg[0]["slot"] = AP_OFFLINE_SLOT;
fake_msg[0]["slot_info"][std::to_string(AP_OFFLINE_SLOT)]["game"] = state->ap_game;
fake_msg[0]["players"] = Json::arrayValue;
fake_msg[0]["players"][0]["team"] = 0;
fake_msg[0]["players"][0]["slot"] = AP_OFFLINE_SLOT;
fake_msg[0]["players"][0]["alias"] = AP_OFFLINE_NAME;
fake_msg[0]["players"][0]["name"] = AP_OFFLINE_NAME;
fake_msg[0]["checked_locations"] = state->sp_save_root["checked_locations"];
fake_msg[0]["slot_data"] = state->sp_ap_root["slot_data"][std::to_string(AP_OFFLINE_SLOT)];
std::string req;
parse_response(state, state->writer.write(fake_msg), req);
fake_msg.clear();
state->datapkg_outdated_games.insert(state->ap_game);
fake_msg[0]["cmd"] = "DataPackage";
fake_msg[0]["data"]["games"] = state->sp_ap_root["datapackage"];
parse_response(state, state->writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "LocationInfo";
fake_msg[0]["locations"] = Json::arrayValue;
for (auto location_id : state->sp_ap_root["locations"][std::to_string(AP_OFFLINE_SLOT)].getMemberNames()) {
Json::Value location;
location["item"] = state->sp_ap_root["locations"][std::to_string(AP_OFFLINE_SLOT)][location_id][0];
location["location"] = (int64_t) strtoll(location_id.c_str(), NULL, 10);
location["player"] = state->ap_player_id;
location["flags"] = state->sp_ap_root["locations"][std::to_string(AP_OFFLINE_SLOT)][location_id][2];
fake_msg[0]["locations"].append(location);
}
parse_response(state, state->writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "ReceivedItems";
fake_msg[0]["index"] = 0;
fake_msg[0]["items"] = Json::arrayValue;
for (unsigned int i = 0; i < state->sp_save_root["checked_locations"].size(); i++) {
int64_t location_id = state->sp_save_root["checked_locations"][i].asInt64();
Json::Value item;
item["item"] = state->location_to_item[location_id];
item["location"] = location_id;
item["player"] = state->ap_player_id;
fake_msg[0]["items"].append(item);
}
for (unsigned int i = 0; i < state->sp_ap_root["precollected_items"][std::to_string(AP_OFFLINE_SLOT)].size(); ++i) {
Json::Value item;
item["item"] = state->sp_ap_root["precollected_items"][std::to_string(AP_OFFLINE_SLOT)][i].asInt64();
item["location"] = 0;
item["player"] = 0;
fake_msg[0]["items"].append(item);
}
parse_response(state, state->writer.write(fake_msg), req);
}
}
void AP_Stop(AP_State* state) {
state->webSocket.stop();
state->init = false;
state->notfound = false;
state->refused = false;
state->datapkg_received = false;
}
bool AP_IsInit(AP_State* state) {
return state->init;
}
bool AP_IsConnected(AP_State* state) {
return state->connected;
}
bool AP_ConnectionError(AP_State* state) {
return state->notfound || state->refused;
}
bool AP_IsScouted(AP_State* state) {
return state->scouted;
}
void AP_SetClientVersion(AP_State* state, AP_NetworkVersion* version) {
state->client_version.major = version->major;
state->client_version.minor = version->minor;
state->client_version.build = version->build;
}
bool AP_LocationExists(AP_State* state, int64_t location_idx) {
return state->all_locations.find(location_idx) != state->all_locations.end();
}
void AP_SendItem(AP_State* state, int64_t location_idx) {
AP_SendItems(state, std::set<int64_t>{ location_idx });
}
void AP_SendItems(AP_State* state, std::set<int64_t> const& locations) {
state->cache_mutex.lock();
for (int64_t idx : locations) {
//printf("AP: Checked '%s'.\n", getLocationName(ap_game, idx).c_str());
state->pending_locations.insert(idx);
if (state->location_has_local_item[idx]) {
int64_t item = state->location_to_item[idx];
int64_t location = idx;
int64_t type = state->location_item_type[idx];
int64_t sending_player = state->location_item_player_id[idx];
state->received_items.push_back(item);
state->received_item_locations.push_back(location);
state->received_item_types.push_back(type);
state->sending_player_ids.push_back(sending_player);
}
}
state->cache_mutex.unlock();
if (state->multiworld) {
Json::Value req_t;
req_t[0]["cmd"] = "LocationChecks";
req_t[0]["locations"] = Json::arrayValue;
for (int64_t loc : locations) {
req_t[0]["locations"].append(loc);
};
APSend(state, state->writer.write(req_t));
} else {
std::set<int64_t> new_locations;
for (int64_t idx : locations) {
bool was_previously_checked = false;
for (auto itr : state->sp_save_root["checked_locations"]) {
if (itr.asInt64() == idx) {
was_previously_checked = true;
break;
}
}
if (!was_previously_checked) new_locations.insert(idx);
}
Json::Value fake_msg;
fake_msg[0]["cmd"] = "ReceivedItems";
fake_msg[0]["index"] = state->last_item_idx+1;
fake_msg[0]["items"] = Json::arrayValue;
for (int64_t location_id : new_locations) {
int64_t recv_item_id = state->location_to_item[location_id];
if (recv_item_id == 0) continue;
Json::Value item;
item["item"] = recv_item_id;
item["location"] = location_id;
item["player"] = state->ap_player_id;
fake_msg[0]["items"].append(item);
}
std::string req;
parse_response(state, state->writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "RoomUpdate";
fake_msg[0]["checked_locations"] = Json::arrayValue;
for (int64_t idx : new_locations) {
fake_msg[0]["checked_locations"].append(idx);
state->sp_save_root["checked_locations"].append(idx);
}
WriteFileJSON(state, state->sp_save_root, state->sp_save_path);
parse_response(state, state->writer.write(fake_msg), req);
}
}
bool AP_GetDataPkgReceived(AP_State* state) {
return state->datapkg_received;
}
void AP_QueueLocationScout(AP_State* state, int64_t location) {
state->queued_scout_locations.insert(location);
}
void AP_RemoveQueuedLocationScout(AP_State* state, int64_t location) {
if (state->datapkg_received) {
state->queued_scout_locations.erase(location);
return;
}
state->removed_scout_locations.insert(location);
}
void AP_QueueLocationScoutsAll(AP_State* state) {
if (state->datapkg_received) {
for (auto location : state->all_locations) {
state->queued_scout_locations.insert(location);
}
return;
}
state->queue_all_locations = true;
}
void AP_SendQueuedLocationScouts(AP_State* state, int create_as_hint) {
if (state->datapkg_received) {
AP_SendLocationScouts(state, state->queued_scout_locations, create_as_hint);
state->queued_scout_locations.clear();
return;
}
state->scout_queued_locations_hint = create_as_hint;
state->scout_queued_locations = true;
}
void AP_SendLocationScoutsAll(AP_State* state, int create_as_hint) {
if (state->datapkg_received) {
AP_SendLocationScouts(state, state->all_locations, create_as_hint);
return;
}
state->scout_all_locations_hint = create_as_hint;
state->scout_all_locations = true;
}
void AP_SendLocationScouts(AP_State* state, std::set<int64_t> locations, int create_as_hint) {
if (state->multiworld) {
Json::Value req_t;
req_t[0]["cmd"] = "LocationScouts";
req_t[0]["locations"] = Json::arrayValue;
for (auto location : locations) {
req_t[0]["locations"].append(location);
}
req_t[0]["create_as_hint"] = create_as_hint;
APSend(state, state->writer.write(req_t));
} else {
Json::Value fake_msg;
fake_msg[0]["cmd"] = "LocationInfo";
fake_msg[0]["locations"] = Json::arrayValue;
for (auto location : locations) {
Json::Value netitem;
netitem["item"] = state->sp_ap_root["location_to_item"].get(std::to_string(location), 0).asInt64();
netitem["location"] = location;
netitem["player"] = state->ap_player_id;
netitem["flags"] = 0b001; // Hardcoded for SP seeds.
fake_msg[0]["locations"].append(netitem);
}
}
}
void AP_StoryComplete(AP_State* state) {
if (!state->multiworld) return;
Json::Value req_t;
req_t[0]["cmd"] = "StatusUpdate";
req_t[0]["status"] = 30; //CLIENT_GOAL
APSend(state, state->writer.write(req_t));
}
void AP_DeathLinkSend(AP_State* state) {
if (!state->enable_deathlink || !state->multiworld) return;
if (state->cur_deathlink_amnesty > 0) {
state->cur_deathlink_amnesty--;
return;
}
state->cur_deathlink_amnesty = state->deathlink_amnesty;
std::chrono::time_point<std::chrono::system_clock> timestamp = std::chrono::system_clock::now();
Json::Value req_t;
req_t[0]["cmd"] = "Bounce";
req_t[0]["data"]["time"] = std::chrono::duration_cast<std::chrono::seconds>(timestamp.time_since_epoch()).count();
req_t[0]["data"]["source"] = state->ap_player_name; // Name and Shame >:D
req_t[0]["tags"][0] = "DeathLink";
APSend(state, state->writer.write(req_t));
}
void AP_EnableQueueItemRecvMsgs(AP_State* state, bool b) {
state->queueitemrecvmsg = b;
}
void AP_SetItemClearCallback(AP_State* state, void (*f_itemclr)()) {
state->resetItemValues = f_itemclr;
}
void AP_SetItemRecvCallback(AP_State* state, void (*f_itemrecv)(int64_t,int,bool)) {
state->getitemfunc = f_itemrecv;
}
void AP_SetLocationCheckedCallback(AP_State* state, void (*f_loccheckrecv)(int64_t)) {
state->checklocfunc = f_loccheckrecv;
}
void AP_SetLocationInfoCallback(AP_State* state, void (*f_locinfrecv)(std::vector<AP_NetworkItem>)) {
state->locinfofunc = f_locinfrecv;
}
void AP_SetDeathLinkRecvCallback(AP_State* state, void (*f_deathrecv)()) {
state->recvdeath = f_deathrecv;
}
void AP_RegisterSlotDataIntCallback(AP_State* state, std::string key, void (*f_slotdata)(int)) {
state->map_slotdata_callback_int[key] = f_slotdata;
state->slotdata_strings.push_back(key);
}
void AP_RegisterSlotDataRawCallback(AP_State* state, std::string key, void (*f_slotdata)(std::string)) {
state->map_slotdata_callback_raw[key] = f_slotdata;
state->slotdata_strings.push_back(key);
}
void AP_RegisterSlotDataMapIntIntCallback(AP_State* state, std::string key, void (*f_slotdata)(std::map<int,int>)) {
state->map_slotdata_callback_mapintint[key] = f_slotdata;
state->slotdata_strings.push_back(key);
}
void AP_SetDeathLinkSupported(AP_State* state, bool supdeathlink) {
state->deathlinksupported = supdeathlink;
}
bool AP_DeathLinkPending(AP_State* state) {
return state->deathlinkstat;
}
void AP_DeathLinkClear(AP_State* state) {
state->deathlinkstat = false;
}
bool AP_IsMessagePending(AP_State* state) {
return !state->messageQueue.empty();
}
AP_Message* AP_GetEarliestMessage(AP_State* state) {
return state->messageQueue.front();
}
AP_Message* AP_GetLatestMessage(AP_State* state) {
return state->messageQueue.back();
}
void AP_ClearEarliestMessage(AP_State* state) {
if (AP_IsMessagePending(state)) {
delete state->messageQueue.front();
state->messageQueue.pop_front();
}
}
void AP_ClearLatestMessage(AP_State* state) {
if (AP_IsMessagePending(state)) {
delete state->messageQueue.back();
state->messageQueue.pop_back();
}
}
void AP_Say(AP_State* state, std::string text) {
Json::Value req_t;
req_t[0]["cmd"] = "Say";
req_t[0]["text"] = text;
APSend(state, state->writer.write(req_t));
}
int AP_GetRoomInfo(AP_State* state, AP_RoomInfo* client_roominfo) {
if (!state->auth) return 1;
*client_roominfo = state->lib_room_info;
return 0;
}
AP_ConnectionStatus AP_GetConnectionStatus(AP_State* state) {
if (!state->multiworld && state->auth) return AP_ConnectionStatus::Authenticated;
if (state->refused) {
return AP_ConnectionStatus::ConnectionRefused;
}
if (state->webSocket.getReadyState() == ix::ReadyState::Open) {
if (state->auth) {
return AP_ConnectionStatus::Authenticated;
} else {
return AP_ConnectionStatus::Connected;
}
}
if (state->notfound) {
return AP_ConnectionStatus::NotFound;
}
return AP_ConnectionStatus::Disconnected;
}
uint64_t AP_GetUUID(AP_State* state) {
return state->ap_uuid;
}
int AP_GetTeamID(AP_State* state) {
return state->ap_team_id;
}
int AP_GetPlayerID(AP_State* state) {
return state->ap_player_id;
}
const char* AP_GetPlayerName(AP_State* state) {
return state->ap_player_name.c_str();
}
void AP_SetServerData(AP_State* state, AP_SetServerDataRequest* request) {
request->status = AP_RequestStatus::Pending;
Json::Value req_t;
req_t[0]["cmd"] = "Set";
req_t[0]["key"] = request->key;
switch (request->type) {
case AP_DataType::Int:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
req_t[0]["operations"][i]["value"] = *((int*)request->operations[i].value);
}
break;
case AP_DataType::Double:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
req_t[0]["operations"][i]["value"] = *((double*)request->operations[i].value);
}
break;
default:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
Json::Value data;
state->reader.parse(*((std::string*)request->operations[i].value), data);
req_t[0]["operations"][i]["value"] = data;
}
Json::Value default_val_json;
state->reader.parse(*((std::string*)request->default_value), default_val_json);
req_t[0]["default"] = default_val_json;
break;
}
req_t[0]["want_reply"] = request->want_reply;
state->map_serverdata_typemanage[request->key] = request->type;
APSend(state, state->writer.write(req_t));
request->status = AP_RequestStatus::Done;
}
void AP_RegisterSetReplyCallback(AP_State* state, void (*f_setreply)(AP_SetReply)) {
state->setreplyfunc = f_setreply;
}
void AP_SetNotifies(AP_State* state, std::map<std::string, AP_DataType> keylist) {
Json::Value req_t;
req_t[0]["cmd"] = "SetNotify";
int i = 0;
for (std::pair<std::string,AP_DataType> keytypepair : keylist) {
req_t[0]["keys"][i] = keytypepair.first;
state->map_serverdata_typemanage[keytypepair.first] = keytypepair.second;
i++;
}
APSend(state, state->writer.write(req_t));
}
void AP_SetNotify(AP_State* state, std::string key, AP_DataType type) {
std::map<std::string, AP_DataType> keylist;
keylist[key] = type;
AP_SetNotifies(state, keylist);
}
void AP_SetManageMemory(AP_State* state, bool b) {
state->manage_memory = b;
}
char* AP_GetDataStorageSync(AP_State* state, const char* key) {
if (state->map_server_data.count(key) == 0) {
state->map_server_data[key] = new AP_GetServerDataRequest();
} else {
if (state->manage_memory) {
delete[] state->map_server_data[key]->value;
}
}
AP_GetServerDataRequest* request = state->map_server_data[key];
request->status = AP_RequestStatus::Pending;
request->type = AP_DataType::Raw;
request->key = key;
Json::Value req_t;
req_t[0]["cmd"] = "Get";
req_t[0]["keys"][0] = key;
APSend(state, state->writer.write(req_t));
while (request->status == AP_RequestStatus::Pending);
return (char*) request->value;
}
void AP_SetDataStorageSync(AP_State* state, const char* key, char* value) {
AP_SetDataStorageAsync(state, key, value);
while (state->map_serverdata_set_status[key] == AP_RequestStatus::Pending);
}
void AP_SetDataStorageAsync(AP_State* state, const char* key, char* value) {
state->map_serverdata_set_status[key] = AP_RequestStatus::Pending;
Json::Value req_t;
req_t[0]["cmd"] = "Set";
req_t[0]["key"] = key;
req_t[0]["want_reply"] = "true";
req_t[0]["operations"][0]["operation"] = "replace";
req_t[0]["operations"][0]["value"] = value;
APSend(state, state->writer.write(req_t));
}
std::string AP_GetPrivateServerDataPrefix(AP_State* state) {
return "APCpp" + std::to_string(state->ap_player_name_hash) + "APCpp" + std::to_string(state->ap_player_id) + "APCpp";
}
bool AP_GetLocationIsChecked(AP_State* state, int64_t location_idx) {
state->cache_mutex.lock();
bool is_checked = state->checked_locations.find(location_idx) != state->checked_locations.end() ||
state->pending_locations.find(location_idx) != state->pending_locations.end();
state->cache_mutex.unlock();
return is_checked;
}
const char* AP_GetItemNameFromID(AP_State* state, int64_t item_id) {
return state->item_to_name[item_id].c_str();
}
size_t AP_GetReceivedItemsSize(AP_State* state) {
state->cache_mutex.lock();
size_t size = state->received_items.size();
state->cache_mutex.unlock();
return size;
}
int64_t AP_GetReceivedItem(AP_State* state, size_t item_idx) {
int64_t item;
state->cache_mutex.lock();
item = state->received_items[item_idx];
state->cache_mutex.unlock();
return item;
}
int64_t AP_GetReceivedItemLocation(AP_State* state, size_t item_idx) {
int64_t location;
state->cache_mutex.lock();
location = state->received_item_locations[item_idx];
state->cache_mutex.unlock();
return location;
}
int64_t AP_GetReceivedItemType(AP_State* state, size_t item_idx) {
int64_t type;
state->cache_mutex.lock();
type = state->received_item_types[item_idx];
state->cache_mutex.unlock();
return type;
}
int64_t AP_GetSendingPlayer(AP_State* state, size_t item_idx) {
int64_t player;
state->cache_mutex.lock();
player = state->sending_player_ids[item_idx];
state->cache_mutex.unlock();
return player;
}
int64_t AP_GetSlotDataInt(AP_State* state, const char* key) {
return stol(state->slot_data[key]);
}
const char* AP_GetSlotDataString(AP_State* state, const char* key) {
return state->slot_data[key].c_str();
}
uintptr_t AP_GetSlotDataRaw(AP_State* state, const char* key) {
return (uintptr_t) &state->slot_data_raw[key];
}
uintptr_t AP_AccessSlotDataRawArray(AP_State* state, uintptr_t jsonValue, size_t index) {
const Json::Value* value = &(*((Json::Value*) jsonValue))[(Json::ArrayIndex) index];
return (uintptr_t) value;