-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathsteam_matchmaking.cpp
1716 lines (1441 loc) · 69.8 KB
/
steam_matchmaking.cpp
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
/* Copyright (C) 2019 Mr Goldberg
This file is part of the Goldberg Emulator
The Goldberg Emulator is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
The Goldberg Emulator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the Goldberg Emulator; if not, see
<http://www.gnu.org/licenses/>. */
#include "dll/steam_matchmaking.h"
#define SEND_LOBBY_RATE 5.0
#define PENDING_JOIN_TIMEOUT 10.0
#define REQUEST_LOBBY_DATA_TIMEOUT 6.0
#define LOBBY_DELETED_TIMEOUT 2
#define LOBBY_CREATE_DELAY 0.07 //artificial delay for lobby creation
#define FILTER_MAX_DEFAULT 4096
#define LOBBY_SEARCH_TIMEOUT 0.2 //Tested on real steam
google::protobuf::Map<std::string,std::string>::const_iterator Steam_Matchmaking::caseinsensitive_find(const ::google::protobuf::Map< ::std::string, ::std::string >& map, std::string key)
{
auto x = map.begin();
while (x != map.end()) {
if (common_helpers::str_cmp_insensitive(key, x->first)) {
break;
}
++x;
}
return x;
}
Lobby* Steam_Matchmaking::get_lobby(CSteamID id)
{
if (!id.IsLobby())
return NULL;
auto lobby = std::find_if(lobbies.begin(), lobbies.end(), [&id](Lobby const& item) { return (item.room_id() & 0xFFFFFFFF) == (id.GetAccountID()); });
if (lobbies.end() == lobby)
return NULL;
return &(*lobby);
}
void Steam_Matchmaking::send_lobby_data()
{
if (lobbies.size()) {
PRINT_DEBUG("lobbies %zu", lobbies.size());
}
for(auto & l: lobbies) {
if (get_lobby_member(&l, settings->get_local_steam_id()) && l.owner() == settings->get_local_steam_id().ConvertToUint64() && !l.deleted()) {
PRINT_DEBUG("lobby " "%" PRIu64 "", l.room_id());
Common_Message msg = Common_Message();
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.set_allocated_lobby(new Lobby(l));
network->sendToAllIndividuals(&msg, true);
}
}
}
void Steam_Matchmaking::trigger_lobby_dataupdate(CSteamID lobby, CSteamID member, bool success, double cb_timeout, bool send_changed_lobby)
{
PRINT_DEBUG("%llu %llu", lobby.ConvertToUint64(), member.ConvertToUint64());
LobbyDataUpdate_t data{};
data.m_ulSteamIDLobby = lobby.ConvertToUint64();
data.m_bSuccess = success;
data.m_ulSteamIDMember = member.ConvertToUint64();
callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), cb_timeout, true);
// if this was a user data update, then trigger another callback for the lobby itself
if (lobby != member) {
data.m_ulSteamIDMember = lobby.ConvertToUint64();
//Is this really necessary?
callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), cb_timeout, true);
}
Lobby *l = get_lobby(lobby);
if (l && l->owner() == settings->get_local_steam_id().ConvertToUint64()) {
if (send_changed_lobby) {
PRINT_DEBUG("resending new data");
Common_Message msg = Common_Message();
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.set_allocated_lobby(new Lobby(*l));
network->sendToAllIndividuals(&msg, true);
}
}
}
void Steam_Matchmaking::trigger_lobby_member_join_leave(CSteamID lobby, CSteamID member, bool leaving, bool success, double cb_timeout)
{
LobbyChatUpdate_t data{};
data.m_ulSteamIDLobby = lobby.ConvertToUint64();
data.m_ulSteamIDUserChanged = member.ConvertToUint64();
data.m_ulSteamIDMakingChange = member.ConvertToUint64();
uint32 member_state_change = 0; //EChatMemberStateChange
if (!leaving) {
member_state_change |= k_EChatMemberStateChangeEntered;
} else {
member_state_change |= k_EChatMemberStateChangeLeft;
}
data.m_rgfChatMemberStateChange = member_state_change;
callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), cb_timeout);
// trigger_lobby_dataupdate(lobby, member, success, cb_timeout);
trigger_lobby_dataupdate(lobby, lobby, success, cb_timeout);
}
bool Steam_Matchmaking::send_owner_packet(CSteamID lobby_id, Lobby_Messages *message)
{
Lobby *lobby = get_lobby(lobby_id);
if (!lobby) {
return false;
}
Common_Message msg{};
msg.set_allocated_lobby_messages(message);
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.set_dest_id((uint64)lobby->owner());
msg.mutable_lobby_messages()->set_id(lobby_id.ConvertToUint64());
return network->sendTo(&msg, true);
}
bool Steam_Matchmaking::send_clients_packet(CSteamID lobby_id, Lobby_Messages *message)
{
Lobby *lobby = get_lobby(lobby_id);
if (!lobby) {
return false;
}
Common_Message msg;
msg.set_allocated_lobby_messages(message);
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.mutable_lobby_messages()->set_id(lobby_id.ConvertToUint64());
return network->sendToAllIndividuals(&msg, true);
}
bool Steam_Matchmaking::send_lobby_members_packet(CSteamID lobby_id, Lobby_Messages *message)
{
Lobby *lobby = get_lobby(lobby_id);
if (!lobby) {
return false;
}
Common_Message msg;
msg.set_allocated_lobby_messages(message);
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.mutable_lobby_messages()->set_id(lobby_id.ConvertToUint64());
for (auto & m : lobby->members()) {
msg.set_dest_id((uint64)m.id());
network->sendTo(&msg, true);
}
return true;
}
bool Steam_Matchmaking::change_owner(Lobby *lobby, CSteamID new_owner)
{
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::CHANGE_OWNER);
message->set_idata(new_owner.ConvertToUint64());
lobby->set_owner(new_owner.ConvertToUint64());
send_owner_packet((uint64)lobby->room_id(), message);
trigger_lobby_dataupdate((uint64)lobby->room_id(), (uint64)lobby->room_id(), true);
return true;
}
void Steam_Matchmaking::send_gameservercreated_cb(uint64 room_id, uint64 server_id, uint32 ip, uint16 port)
{
LobbyGameCreated_t data;
data.m_ulSteamIDLobby = room_id;
data.m_ulSteamIDGameServer = server_id;
data.m_unIP = ip;
data.m_usPort = port;
callbacks->addCBResult(data.k_iCallback, &data, sizeof(data));
}
void Steam_Matchmaking::on_self_enter_leave_lobby(CSteamID id, int type, bool leaving)
{
if (type == k_ELobbyTypeInvisible) return;
if (!leaving) {
settings->set_lobby(id);
} else {
settings->set_lobby(k_steamIDNil);
}
//TODO: handle cases where in two lobbies of type not invisible
//steam says a user can only be in one regular lobby but we all know how well documented steam is
}
void Steam_Matchmaking::steam_matchmaking_callback(void *object, Common_Message *msg)
{
// PRINT_DEBUG_ENTRY();
Steam_Matchmaking *steam_matchmaking = (Steam_Matchmaking *)object;
steam_matchmaking->Callback(msg);
}
void Steam_Matchmaking::steam_matchmaking_run_every_runcb(void *object)
{
// PRINT_DEBUG_ENTRY();
Steam_Matchmaking *steam_matchmaking = (Steam_Matchmaking *)object;
steam_matchmaking->RunCallbacks();
}
bool Steam_Matchmaking::add_member_to_lobby(Lobby *lobby, CSteamID id)
{
if (get_lobby_member(lobby, id)) return false; // player already exists
Lobby_Member *member = lobby->add_members();
member->set_id(id.ConvertToUint64());
PRINT_DEBUG("added lobby member %llu", (uint64)id.ConvertToUint64());
return true;
}
bool Steam_Matchmaking::leave_lobby(Lobby *lobby, CSteamID id)
{
auto member = std::find_if(lobby->mutable_members()->begin(), lobby->mutable_members()->end(), [&id](Lobby_Member const& item) { return item.id() == id.ConvertToUint64(); });
if (member != lobby->mutable_members()->end()) {
lobby->mutable_members()->erase(member);
return true;
}
return false;
}
Lobby_Member* Steam_Matchmaking::get_lobby_member(Lobby *lobby, CSteamID user_id)
{
if (!lobby) return NULL;
auto member = std::find_if(lobby->mutable_members()->begin(), lobby->mutable_members()->end(), [&user_id](Lobby_Member const& item) { return item.id() == user_id.ConvertToUint64(); });
if (lobby->mutable_members()->end() == member)
return NULL;
return &(*member);
}
Steam_Matchmaking::Steam_Matchmaking(class Settings *settings, class Local_Storage *local_storage, class Networking *network, class SteamCallResults *callback_results, class SteamCallBacks *callbacks, class RunEveryRunCB *run_every_runcb)
{
this->settings = settings;
this->local_storage = local_storage;
this->network = network;
this->callback_results = callback_results;
this->callbacks = callbacks;
this->run_every_runcb = run_every_runcb;
this->filter_max_results = FILTER_MAX_DEFAULT;
search_call_api_id = 0;
searching = false;
this->network->setCallback(CALLBACK_ID_LOBBY, settings->get_local_steam_id(), &Steam_Matchmaking::steam_matchmaking_callback, this);
this->network->setCallback(CALLBACK_ID_USER_STATUS, settings->get_local_steam_id(), &Steam_Matchmaking::steam_matchmaking_callback, this);
this->run_every_runcb->add(&Steam_Matchmaking::steam_matchmaking_run_every_runcb, this);
}
Steam_Matchmaking::~Steam_Matchmaking()
{
this->network->rmCallback(CALLBACK_ID_LOBBY, settings->get_local_steam_id(), &Steam_Matchmaking::steam_matchmaking_callback, this);
this->network->rmCallback(CALLBACK_ID_USER_STATUS, settings->get_local_steam_id(), &Steam_Matchmaking::steam_matchmaking_callback, this);
this->run_every_runcb->remove(&Steam_Matchmaking::steam_matchmaking_run_every_runcb, this);
}
// game server favorites storage
// saves basic details about a multiplayer game server locally
// returns the number of favorites servers the user has stored
int Steam_Matchmaking::GetFavoriteGameCount()
{
PRINT_DEBUG_ENTRY();
std::string file_path = local_storage->get_current_save_directory() + "7" + PATH_SEPARATOR + Local_Storage::remote_storage_folder + PATH_SEPARATOR + "serverbrowser_favorites.txt";
unsigned int file_size = file_size_(file_path);
if (file_size) {
std::string list{};
list.resize(file_size);
Local_Storage::get_file_data(file_path, (char *)&list[0], file_size, 0);
auto list_lines = std::count(list.begin(), list.end(), '\n');
list_lines += (!list.empty() && list.back() != '\n');
return static_cast<int>(list_lines);
}
return 0;
}
// returns the details of the game server
// iGame is of range [0,GetFavoriteGameCount())
// *pnIP, *pnConnPort are filled in the with IP:port of the game server
// *punFlags specify whether the game server was stored as an explicit favorite or in the history of connections
// *pRTime32LastPlayedOnServer is filled in the with the Unix time the favorite was added
bool Steam_Matchmaking::GetFavoriteGame( int iGame, AppId_t *pnAppID, uint32 *pnIP, uint16 *pnConnPort, uint16 *pnQueryPort, uint32 *punFlags, uint32 *pRTime32LastPlayedOnServer )
{
PRINT_DEBUG_ENTRY();
return false;
}
// adds the game server to the local list; updates the time played of the server if it already exists in the list
int Steam_Matchmaking::AddFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags, uint32 rTime32LastPlayedOnServer )
{
PRINT_DEBUG("%u %u %hu %hu %u %u", nAppID, nIP, nConnPort, nQueryPort, unFlags, rTime32LastPlayedOnServer);
std::string file_path{};
unsigned int file_size{};
if (unFlags == 1) {
file_path = local_storage->get_current_save_directory() + "7" + PATH_SEPARATOR + Local_Storage::remote_storage_folder + PATH_SEPARATOR + "serverbrowser_favorites.txt";
file_size = file_size_(file_path);
} else if (unFlags == 2) {
file_path = local_storage->get_current_save_directory() + "7" + PATH_SEPARATOR + Local_Storage::remote_storage_folder + PATH_SEPARATOR + "serverbrowser_history.txt";
file_size = file_size_(file_path);
} else {
return 0;
}
unsigned char ip[4]{};
ip[0] = nIP & 0xFF;
ip[1] = (nIP >> 8) & 0xFF;
ip[2] = (nIP >> 16) & 0xFF;
ip[3] = (nIP >> 24) & 0xFF;
char newip[24]{};
snprintf(newip, sizeof(newip), "%d.%d.%d.%d:%d\n", ip[3], ip[2], ip[1], ip[0], nConnPort);
std::string newip_string(newip);
if (file_size) {
std::string list{};
list.resize(file_size);
Local_Storage::get_file_data(file_path, (char*)&list[0], file_size, 0);
auto list_lines = std::count(list.begin(), list.end(), '\n');
list_lines += (!list.empty() && list.back() != '\n');
std::size_t find_ip = list.find(newip_string);
if (find_ip == std::string::npos) {
list.append(newip_string);
list.append("\n");
std::size_t file_directory = file_path.find_last_of("/\\");
std::string directory_path;
std::string file_name;
if (file_directory != std::string::npos) {
directory_path = file_path.substr(0, file_directory);
file_name = file_path.substr(file_directory);
}
Local_Storage::store_file_data(directory_path, file_name, (char *)list.data(), (unsigned int)list.size());
++list_lines;
return static_cast<int>(list_lines);
}
return static_cast<int>(list_lines);
} else {
newip_string.append("\n");
std::size_t file_directory = file_path.find_last_of("/\\");
std::string directory_path;
std::string file_name;
if (file_directory != std::string::npos) {
directory_path = file_path.substr(0, file_directory);
file_name = file_path.substr(file_directory);
}
Local_Storage::store_file_data(directory_path, file_name, (char *)newip_string.data(), (unsigned int)newip_string.size());
return 1;
}
}
// removes the game server from the local storage; returns true if one was removed
bool Steam_Matchmaking::RemoveFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags )
{
PRINT_DEBUG_ENTRY();
std::string file_path{};
unsigned int file_size{};
if (unFlags == 1) {
file_path = local_storage->get_current_save_directory() + "7" + PATH_SEPARATOR + Local_Storage::remote_storage_folder + "serverbrowser_favorites.txt";
file_size = file_size_(file_path);
} else if (unFlags == 2) {
file_path = local_storage->get_current_save_directory() + "7" + PATH_SEPARATOR + Local_Storage::remote_storage_folder + "serverbrowser_history.txt";
file_size = file_size_(file_path);
} else {
return false;
}
if (file_size) {
std::string list{};
list.resize(file_size);
Local_Storage::get_file_data(file_path, (char*)&list[0], file_size, 0);
unsigned char ip[4]{};
ip[0] = nIP & 0xFF;
ip[1] = (nIP >> 8) & 0xFF;
ip[2] = (nIP >> 16) & 0xFF;
ip[3] = (nIP >> 24) & 0xFF;
char newip[24]{};
snprintf((char *)newip, sizeof(newip), "%d.%d.%d.%d:%d\n", ip[3], ip[2], ip[1], ip[0], nConnPort);
std::string newip_string(newip);
std::size_t list_ip = list.find(newip_string);
if (list_ip != std::string::npos) {
list.erase(list_ip, newip_string.length());
std::size_t file_directory = file_path.find_last_of("/\\");
std::string directory_path{};
std::string file_name{};
if (file_directory != std::string::npos) {
directory_path = file_path.substr(0, file_directory);
file_name = file_path.substr(file_directory);
}
Local_Storage::store_file_data(directory_path, file_name, (char *)list.data(), (unsigned int)list.size());
return true;
}
}
return false;
}
///////
// Game lobby functions
// Get a list of relevant lobbies
// this is an asynchronous request
// results will be returned by LobbyMatchList_t callback & call result, with the number of lobbies found
// this will never return lobbies that are full
// to add more filter, the filter calls below need to be call before each and every RequestLobbyList() call
// use the CCallResult<> object in steam_api.h to match the SteamAPICall_t call result to a function in an object, e.g.
/*
class CMyLobbyListManager
{
CCallResult<CMyLobbyListManager, LobbyMatchList_t> m_CallResultLobbyMatchList;
void FindLobbies()
{
// SteamMatchmaking()->AddRequestLobbyListFilter*() functions would be called here, before RequestLobbyList();
m_CallResultLobbyMatchList.Set( hSteamAPICall, this, &CMyLobbyListManager::OnLobbyMatchList );
}
void OnLobbyMatchList( LobbyMatchList_t *pLobbyMatchList, bool bIOFailure )
{
// lobby list has be retrieved from Steam back-end, use results
}
}
*/
//
STEAM_CALL_RESULT( LobbyMatchList_t )
SteamAPICall_t Steam_Matchmaking::RequestLobbyList()
{
PRINT_DEBUG_ENTRY();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
filtered_lobbies.clear();
lobby_last_search = std::chrono::high_resolution_clock::now();
filter_values_copy = filter_values;
filter_max_results_copy = filter_max_results;
filter_values.clear();
filter_max_results = FILTER_MAX_DEFAULT;
searching = true;
if (search_call_api_id) callback_results->rmCallBack(search_call_api_id, NULL);
search_call_api_id = callback_results->reserveCallResult();
return search_call_api_id;
}
void Steam_Matchmaking::RequestLobbyList_OLD()
{
RequestLobbyList();
}
// filters for lobbies
// this needs to be called before RequestLobbyList() to take effect
// these are cleared on each call to RequestLobbyList()
void Steam_Matchmaking::AddRequestLobbyListStringFilter( const char *pchKeyToMatch, const char *pchValueToMatch, ELobbyComparison eComparisonType )
{
PRINT_DEBUG("'%s'=='%s' %i", pchKeyToMatch, pchValueToMatch, eComparisonType);
if (!pchValueToMatch) return;
std::lock_guard<std::recursive_mutex> lock(global_mutex);
struct Filter_Values fv;
fv.key = std::string(pchKeyToMatch);
fv.value_string = std::string(pchValueToMatch);
fv.is_int = false;
fv.eComparisonType = eComparisonType;
filter_values.push_back(fv);
}
// numerical comparison
void Steam_Matchmaking::AddRequestLobbyListNumericalFilter( const char *pchKeyToMatch, int nValueToMatch, ELobbyComparison eComparisonType )
{
PRINT_DEBUG("'%s'==%i %i", pchKeyToMatch, nValueToMatch, eComparisonType);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
struct Filter_Values fv;
fv.key = std::string(pchKeyToMatch);
fv.value_int = nValueToMatch;
fv.is_int = true;
fv.eComparisonType = eComparisonType;
filter_values.push_back(fv);
}
// returns results closest to the specified value. Multiple near filters can be added, with early filters taking precedence
void Steam_Matchmaking::AddRequestLobbyListNearValueFilter( const char *pchKeyToMatch, int nValueToBeCloseTo )
{
PRINT_DEBUG("'%s'==%u", pchKeyToMatch, nValueToBeCloseTo);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
}
// returns only lobbies with the specified number of slots available
void Steam_Matchmaking::AddRequestLobbyListFilterSlotsAvailable( int nSlotsAvailable )
{
PRINT_DEBUG("%i", nSlotsAvailable);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
}
// sets the distance for which we should search for lobbies (based on users IP address to location map on the Steam backed)
void Steam_Matchmaking::AddRequestLobbyListDistanceFilter( ELobbyDistanceFilter eLobbyDistanceFilter )
{
PRINT_DEBUG("%i", eLobbyDistanceFilter);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
}
// sets how many results to return, the lower the count the faster it is to download the lobby results & details to the client
void Steam_Matchmaking::AddRequestLobbyListResultCountFilter( int cMaxResults )
{
PRINT_DEBUG("%i", cMaxResults);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
filter_max_results = cMaxResults;
}
void Steam_Matchmaking::AddRequestLobbyListCompatibleMembersFilter( CSteamID steamIDLobby )
{
PRINT_DEBUG_ENTRY();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
}
void Steam_Matchmaking::AddRequestLobbyListFilter( const char *pchKeyToMatch, const char *pchValueToMatch )
{
AddRequestLobbyListStringFilter(pchKeyToMatch, pchValueToMatch, k_ELobbyComparisonEqual);
}
void Steam_Matchmaking::AddRequestLobbyListNumericalFilter( const char *pchKeyToMatch, int nValueToMatch, int nComparisonType )
{
AddRequestLobbyListNumericalFilter(pchKeyToMatch, nValueToMatch, (ELobbyComparison) nComparisonType );
}
void Steam_Matchmaking::AddRequestLobbyListSlotsAvailableFilter()
{
PRINT_DEBUG_TODO();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
}
// returns the CSteamID of a lobby, as retrieved by a RequestLobbyList call
// should only be called after a LobbyMatchList_t callback is received
// iLobby is of the range [0, LobbyMatchList_t::m_nLobbiesMatching)
// the returned CSteamID::IsValid() will be false if iLobby is out of range
CSteamID Steam_Matchmaking::GetLobbyByIndex( int iLobby )
{
PRINT_DEBUG("%i", iLobby);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
CSteamID id = k_steamIDNil;
if (iLobby >= 0 && static_cast<size_t>(iLobby) < filtered_lobbies.size()) {
id = filtered_lobbies[iLobby];
}
PRINT_DEBUG("found lobby %llu", id.ConvertToUint64());
return id;
}
void Steam_Matchmaking::GetLobbyByIndex(CSteamID& res, int iLobby )
{
PRINT_DEBUG_GNU_WIN();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
res = GetLobbyByIndex(iLobby );
}
// Create a lobby on the Steam servers.
// If private, then the lobby will not be returned by any RequestLobbyList() call; the CSteamID
// of the lobby will need to be communicated via game channels or via InviteUserToLobby()
// this is an asynchronous request
// results will be returned by LobbyCreated_t callback and call result; lobby is joined & ready to use at this point
// a LobbyEnter_t callback will also be received (since the local user is joining their own lobby)
STEAM_CALL_RESULT( LobbyCreated_t )
SteamAPICall_t Steam_Matchmaking::CreateLobby( ELobbyType eLobbyType, int cMaxMembers )
{
PRINT_DEBUG("type: %i max_members: %i", eLobbyType, cMaxMembers);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
struct Pending_Creates p_c{};
p_c.api_id = callback_results->reserveCallResult();
p_c.eLobbyType = eLobbyType;
p_c.cMaxMembers = cMaxMembers;
p_c.created = std::chrono::high_resolution_clock::now();
pending_creates.push_back(p_c);
return p_c.api_id;
}
SteamAPICall_t Steam_Matchmaking::CreateLobby( ELobbyType eLobbyType )
{
PRINT_DEBUG("old");
return CreateLobby(eLobbyType, 0);
}
void Steam_Matchmaking::CreateLobby_OLD( ELobbyType eLobbyType )
{
CreateLobby(eLobbyType);
}
void Steam_Matchmaking::CreateLobby( bool bPrivate )
{
CreateLobby(bPrivate ? k_ELobbyTypePrivate : k_ELobbyTypePublic);
}
// Joins an existing lobby
// this is an asynchronous request
// results will be returned by LobbyEnter_t callback & call result, check m_EChatRoomEnterResponse to see if was successful
// lobby metadata is available to use immediately on this call completing
STEAM_CALL_RESULT( LobbyEnter_t )
SteamAPICall_t Steam_Matchmaking::JoinLobby( CSteamID steamIDLobby )
{
PRINT_DEBUG("%llu", steamIDLobby.ConvertToUint64());
std::lock_guard<std::recursive_mutex> lock(global_mutex);
auto pj = std::find_if(pending_joins.begin(), pending_joins.end(), [&steamIDLobby](Pending_Joins const& item) {return item.lobby_id == steamIDLobby;});
if (pj != pending_joins.end()) {
PRINT_DEBUG("already found in pending joins list");
return pj->api_id;
}
Pending_Joins pending_join{};
pending_join.api_id = callback_results->reserveCallResult();
pending_join.lobby_id = steamIDLobby;
pending_join.joined = std::chrono::high_resolution_clock::now();
pending_joins.push_back(pending_join);
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::JOIN);
pending_join.message_sent = send_owner_packet(steamIDLobby, message);
PRINT_DEBUG("added new entry to pending joins");
return pending_join.api_id;
}
void Steam_Matchmaking::JoinLobby_OLD( CSteamID steamIDLobby )
{
JoinLobby(steamIDLobby);
}
// Leave a lobby; this will take effect immediately on the client side
// other users in the lobby will be notified by a LobbyChatUpdate_t callback
void Steam_Matchmaking::LeaveLobby( CSteamID steamIDLobby )
{
PRINT_DEBUG_ENTRY();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
PRINT_DEBUG("pass mutex");
Lobby *lobby = get_lobby(steamIDLobby);
if (lobby) {
if (!lobby->deleted()) {
on_self_enter_leave_lobby((uint64)lobby->room_id(), lobby->type(), true);
self_lobby_member_data.erase(lobby->room_id());
if (lobby->owner() != settings->get_local_steam_id().ConvertToUint64()) {
PRINT_DEBUG("not owner");
leave_lobby(&(*lobby), settings->get_local_steam_id());
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::LEAVE);
send_owner_packet(steamIDLobby, message);
} else {
PRINT_DEBUG("owner");
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::LEAVE);
if (lobby->members().size() > 1) {
leave_lobby(&(*lobby), settings->get_local_steam_id());
change_owner(&(*lobby), (uint64)lobby->members(0).id());
send_owner_packet(steamIDLobby, message);
} else {
send_clients_packet(steamIDLobby, message);
lobby->set_deleted(true);
lobby->set_time_deleted(std::chrono::duration_cast<std::chrono::duration<uint64>>(std::chrono::system_clock::now().time_since_epoch()).count());
}
}
}
}
PRINT_DEBUG("Done");
}
// Invite another user to the lobby
// the target user will receive a LobbyInvite_t callback
// will return true if the invite is successfully sent, whether or not the target responds
// returns false if the local user is not connected to the Steam servers
// if the other user clicks the join link, a GameLobbyJoinRequested_t will be posted if the user is in-game,
// or if the game isn't running yet the game will be launched with the parameter +connect_lobby <64-bit lobby id>
bool Steam_Matchmaking::InviteUserToLobby( CSteamID steamIDLobby, CSteamID steamIDInvitee )
{
PRINT_DEBUG_ENTRY();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
if (!lobby) return false;
Common_Message msg;
Friend_Messages *friend_messages = new Friend_Messages();
friend_messages->set_type(Friend_Messages::LOBBY_INVITE);
friend_messages->set_lobby_id(steamIDLobby.ConvertToUint64());
msg.set_allocated_friend_messages(friend_messages);
msg.set_source_id(settings->get_local_steam_id().ConvertToUint64());
msg.set_dest_id(steamIDInvitee.ConvertToUint64());
return network->sendTo(&msg, true);
}
// Lobby iteration, for viewing details of users in a lobby
// only accessible if the lobby user is a member of the specified lobby
// persona information for other lobby members (name, avatar, etc.) will be asynchronously received
// and accessible via ISteamFriends interface
// returns the number of users in the specified lobby
int Steam_Matchmaking::GetNumLobbyMembers( CSteamID steamIDLobby )
{
PRINT_DEBUG("%llu", steamIDLobby.ConvertToUint64());
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
int ret = 0;
if (lobby) ret = lobby->members().size();
PRINT_DEBUG("count=%i", ret);
return ret;
}
// returns the CSteamID of a user in the lobby
// iMember is of range [0,GetNumLobbyMembers())
// note that the current user must be in a lobby to retrieve CSteamIDs of other users in that lobby
CSteamID Steam_Matchmaking::GetLobbyMemberByIndex( CSteamID steamIDLobby, int iMember )
{
PRINT_DEBUG("%llu %i", steamIDLobby.ConvertToUint64(), iMember);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
CSteamID id = k_steamIDNil;
if (lobby && !lobby->deleted() && lobby->members().size() > iMember && iMember >= 0) id = (uint64)lobby->members(iMember).id();
PRINT_DEBUG("found member: %llu", id.ConvertToUint64());
return id;
}
void Steam_Matchmaking::GetLobbyMemberByIndex(CSteamID&res, CSteamID steamIDLobby, int iMember )
{
PRINT_DEBUG_GNU_WIN();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
res = GetLobbyMemberByIndex( steamIDLobby, iMember );
}
// Get data associated with this lobby
// takes a simple key, and returns the string associated with it
// "" will be returned if no value is set, or if steamIDLobby is invalid
const char* Steam_Matchmaking::GetLobbyData( CSteamID steamIDLobby, const char *pchKey )
{
PRINT_DEBUG("%llu '%s'", steamIDLobby.ConvertToUint64(), pchKey);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
if (!pchKey) return "";
Lobby *lobby = get_lobby(steamIDLobby);
const char *ret = "";
if (lobby) {
auto result = caseinsensitive_find(lobby->values(), pchKey);
if (result != lobby->values().end()) ret = result->second.c_str();
}
PRINT_DEBUG("returned '%s'", ret);
return ret;
}
// Sets a key/value pair in the lobby metadata
// each user in the lobby will be broadcast this new value, and any new users joining will receive any existing data
// this can be used to set lobby names, map, etc.
// to reset a key, just set it to ""
// other users in the lobby will receive notification of the lobby data change via a LobbyDataUpdate_t callback
bool Steam_Matchmaking::SetLobbyData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue )
{
PRINT_DEBUG("[%llu] '%s'='%s'", steamIDLobby.ConvertToUint64(), pchKey, pchValue);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
if (!pchKey) return false;
if (!pchValue) pchValue = "";
Lobby *lobby = get_lobby(steamIDLobby);
if (!lobby || lobby->deleted()) {
return false;
}
bool changed = true;
//callback is always triggered when setlobbydata is called from non owner however no data is actually changed.
if (lobby->owner() == settings->get_local_steam_id().ConvertToUint64()) {
auto result = caseinsensitive_find(lobby->values(), pchKey);
if (result == lobby->values().end()) {
(*lobby->mutable_values())[pchKey] = pchValue;
} else {
if (result->second == std::string(pchValue)) changed = false;
(*lobby->mutable_values())[result->first] = pchValue;
}
}
if (changed)
trigger_lobby_dataupdate(steamIDLobby, steamIDLobby, true, 0.005, changed);
return true;
}
// returns the number of metadata keys set on the specified lobby
int Steam_Matchmaking::GetLobbyDataCount( CSteamID steamIDLobby )
{
PRINT_DEBUG("%llu", steamIDLobby.ConvertToUint64());
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
int size = 0;
if (lobby) size = static_cast<int>(lobby->values().size());
return size;
}
// returns a lobby metadata key/values pair by index, of range [0, GetLobbyDataCount())
bool Steam_Matchmaking::GetLobbyDataByIndex( CSteamID steamIDLobby, int iLobbyData, char *pchKey, int cchKeyBufferSize, char *pchValue, int cchValueBufferSize )
{
PRINT_DEBUG("%llu [%i] key size=%i, value size=%i", steamIDLobby.ConvertToUint64(), iLobbyData, cchKeyBufferSize, cchValueBufferSize);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
bool ret = false;
if (iLobbyData >= 0 && lobby && lobby->values().size() > static_cast<size_t>(iLobbyData)) {
auto lobby_data = lobby->values().begin();
for (int i = 0; i < iLobbyData; ++i) ++lobby_data;
if (pchKey && cchKeyBufferSize > 0) {
strncpy(pchKey, lobby_data->first.c_str(), cchKeyBufferSize - 1);
pchKey[cchKeyBufferSize - 1] = 0;
}
if (pchValue && cchValueBufferSize > 0) {
strncpy(pchValue, lobby_data->second.c_str(), cchValueBufferSize - 1);
pchValue[cchValueBufferSize - 1] = 0;
}
PRINT_DEBUG("ret '%s'='%s'", pchKey, pchValue);
ret = true;
}
return ret;
}
// removes a metadata key from the lobby
bool Steam_Matchmaking::DeleteLobbyData( CSteamID steamIDLobby, const char *pchKey )
{
PRINT_DEBUG("'%s'", pchKey);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
if (!lobby || lobby->owner() != settings->get_local_steam_id().ConvertToUint64() || lobby->deleted()) {
return false;
}
lobby->mutable_values()->erase(pchKey);
trigger_lobby_dataupdate(steamIDLobby, steamIDLobby, true);
return true;
}
// Gets per-user metadata for someone in this lobby
const char* Steam_Matchmaking::GetLobbyMemberData( CSteamID steamIDLobby, CSteamID steamIDUser, const char *pchKey )
{
PRINT_DEBUG("'%s' %llu %llu", pchKey, steamIDLobby.ConvertToUint64(), steamIDUser.ConvertToUint64());
std::lock_guard<std::recursive_mutex> lock(global_mutex);
if (!pchKey) return "";
Lobby_Member *member = get_lobby_member(get_lobby(steamIDLobby), steamIDUser);
const char *ret = "";
if (member) {
if (steamIDUser == settings->get_local_steam_id()) {
auto result = self_lobby_member_data.find(steamIDLobby.ConvertToUint64());
if (result != self_lobby_member_data.end()) {
auto value = caseinsensitive_find(result->second, std::string(pchKey));
if (value != result->second.end()) {
ret = value->second.c_str();
}
}
} else {
auto result = caseinsensitive_find(member->values(), std::string(pchKey));
if (result == member->values().end()) return "";
ret = result->second.c_str();
}
}
PRINT_DEBUG("res '%s'", ret);
return ret;
}
// Sets per-user metadata (for the local user implicitly)
void Steam_Matchmaking::SetLobbyMemberData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue )
{
PRINT_DEBUG("%llu '%s'='%s'", steamIDLobby.ConvertToUint64(), pchKey, pchValue);
if (!pchKey) return;
char empty_string[] = "";
if (!pchValue) pchValue = empty_string;
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
if (!lobby || lobby->deleted()) return;
Lobby_Member *member = get_lobby_member(lobby, settings->get_local_steam_id());
if (member) {
if (lobby->owner() == settings->get_local_steam_id().ConvertToUint64()) {
auto result = caseinsensitive_find(member->values(), std::string(pchKey));
if (result == member->values().end()) {
(*member->mutable_values())[pchKey] = pchValue;
} else {
(*member->mutable_values())[result->first] = pchValue;
}
trigger_lobby_dataupdate(steamIDLobby, (uint64)member->id(), true);
} else {
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::MEMBER_DATA);
(*message->mutable_map())[pchKey] = pchValue;
send_owner_packet(steamIDLobby, message);
}
{
auto result = self_lobby_member_data.find(steamIDLobby.ConvertToUint64());
if (result != self_lobby_member_data.end()) {
auto value = caseinsensitive_find(result->second, std::string(pchKey));
if (value != result->second.end()) {
self_lobby_member_data[steamIDLobby.ConvertToUint64()][value->first] = pchValue;
} else {
self_lobby_member_data[steamIDLobby.ConvertToUint64()][pchKey] = pchValue;
}
} else {
self_lobby_member_data[steamIDLobby.ConvertToUint64()][pchKey] = pchValue;
}
}
}
}
// Broadcasts a chat message to the all the users in the lobby
// users in the lobby (including the local user) will receive a LobbyChatMsg_t callback
// returns true if the message is successfully sent
// pvMsgBody can be binary or text data, up to 4k
// if pvMsgBody is text, cubMsgBody should be strlen( text ) + 1, to include the null terminator
bool Steam_Matchmaking::SendLobbyChatMsg( CSteamID steamIDLobby, const void *pvMsgBody, int cubMsgBody )
{
PRINT_DEBUG("%llu %i", steamIDLobby.ConvertToUint64(), cubMsgBody);
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Lobby *lobby = get_lobby(steamIDLobby);
if (!lobby || lobby->deleted()) return false;
Lobby_Messages *message = new Lobby_Messages();
message->set_type(Lobby_Messages::CHAT_MESSAGE);
message->set_bdata(pvMsgBody, cubMsgBody);
return send_lobby_members_packet(steamIDLobby, message);
}
// Get a chat message as specified in a LobbyChatMsg_t callback
// iChatID is the LobbyChatMsg_t::m_iChatID value in the callback