• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Return-To-The-Roots / s25client / 9329876669

01 Jun 2024 11:21AM UTC coverage: 50.405% (+0.005%) from 50.4%
9329876669

Pull #1671

github

web-flow
Merge d052ea2de into bd8f2bdd0
Pull Request #1671: Add `indexOf_if` and refactor `helpers::` related functions

70 of 86 new or added lines in 15 files covered. (81.4%)

8 existing lines in 3 files now uncovered.

22013 of 43672 relevant lines covered (50.41%)

32345.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

4.66
/libs/s25main/network/GameServer.cpp
1
// Copyright (C) 2005 - 2024 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "GameServer.h"
6
#include "Debug.h"
7
#include "GameMessage.h"
8
#include "GameMessage_GameCommand.h"
9
#include "GameServerPlayer.h"
10
#include "GlobalGameSettings.h"
11
#include "JoinPlayerInfo.h"
12
#include "RTTR_Version.h"
13
#include "RttrConfig.h"
14
#include "Savegame.h"
15
#include "Settings.h"
16
#include "commonDefines.h"
17
#include "files.h"
18
#include "helpers/containerUtils.h"
19
#include "helpers/mathFuncs.h"
20
#include "helpers/random.h"
21
#include "network/CreateServerInfo.h"
22
#include "network/GameMessages.h"
23
#include "random/randomIO.h"
24
#include "gameTypes/LanGameInfo.h"
25
#include "gameTypes/TeamTypes.h"
26
#include "gameData/GameConsts.h"
27
#include "gameData/LanDiscoveryCfg.h"
28
#include "gameData/MaxPlayers.h"
29
#include "liblobby/LobbyClient.h"
30
#include "libsiedler2/ArchivItem_Map.h"
31
#include "libsiedler2/ArchivItem_Map_Header.h"
32
#include "libsiedler2/prototypen.h"
33
#include "s25util/SocketSet.h"
34
#include "s25util/colors.h"
35
#include "s25util/utf8.h"
36
#include <boost/container/static_vector.hpp>
37
#include <boost/filesystem.hpp>
38
#include <boost/nowide/convert.hpp>
39
#include <boost/nowide/fstream.hpp>
40
#include <helpers/chronoIO.h>
41
#include <iomanip>
42
#include <iterator>
43
#include <mygettext/mygettext.h>
44

45
struct GameServer::AsyncLog
46
{
47
    uint8_t playerId;
48
    bool done;
49
    AsyncChecksum checksum;
50
    std::string addData;
51
    std::vector<RandomEntry> randEntries;
52
    AsyncLog(uint8_t playerId, AsyncChecksum checksum) : playerId(playerId), done(false), checksum(checksum) {}
×
53
};
54

55
GameServer::ServerConfig::ServerConfig()
×
56
{
57
    Clear();
×
58
}
×
59

60
void GameServer::ServerConfig::Clear()
×
61
{
62
    servertype = ServerType::Local;
×
63
    gamename.clear();
×
64
    password.clear();
×
65
    port = 0;
×
66
    ipv6 = false;
×
67
}
×
68

69
GameServer::CountDown::CountDown() : isActive(false), remainingSecs(0) {}
×
70

71
void GameServer::CountDown::Start(unsigned timeInSec)
×
72
{
73
    isActive = true;
×
74
    remainingSecs = timeInSec;
×
75
    lasttime = SteadyClock::now();
×
76
}
×
77

78
void GameServer::CountDown::Stop()
×
79
{
80
    isActive = false;
×
81
}
×
82

83
bool GameServer::CountDown::Update()
×
84
{
85
    RTTR_Assert(isActive);
×
86
    SteadyClock::time_point curTime = SteadyClock::now();
×
87

88
    // Check if 1s has passed
89
    if(curTime - lasttime < std::chrono::seconds(1))
×
90
        return false;
×
91
    if(remainingSecs == 0)
×
92
    {
93
        Stop();
×
94
        return true;
×
95
    }
96
    // 1s has passed -> Reduce remaining time
97
    lasttime = curTime;
×
98
    remainingSecs--;
×
99
    return true;
×
100
}
101

102
///////////////////////////////////////////////////////////////////////////////
103
//
104
GameServer::GameServer() : skiptogf(0), state(ServerState::Stopped), currentGF(0), lanAnnouncer(LAN_DISCOVERY_CFG) {}
×
105

106
///////////////////////////////////////////////////////////////////////////////
107
//
108
GameServer::~GameServer()
×
109
{
110
    Stop();
×
111
}
×
112

113
///////////////////////////////////////////////////////////////////////////////
114
// Spiel hosten
115
bool GameServer::Start(const CreateServerInfo& csi, const MapDescription& map, const std::string& hostPw)
×
116
{
117
    Stop();
×
118

119
    // Name, Password und Kartenname kopieren
120
    config.gamename = csi.gameName;
×
121
    config.hostPassword = hostPw;
×
122
    config.password = csi.password;
×
123
    config.servertype = csi.type;
×
124
    config.port = csi.port;
×
125
    config.ipv6 = csi.ipv6;
×
126
    mapinfo.type = map.map_type;
×
127
    mapinfo.filepath = map.map_path;
×
128

129
    // Maps, Random-Maps, Savegames - Header laden und relevante Informationen rausschreiben (Map-Titel, Spieleranzahl)
130
    switch(mapinfo.type)
×
131
    {
132
        // Altes S2-Mapformat von BB
133
        case MapType::OldMap:
×
134
        {
135
            libsiedler2::Archiv map;
×
136

137
            // Karteninformationen laden
138
            if(libsiedler2::loader::LoadMAP(mapinfo.filepath, map, true) != 0)
×
139
            {
140
                LOG.write("GameServer::Start: ERROR: Map %1%, couldn't load header!\n") % mapinfo.filepath;
×
141
                return false;
×
142
            }
143
            const libsiedler2::ArchivItem_Map_Header& header =
144
              checkedCast<const libsiedler2::ArchivItem_Map*>(map.get(0))->getHeader();
×
145

146
            playerInfos.resize(header.getNumPlayers());
×
147
            mapinfo.title = s25util::ansiToUTF8(header.getName());
×
148
            ggs_.LoadSettings();
×
149
            currentGF = 0;
×
150
        }
151
        break;
×
152
        // Gespeichertes Spiel
153
        case MapType::Savegame:
×
154
        {
155
            Savegame save;
×
156

157
            if(!save.Load(mapinfo.filepath, SaveGameDataToLoad::HeaderAndSettings))
×
158
                return false;
×
159

160
            // Spieleranzahl
161
            playerInfos.resize(save.GetNumPlayers());
×
162
            mapinfo.title = save.GetMapName();
×
163

164
            for(unsigned i = 0; i < playerInfos.size(); ++i)
×
165
            {
166
                playerInfos[i] = JoinPlayerInfo(save.GetPlayer(i));
×
167
                // If it was a human we make it free, so someone can join
168
                if(playerInfos[i].ps == PlayerState::Occupied)
×
169
                    playerInfos[i].ps = PlayerState::Free;
×
170
            }
171

172
            ggs_ = save.ggs;
×
173
            currentGF = save.start_gf;
×
174
        }
175
        break;
×
176
    }
177

178
    if(playerInfos.empty())
×
179
    {
180
        LOG.write("Map %1% has no players!\n") % mapinfo.filepath;
×
181
        return false;
×
182
    }
183

184
    if(!mapinfo.mapData.CompressFromFile(mapinfo.filepath, &mapinfo.mapChecksum))
×
185
        return false;
×
186

187
    if(map.lua_path.has_value() && !bfs::is_regular_file(*map.lua_path))
×
188
        return false;
×
189

190
    bfs::path luaFilePath = map.lua_path.get_value_or(bfs::path(mapinfo.filepath).replace_extension("lua"));
×
191
    if(bfs::is_regular_file(luaFilePath))
×
192
    {
193
        if(!mapinfo.luaData.CompressFromFile(luaFilePath, &mapinfo.luaChecksum))
×
194
            return false;
×
195
        mapinfo.luaFilepath = luaFilePath;
×
196
    } else
197
        RTTR_Assert(mapinfo.luaFilepath.empty() && mapinfo.luaChecksum == 0);
×
198

199
    if(!mapinfo.verifySize())
×
200
    {
201
        LOG.write("Map %1% is to large!\n") % mapinfo.filepath;
×
202
        return false;
×
203
    }
204

205
    // ab in die Konfiguration
206
    state = ServerState::Config;
×
207

208
    // und das socket in listen-modus schicken
209
    if(!serversocket.Listen(config.port, config.ipv6, csi.use_upnp))
×
210
    {
211
        LOG.write("GameServer::Start: ERROR: Listening on port %d failed!\n") % config.port;
×
212
        LOG.writeLastError("Fehler");
×
213
        return false;
×
214
    }
215

216
    if(config.servertype == ServerType::LAN)
×
217
        lanAnnouncer.Start();
×
218
    else if(config.servertype == ServerType::Lobby)
×
219
    {
220
        LOBBYCLIENT.AddServer(config.gamename, mapinfo.title, (config.password.length() != 0), config.port);
×
221
        LOBBYCLIENT.AddListener(this);
×
222
    }
223
    AnnounceStatusChange();
×
224

225
    return true;
×
226
}
227

228
unsigned GameServer::GetNumFilledSlots() const
×
229
{
230
    unsigned numFilled = 0;
×
231
    for(const JoinPlayerInfo& player : playerInfos)
×
232
    {
233
        if(player.ps != PlayerState::Free)
×
234
            ++numFilled;
×
235
    }
236
    return numFilled;
×
237
}
238

239
void GameServer::AnnounceStatusChange()
×
240
{
241
    if(config.servertype == ServerType::LAN)
×
242
    {
243
        LanGameInfo info;
×
244
        info.name = config.gamename;
×
245
        info.hasPwd = !config.password.empty();
×
246
        info.map = mapinfo.title;
×
247
        info.curNumPlayers = GetNumFilledSlots();
×
248
        info.maxNumPlayers = playerInfos.size();
×
249
        info.port = config.port;
×
250
        info.isIPv6 = config.ipv6;
×
251
        info.version = rttr::version::GetReadableVersion();
×
252
        info.revision = rttr::version::GetRevision();
×
253
        Serializer ser;
×
254
        info.Serialize(ser);
×
255
        lanAnnouncer.SetPayload(ser.GetData(), ser.GetLength());
×
256
    } else if(config.servertype == ServerType::Lobby)
×
257
    {
258
        if(LOBBYCLIENT.IsIngame())
×
259
            LOBBYCLIENT.UpdateServerNumPlayers(GetNumFilledSlots(), playerInfos.size());
×
260
    }
261
}
×
262

263
void GameServer::LC_Status_Error(const std::string& /*error*/)
×
264
{
265
    // Error during adding of server to lobby -> Stop
266
    Stop();
×
267
}
×
268

269
void GameServer::LC_Created()
×
270
{
271
    // All good -> Don't listen anymore
272
    LOBBYCLIENT.RemoveListener(this);
×
273
    AnnounceStatusChange();
×
274
}
×
275

276
///////////////////////////////////////////////////////////////////////////////
277
// Hauptschleife
278
void GameServer::Run()
×
279
{
280
    if(state == ServerState::Stopped)
×
281
        return;
×
282

283
    // auf tote Clients prüfen
284
    ClientWatchDog();
×
285

286
    // auf neue Clients warten
287
    if(state == ServerState::Config)
×
288
        RunStateConfig();
×
289
    else if(state == ServerState::Loading)
×
290
        RunStateLoading();
×
291
    else if(state == ServerState::Game)
×
292
        RunStateGame();
×
293

294
    // post zustellen
295
    FillPlayerQueues();
×
296

297
    // Execute messages
298
    for(GameServerPlayer& player : networkPlayers)
×
299
    {
300
        // Ignore kicked players
301
        if(!player.socket.isValid())
×
302
            continue;
×
303
        player.executeMsgs(*this);
×
304
    }
305
    // Send afterwards as most messages are relayed which should be done as fast as possible
306
    for(GameServerPlayer& player : networkPlayers)
×
307
    {
308
        // Ignore kicked players
309
        if(!player.socket.isValid())
×
310
            continue;
×
311
        player.sendMsgs(10);
×
312
    }
313
    helpers::erase_if(networkPlayers, [](const auto& player) { return !player.socket.isValid(); });
×
314

315
    lanAnnouncer.Run();
×
316
}
317

318
void GameServer::RunStateConfig()
×
319
{
320
    WaitForClients();
×
321
    if(countdown.IsActive() && countdown.Update())
×
322
    {
323
        // nun echt starten
324
        if(!countdown.IsActive())
×
325
        {
326
            if(!StartGame())
×
327
            {
328
                Stop();
×
329
                return;
×
330
            }
331
        } else
332
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
333
    }
334
}
335

336
void GameServer::RunStateLoading()
×
337
{
338
    if(!nwfInfo.isReady())
×
339
    {
340
        if(SteadyClock::now() - loadStartTime > std::chrono::seconds(LOAD_TIMEOUT))
×
341
        {
342
            for(const NWFPlayerInfo& player : nwfInfo.getPlayerInfos())
×
343
            {
344
                if(player.isLagging)
×
345
                    KickPlayer(player.id, KickReason::PingTimeout, __LINE__);
×
346
            }
347
        }
348
        return;
×
349
    }
350
    LOG.write("SERVER: Game loaded by all players after %1%\n")
×
351
      % helpers::withUnit(std::chrono::duration_cast<std::chrono::seconds>(SteadyClock::now() - loadStartTime));
×
352
    // The first NWF is ready. Server has to set up "missing" commands so every future command is for the correct NWF as
353
    // specified with cmdDelay. We have commands for NWF 0. When clients execute this they will send the commands for
354
    // NWF cmdDelay. So commands for NWF 1..cmdDelay-1 are missing. Do this here and before the NWFDone is sent,
355
    // otherwise we might get them in a wrong order when messages are sent asynchronously
356
    for(unsigned i = 1; i < nwfInfo.getCmdDelay(); i++)
×
357
    {
358
        for(const NWFPlayerInfo& player : nwfInfo.getPlayerInfos())
×
359
        {
360
            GameMessage_GameCommand msg(player.id, nwfInfo.getPlayerCmds(player.id).checksum,
×
361
                                        std::vector<gc::GameCommandPtr>());
×
362
            SendToAll(msg);
×
363
            nwfInfo.addPlayerCmds(player.id, msg.cmds);
×
364
        }
365
    }
366

367
    NWFServerInfo serverInfo = nwfInfo.getServerInfo();
×
368
    // Send cmdDelay NWFDone messages
369
    // First send the OK for NWF 0 which is also the game ready command
370
    // Note: Do not store. It already is in NWFInfo
371
    SendToAll(GameMessage_Server_NWFDone(serverInfo.gf, serverInfo.newGFLen, serverInfo.nextNWF));
×
372
    RTTR_Assert(framesinfo.nwf_length > 0);
×
373
    // Then the remaining OKs for the commands sent above
374
    for(unsigned i = 1; i < nwfInfo.getCmdDelay(); i++)
×
375
    {
376
        serverInfo.gf = serverInfo.nextNWF;
×
377
        serverInfo.nextNWF += framesinfo.nwf_length;
×
378
        SendNWFDone(serverInfo);
×
379
    }
380

381
    // And go!
382
    framesinfo.lastTime = FramesInfo::UsedClock::now();
×
383
    state = ServerState::Game;
×
384
}
385

386
void GameServer::RunStateGame()
×
387
{
388
    if(!framesinfo.isPaused)
×
389
        ExecuteGameFrame();
×
390
}
×
391

392
///////////////////////////////////////////////////////////////////////////////
393
// stoppt den server
394
void GameServer::Stop()
×
395
{
396
    if(state == ServerState::Stopped)
×
397
        return;
×
398

399
    // player verabschieden
400
    playerInfos.clear();
×
401
    networkPlayers.clear();
×
402

403
    // aufräumen
404
    framesinfo.Clear();
×
405
    config.Clear();
×
406
    mapinfo.Clear();
×
407
    countdown.Stop();
×
408

409
    // laden dicht machen
410
    serversocket.Close();
×
411
    // clear jump target
412
    skiptogf = 0;
×
413

414
    // clear async logs
415
    asyncLogs.clear();
×
416

417
    lanAnnouncer.Stop();
×
418

419
    if(LOBBYCLIENT.IsLoggedIn()) // steht die Lobbyverbindung noch?
×
420
        LOBBYCLIENT.DeleteServer();
×
421
    LOBBYCLIENT.RemoveListener(this);
×
422

423
    // status
424
    state = ServerState::Stopped;
×
425
    LOG.write("server state changed to stop\n");
×
426
}
427

428
// Check if there are players that have not been assigned a team but only a random team.
429
// Those players are assigned a team now optionally trying to balance the number of players per team.
430
// Returns true iff players have been assigned.
431
bool GameServer::assignPlayersOfRandomTeams(std::vector<JoinPlayerInfo>& playerInfos)
24✔
432
{
433
    static_assert(NUM_TEAMS == 4, "Expected exactly 4 playable teams!");
434
    RTTR_Assert(playerInfos.size() <= MAX_PLAYERS);
24✔
435

436
    using boost::container::static_vector;
437
    using PlayerIndex = unsigned;
438
    using TeamIndex = unsigned;
439
    const auto teamIdxToTeam = [](const TeamIndex teamNum) {
83✔
440
        RTTR_Assert(teamNum < NUM_TEAMS);
83✔
441
        return Team(static_cast<TeamIndex>(Team::Team1) + teamNum);
83✔
442
    };
443

444
    std::array<unsigned, NUM_TEAMS> numPlayersInTeam{};
24✔
445
    struct AssignPlayer
446
    {
447
        PlayerIndex player;
448
        static_vector<TeamIndex, NUM_TEAMS> possibleTeams;
449
        TeamIndex chosenTeam = 0;
450
    };
451

452
    static_vector<AssignPlayer, MAX_PLAYERS> playersToAssign;
×
453
    auto rng = helpers::getRandomGenerator();
24✔
454

455
    bool playerWasAssigned = false;
24✔
456

457
    // Assign (fully) random teams, count players in team and sort into playersToAssign
458
    for(PlayerIndex player = 0; player < playerInfos.size(); ++player)
162✔
459
    {
460
        auto& playerInfo = playerInfos[player];
138✔
461
        if(playerInfo.team == Team::Random)
138✔
462
        {
463
            const TeamIndex randTeam = std::uniform_int_distribution<TeamIndex>{0, NUM_TEAMS - 1u}(rng);
2✔
464
            playerInfo.team = teamIdxToTeam(randTeam);
2✔
465
            playerWasAssigned = true;
2✔
466
        }
467
        switch(playerInfo.team)
138✔
468
        {
469
            case Team::Team1: ++numPlayersInTeam[0]; break;
25✔
470
            case Team::Team2: ++numPlayersInTeam[1]; break;
7✔
471
            case Team::Team3: ++numPlayersInTeam[2]; break;
19✔
472
            case Team::Team4: ++numPlayersInTeam[3]; break;
4✔
473
            case Team::Random1To2: playersToAssign.emplace_back(AssignPlayer{player, {0, 1}}); break;
57✔
474
            case Team::Random1To3: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2}}); break;
144✔
475
            case Team::Random1To4: playersToAssign.emplace_back(AssignPlayer{player, {0, 1, 2, 3}}); break;
42✔
476
            case Team::Random: RTTR_Assert(false); break;
×
477
            case Team::None: break;
2✔
478
        }
479
    }
480

481
    // To make the teams as even as possible we start to assign the most constrained players first
482
    std::sort(playersToAssign.begin(), playersToAssign.end(), [](const AssignPlayer& lhs, const AssignPlayer& rhs) {
24✔
483
        return lhs.possibleTeams.size() < rhs.possibleTeams.size();
378✔
484
    });
485

486
    // Put each player into a random team with the currently least amount of players using the possible teams only
487
    for(AssignPlayer& player : playersToAssign)
234✔
488
    {
489
        // Determine the teams with the minima size for the currently possible teams and choose one randomly
490
        unsigned minNextTeamSize = std::numeric_limits<unsigned>::max();
81✔
491
        static_vector<TeamIndex, NUM_TEAMS> teamsForNextPlayer;
×
492
        for(const TeamIndex team : player.possibleTeams)
719✔
493
        {
494
            if(minNextTeamSize > numPlayersInTeam[team])
238✔
495
            {
496
                teamsForNextPlayer.clear();
497
                teamsForNextPlayer.push_back(team);
498
                minNextTeamSize = numPlayersInTeam[team];
123✔
499
            } else if(minNextTeamSize == numPlayersInTeam[team])
115✔
500
                teamsForNextPlayer.push_back(team);
501
        }
502
        player.chosenTeam = helpers::getRandomElement(rng, teamsForNextPlayer);
81✔
503

504
        ++numPlayersInTeam[player.chosenTeam];
81✔
505
        playerWasAssigned = true;
81✔
506
    }
507
    // Now the teams are as even as possible and the uneven team(s) is a random one within the constraints
508
    // To have some more randomness we swap players within their constraints
509
    std::shuffle(playersToAssign.begin(), playersToAssign.end(), rng);
24✔
510
    for(auto it = playersToAssign.begin(); it != playersToAssign.end(); ++it)
186✔
511
    {
512
        // Search for a random player with which we can swap, including ourselfes
513
        // Go only forward to avoid back-swapping
514
        static_vector<decltype(it), MAX_PLAYERS> possibleSwapTargets;
×
515
        for(auto it2 = it; it2 != playersToAssign.end(); ++it2)
513✔
516
        {
517
            if(helpers::contains(it->possibleTeams, it2->chosenTeam)
432✔
518
               && helpers::contains(it2->possibleTeams, it->chosenTeam))
616✔
519
                possibleSwapTargets.push_back(it2);
520
        }
521
        const auto itSwapTarget = helpers::getRandomElement(rng, possibleSwapTargets);
81✔
522
        std::swap(it->chosenTeam, itSwapTarget->chosenTeam);
162✔
523
        playerInfos[it->player].team = teamIdxToTeam(it->chosenTeam);
162✔
524
    }
525

526
    return playerWasAssigned;
48✔
527
}
528

529
/**
530
 *  startet das Spiel.
531
 */
532
bool GameServer::StartGame()
×
533
{
534
    lanAnnouncer.Stop();
×
535

536
    // Finalize the team selection for unassigned players.
537
    if(assignPlayersOfRandomTeams(playerInfos))
×
538
        SendToAll(GameMessage_Player_List(playerInfos));
×
539

540
    // Bei Savegames wird der Startwert von den Clients aus der Datei gelesen!
541
    unsigned random_init;
542
    if(mapinfo.type == MapType::Savegame)
×
543
        random_init = 0;
×
544
    else
545
        random_init = static_cast<unsigned>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
×
546

547
    nwfInfo.init(currentGF, 3);
×
548

549
    // Send start first, then load the rest
550
    SendToAll(GameMessage_Server_Start(random_init, nwfInfo.getNextNWF(), nwfInfo.getCmdDelay()));
×
551
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_SERVER_START(%d)\n") % random_init;
×
552

553
    // Höchsten Ping ermitteln
554
    unsigned highest_ping = 0;
×
555
    for(const JoinPlayerInfo& player : playerInfos)
×
556
    {
557
        if(player.ps == PlayerState::Occupied)
×
558
        {
559
            if(player.ping > highest_ping)
×
560
                highest_ping = player.ping;
×
561
        }
562
    }
563

564
    framesinfo.gfLengthReq = framesinfo.gf_length = SPEED_GF_LENGTHS[ggs_.speed];
×
565

566
    // NetworkFrame-Länge bestimmen, je schlechter (also höher) die Pings, desto länger auch die Framelänge
567
    framesinfo.nwf_length = CalcNWFLenght(FramesInfo::milliseconds32_t(highest_ping));
×
568

569
    LOG.write("SERVER: Using gameframe length of %1%\n") % helpers::withUnit(framesinfo.gf_length);
×
570
    LOG.write("SERVER: Using networkframe length of %1% GFs (%2%)\n") % framesinfo.nwf_length
×
571
      % helpers::withUnit(framesinfo.nwf_length * framesinfo.gf_length);
×
572

573
    for(unsigned id = 0; id < playerInfos.size(); id++)
×
574
    {
575
        if(playerInfos[id].isUsed())
×
576
            nwfInfo.addPlayer(id);
×
577
    }
578

579
    // Add server info so nwfInfo can be ready but do NOT send it yet, as we wait for the player commands before sending
580
    // the done msg
581
    nwfInfo.addServerInfo(NWFServerInfo(currentGF, framesinfo.gf_length / FramesInfo::milliseconds32_t(1),
×
582
                                        currentGF + framesinfo.nwf_length));
×
583

584
    state = ServerState::Loading;
×
585
    loadStartTime = SteadyClock::now();
×
586

587
    return true;
×
588
}
589

590
unsigned GameServer::CalcNWFLenght(FramesInfo::milliseconds32_t minDuration) const
×
591
{
592
    constexpr unsigned maxNumGF = 20;
×
593
    for(unsigned i = 1; i < maxNumGF; ++i)
×
594
    {
595
        if(i * framesinfo.gf_length >= minDuration)
×
596
            return i;
×
597
    }
598
    return maxNumGF;
×
599
}
600

601
void GameServer::SendNWFDone(const NWFServerInfo& info)
×
602
{
603
    nwfInfo.addServerInfo(info);
×
604
    SendToAll(GameMessage_Server_NWFDone(info.gf, info.newGFLen, info.nextNWF));
×
605
}
×
606

607
/**
608
 *  Nachricht an Alle
609
 */
610
void GameServer::SendToAll(const GameMessage& msg)
×
611
{
612
    for(GameServerPlayer& player : networkPlayers)
×
613
    {
614
        // ist der Slot Belegt, dann Nachricht senden
615
        if(player.isActive())
×
616
            player.sendMsgAsync(msg.clone());
×
617
    }
618
}
×
619

620
void GameServer::KickPlayer(uint8_t playerId, KickReason cause, uint32_t param)
×
621
{
622
    if(playerId >= playerInfos.size())
×
623
        return;
×
624
    JoinPlayerInfo& playerInfo = playerInfos[playerId];
×
625
    GameServerPlayer* player = GetNetworkPlayer(playerId);
×
626
    if(player)
×
627
        player->closeConnection();
×
628
    // Non-existing or connecting player
629
    if(!playerInfo.isUsed())
×
630
        return;
×
631
    playerInfo.ps = PlayerState::Free;
×
632

633
    SendToAll(GameMessage_Player_Kicked(playerId, cause, param));
×
634

635
    // If we are ingame, replace by KI
636
    if(state == ServerState::Game || state == ServerState::Loading)
×
637
    {
638
        playerInfo.ps = PlayerState::AI;
×
639
        playerInfo.aiInfo = AI::Info(AI::Type::Dummy);
×
640
    } else
641
        CancelCountdown();
×
642

643
    AnnounceStatusChange();
×
644
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYERKICKED(%d,%d,%d)\n") % unsigned(playerId) % unsigned(cause)
×
645
      % unsigned(param);
×
646
}
647

648
///////////////////////////////////////////////////////////////////////////////
649
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
650
void GameServer::ClientWatchDog()
×
651
{
652
    SocketSet set;
×
653
    set.Clear();
×
654

655
    // sockets zum set hinzufügen
656
    for(GameServerPlayer& player : networkPlayers)
×
657
        set.Add(player.socket);
×
658

659
    // auf fehler prüfen
660
    if(set.Select(0, 2) > 0)
×
661
    {
662
        for(const GameServerPlayer& player : networkPlayers)
×
663
        {
664
            if(set.InSet(player.socket))
×
665
            {
666
                LOG.write(_("SERVER: Error on socket of player %1%, bye bye!\n")) % player.playerId;
×
667
                KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
668
            }
669
        }
670
    }
671

672
    for(GameServerPlayer& player : networkPlayers)
×
673
    {
674
        if(player.hasTimedOut())
×
675
        {
676
            LOG.write(_("SERVER: Reserved slot %1% freed due to timeout\n")) % player.playerId;
×
677
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
678
        } else
679
            player.doPing();
×
680
    }
681
}
×
682

683
void GameServer::ExecuteGameFrame()
×
684
{
685
    RTTR_Assert(state == ServerState::Game);
×
686

687
    FramesInfo::UsedClock::time_point currentTime = FramesInfo::UsedClock::now();
×
688
    FramesInfo::milliseconds32_t passedTime =
689
      std::chrono::duration_cast<FramesInfo::milliseconds32_t>(currentTime - framesinfo.lastTime);
×
690

691
    // prüfen ob GF vergangen
692
    if(passedTime >= framesinfo.gf_length || skiptogf > currentGF)
×
693
    {
694
        // NWF vergangen?
695
        if(currentGF == nwfInfo.getNextNWF())
×
696
        {
697
            if(CheckForLaggingPlayers())
×
698
            {
699
                // Check for kicking every second
700
                static FramesInfo::UsedClock::time_point lastLagKickTime;
701
                if(currentTime - lastLagKickTime >= std::chrono::seconds(1))
×
702
                {
703
                    lastLagKickTime = currentTime;
×
704
                    CheckAndKickLaggingPlayers();
×
705
                }
706
                // Skip the rest
707
                return;
×
708
            } else
709
                ExecuteNWF();
×
710
        }
711
        // Advance GF
712
        ++currentGF;
×
713
        // Normally we set lastTime = curTime (== lastTime + passedTime) where passedTime is ideally 1 GF
714
        // But we might got called late, so we advance the time by 1 GF anyway so in that case we execute the next GF a
715
        // bit earlier. Exception: We lag many GFs behind, then we advance by the full passedTime - 1 GF which means we
716
        // are now only 1 GF behind and execute that on the next call
717
        if(passedTime <= 4 * framesinfo.gf_length)
×
718
            passedTime = framesinfo.gf_length;
×
719
        else
720
            passedTime -= framesinfo.gf_length;
×
721
        framesinfo.lastTime += passedTime;
×
722
    }
723
}
724

725
void GameServer::ExecuteNWF()
×
726
{
727
    // Check for asyncs
728
    if(CheckForAsync())
×
729
    {
730
        // Pause game
731
        RTTR_Assert(!framesinfo.isPaused);
×
732
        SetPaused(true);
×
733

734
        // Notify players
735
        std::vector<unsigned> checksumHashes;
×
736
        for(const GameServerPlayer& player : networkPlayers)
×
737
            checksumHashes.push_back(nwfInfo.getPlayerCmds(player.playerId).checksum.getHash());
×
738
        SendToAll(GameMessage_Server_Async(checksumHashes));
×
739

740
        // Request async logs
741
        for(GameServerPlayer& player : networkPlayers)
×
742
        {
743
            asyncLogs.push_back(AsyncLog(player.playerId, nwfInfo.getPlayerCmds(player.playerId).checksum));
×
744
            player.sendMsgAsync(new GameMessage_GetAsyncLog());
×
745
        }
746
    }
747
    const NWFServerInfo serverInfo = nwfInfo.getServerInfo();
×
748
    RTTR_Assert(serverInfo.gf == currentGF);
×
749
    RTTR_Assert(serverInfo.nextNWF > currentGF);
×
750
    // First save old values
751
    unsigned lastNWF = nwfInfo.getLastNWF();
×
752
    FramesInfo::milliseconds32_t oldGFLen = framesinfo.gf_length;
×
753
    nwfInfo.execute(framesinfo);
×
754
    if(oldGFLen != framesinfo.gf_length)
×
755
    {
756
        LOG.write(_("SERVER: At GF %1%: Speed changed from %2% to %3%. NWF %4%\n")) % currentGF
×
757
          % helpers::withUnit(oldGFLen) % helpers::withUnit(framesinfo.gf_length) % framesinfo.nwf_length;
×
758
    }
759
    NWFServerInfo newInfo(lastNWF, framesinfo.gfLengthReq / FramesInfo::milliseconds32_t(1),
×
760
                          lastNWF + framesinfo.nwf_length);
×
761
    if(framesinfo.gfLengthReq != framesinfo.gf_length)
×
762
    {
763
        // Speed will change, adjust nwf length so the time will stay constant
764
        using namespace std::chrono;
765
        using MsDouble = duration<double, std::milli>;
766
        double newNWFLen =
767
          framesinfo.nwf_length * framesinfo.gf_length / duration_cast<MsDouble>(framesinfo.gfLengthReq);
×
768
        newInfo.nextNWF = lastNWF + std::max(1u, helpers::iround<unsigned>(newNWFLen));
×
769
    }
770
    SendNWFDone(newInfo);
×
771
}
×
772

773
bool GameServer::CheckForAsync()
×
774
{
775
    if(networkPlayers.empty())
×
776
        return false;
×
777
    bool isAsync = false;
×
778
    const AsyncChecksum& refChecksum = nwfInfo.getPlayerCmds(networkPlayers.front().playerId).checksum;
×
779
    for(const GameServerPlayer& player : networkPlayers)
×
780
    {
781
        const AsyncChecksum& curChecksum = nwfInfo.getPlayerCmds(player.playerId).checksum;
×
782

783
        // Checksummen nicht gleich?
784
        if(curChecksum != refChecksum)
×
785
        {
786
            LOG.write(_("Async at GF %1% of player %2% vs %3%. Checksums:\n%4%\n%5%\n\n")) % currentGF % player.playerId
×
787
              % networkPlayers.front().playerId % curChecksum % refChecksum;
×
788
            isAsync = true;
×
789
        }
790
    }
791
    return isAsync;
×
792
}
793

794
void GameServer::CheckAndKickLaggingPlayers()
×
795
{
796
    for(const GameServerPlayer& player : networkPlayers)
×
797
    {
798
        const unsigned timeOut = player.getLagTimeOut();
×
799
        if(timeOut == 0)
×
800
            KickPlayer(player.playerId, KickReason::PingTimeout, __LINE__);
×
801
        else if(timeOut <= 30
×
802
                && (timeOut % 5 == 0
×
803
                    || timeOut < 5)) // Notify every 5s if max 30s are remaining, if less than 5s notify every second
×
804
            LOG.write(_("SERVER: Kicking player %1% in %2% seconds\n")) % player.playerId % timeOut;
×
805
    }
806
}
×
807

808
bool GameServer::CheckForLaggingPlayers()
×
809
{
810
    if(nwfInfo.isReady())
×
811
        return false;
×
812
    for(GameServerPlayer& player : networkPlayers)
×
813
    {
814
        if(nwfInfo.getPlayerInfo(player.playerId).isLagging)
×
815
            player.setLagging();
×
816
    }
817
    return true;
×
818
}
819

820
///////////////////////////////////////////////////////////////////////////////
821
// testet, ob in der Verbindungswarteschlange Clients auf Verbindung warten
822
void GameServer::WaitForClients()
×
823
{
824
    SocketSet set;
×
825

826
    set.Add(serversocket);
×
827
    if(set.Select(0, 0) > 0)
×
828
    {
829
        RTTR_Assert(set.InSet(serversocket));
×
830
        Socket socket = serversocket.Accept();
×
831

832
        // Verbindung annehmen
833
        if(!socket.isValid())
×
834
            return;
×
835

836
        unsigned newPlayerId = GameMessageWithPlayer::NO_PLAYER_ID;
×
837
        // Geeigneten Platz suchen
838
        for(unsigned playerId = 0; playerId < playerInfos.size(); ++playerId)
×
839
        {
840
            if(playerInfos[playerId].ps == PlayerState::Free && !GetNetworkPlayer(playerId))
×
841
            {
842
                networkPlayers.push_back(GameServerPlayer(playerId, socket));
×
843
                newPlayerId = playerId;
×
844
                break;
×
845
            }
846
        }
847

848
        GameMessage_Player_Id msg(newPlayerId);
×
849
        MessageHandler::send(socket, msg);
×
850

851
        // war kein platz mehr frei, wenn ja dann verbindung trennen?
852
        if(newPlayerId == 0xFFFFFFFF)
×
853
            socket.Close();
×
854
    }
855
}
856

857
///////////////////////////////////////////////////////////////////////////////
858
// füllt die warteschlangen mit "paketen"
859
void GameServer::FillPlayerQueues()
×
860
{
861
    SocketSet set;
×
862
    bool msgReceived = false;
×
863

864
    // erstmal auf Daten überprüfen
865
    do
×
866
    {
867
        // sockets zum set hinzufügen
868
        for(const GameServerPlayer& player : networkPlayers)
×
869
            set.Add(player.socket);
×
870

871
        msgReceived = false;
×
872

873
        // ist eines der Sockets im Set lesbar?
874
        if(set.Select(0, 0) > 0)
×
875
        {
876
            for(GameServerPlayer& player : networkPlayers)
×
877
            {
878
                if(set.InSet(player.socket))
×
879
                {
880
                    // nachricht empfangen
881
                    if(!player.receiveMsgs())
×
882
                    {
883
                        LOG.write(_("SERVER: Receiving Message for player %1% failed, kicking...\n")) % player.playerId;
×
884
                        KickPlayer(player.playerId, KickReason::ConnectionLost, __LINE__);
×
885
                    } else
886
                        msgReceived = true;
×
887
                }
888
            }
889
        }
890
    } while(msgReceived);
891
}
×
892

893
///////////////////////////////////////////////////////////////////////////////
894
// pongnachricht
895
bool GameServer::OnGameMessage(const GameMessage_Pong& msg)
×
896
{
897
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
898
    if(player)
×
899
    {
900
        unsigned ping = player->calcPingTime();
×
901
        if(ping == 0u)
×
902
            return true;
×
903
        playerInfos[msg.senderPlayerID].ping = ping;
×
904
        SendToAll(GameMessage_Player_Ping(msg.senderPlayerID, ping));
×
905
    }
906
    return true;
×
907
}
908

909
///////////////////////////////////////////////////////////////////////////////
910
// servertype
911
bool GameServer::OnGameMessage(const GameMessage_Server_Type& msg)
×
912
{
913
    if(state != ServerState::Config)
×
914
    {
915
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
916
        return true;
×
917
    }
918

919
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
920
    if(!player)
×
921
        return true;
×
922

923
    auto typeok = GameMessage_Server_TypeOK::StatusCode::Ok;
×
924
    if(msg.type != config.servertype)
×
925
        typeok = GameMessage_Server_TypeOK::StatusCode::InvalidServerType;
×
926
    else if(msg.revision != rttr::version::GetRevision())
×
927
        typeok = GameMessage_Server_TypeOK::StatusCode::WrongVersion;
×
928

929
    player->sendMsg(GameMessage_Server_TypeOK(typeok, rttr::version::GetRevision()));
×
930

931
    if(typeok != GameMessage_Server_TypeOK::StatusCode::Ok)
×
932
        KickPlayer(msg.senderPlayerID, KickReason::ConnectionLost, __LINE__);
×
933
    return true;
×
934
}
935

936
/**
937
 *  Server-Passwort-Nachricht
938
 */
939
bool GameServer::OnGameMessage(const GameMessage_Server_Password& msg)
×
940
{
941
    if(state != ServerState::Config)
×
942
    {
943
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
944
        return true;
×
945
    }
946

947
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
948
    if(!player)
×
949
        return true;
×
950

951
    std::string passwordok = (config.password == msg.password ? "true" : "false");
×
952
    if(msg.password == config.hostPassword)
×
953
    {
954
        passwordok = "true";
×
955
        playerInfos[msg.senderPlayerID].isHost = true;
×
956
    } else
957
        playerInfos[msg.senderPlayerID].isHost = false;
×
958

959
    player->sendMsgAsync(new GameMessage_Server_Password(passwordok));
×
960

961
    if(passwordok == "false")
×
962
        KickPlayer(msg.senderPlayerID, KickReason::WrongPassword, __LINE__);
×
963
    return true;
×
964
}
965

966
/**
967
 *  Chat-Nachricht.
968
 */
969
bool GameServer::OnGameMessage(const GameMessage_Chat& msg)
×
970
{
971
    int playerID = GetTargetPlayer(msg);
×
972
    if(playerID >= 0)
×
973
        SendToAll(GameMessage_Chat(playerID, msg.destination, msg.text));
×
974
    return true;
×
975
}
976

977
bool GameServer::OnGameMessage(const GameMessage_Player_State& msg)
×
978
{
979
    if(state != ServerState::Config)
×
980
    {
981
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
982
        return true;
×
983
    }
984
    // Can't do this. Have to have a joined player
985
    if(msg.ps == PlayerState::Occupied)
×
986
        return true;
×
987

988
    int playerID = GetTargetPlayer(msg);
×
989
    if(playerID < 0)
×
990
        return true;
×
991
    JoinPlayerInfo& player = playerInfos[playerID];
×
992
    const PlayerState oldPs = player.ps;
×
993
    // Can't change self
994
    if(playerID != msg.senderPlayerID)
×
995
    {
996
        // oh ein spieler, weg mit ihm!
997
        if(GetNetworkPlayer(playerID))
×
998
            KickPlayer(playerID, KickReason::NoCause, __LINE__);
×
999

1000
        if(mapinfo.type == MapType::Savegame)
×
1001
        {
1002
            // For savegames we cannot set anyone on a locked slot as the player does not exist on the map
1003
            if(player.ps != PlayerState::Locked)
×
1004
            {
1005
                // And we don't lock!
1006
                player.ps = msg.ps == PlayerState::Locked ? PlayerState::Free : msg.ps;
×
1007
                player.aiInfo = msg.aiInfo;
×
1008
            }
1009
        } else
1010
        {
1011
            player.ps = msg.ps;
×
1012
            player.aiInfo = msg.aiInfo;
×
1013
        }
1014
        if(player.ps == PlayerState::Free && config.servertype == ServerType::Local)
×
1015
        {
1016
            player.ps = PlayerState::AI;
×
1017
            player.aiInfo = AI::Info(AI::Type::Default);
×
1018
        }
1019
    }
1020
    // Even when nothing changed we send the data because the other players might have expected a change
1021

1022
    if(player.ps == PlayerState::AI)
×
1023
    {
1024
        player.SetAIName(playerID);
×
1025
        SendToAll(GameMessage_Player_Name(playerID, player.name));
×
1026
    }
1027
    // If slot is filled, check current color
1028
    if(player.isUsed())
×
1029
        CheckAndSetColor(playerID, player.color);
×
1030
    SendToAll(GameMessage_Player_State(playerID, player.ps, player.aiInfo));
×
1031

1032
    if(oldPs != player.ps)
×
1033
        player.isReady = (player.ps == PlayerState::AI);
×
1034
    SendToAll(GameMessage_Player_Ready(playerID, player.isReady));
×
1035
    PlayerDataChanged(playerID);
×
1036
    AnnounceStatusChange();
×
1037
    return true;
×
1038
}
1039

1040
///////////////////////////////////////////////////////////////////////////////
1041
// Spielername
1042
bool GameServer::OnGameMessage(const GameMessage_Player_Name& msg)
×
1043
{
1044
    if(state != ServerState::Config)
×
1045
    {
1046
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1047
        return true;
×
1048
    }
1049
    int playerID = GetTargetPlayer(msg);
×
1050
    if(playerID < 0)
×
1051
        return true;
×
1052

1053
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_PLAYER_NAME(%s)\n") % playerID % msg.playername;
×
1054

1055
    playerInfos[playerID].name = msg.playername;
×
1056
    SendToAll(GameMessage_Player_Name(playerID, msg.playername));
×
1057
    PlayerDataChanged(playerID);
×
1058

1059
    return true;
×
1060
}
1061

1062
///////////////////////////////////////////////////////////////////////////////
1063
// Nation weiterwechseln
1064
bool GameServer::OnGameMessage(const GameMessage_Player_Nation& msg)
×
1065
{
1066
    if(state != ServerState::Config)
×
1067
    {
1068
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1069
        return true;
×
1070
    }
1071
    int playerID = GetTargetPlayer(msg);
×
1072
    if(playerID < 0)
×
1073
        return true;
×
1074

1075
    playerInfos[playerID].nation = msg.nation;
×
1076

1077
    SendToAll(GameMessage_Player_Nation(playerID, msg.nation));
×
1078
    PlayerDataChanged(playerID);
×
1079
    return true;
×
1080
}
1081

1082
///////////////////////////////////////////////////////////////////////////////
1083
// Team weiterwechseln
1084
bool GameServer::OnGameMessage(const GameMessage_Player_Team& msg)
×
1085
{
1086
    if(state != ServerState::Config)
×
1087
    {
1088
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1089
        return true;
×
1090
    }
1091
    int playerID = GetTargetPlayer(msg);
×
1092
    if(playerID < 0)
×
1093
        return true;
×
1094

1095
    playerInfos[playerID].team = msg.team;
×
1096

1097
    SendToAll(GameMessage_Player_Team(playerID, msg.team));
×
1098
    PlayerDataChanged(playerID);
×
1099
    return true;
×
1100
}
1101

1102
///////////////////////////////////////////////////////////////////////////////
1103
// Farbe weiterwechseln
1104
bool GameServer::OnGameMessage(const GameMessage_Player_Color& msg)
×
1105
{
1106
    if(state != ServerState::Config)
×
1107
    {
1108
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1109
        return true;
×
1110
    }
1111
    int playerID = GetTargetPlayer(msg);
×
1112
    if(playerID < 0)
×
1113
        return true;
×
1114

1115
    CheckAndSetColor(playerID, msg.color);
×
1116
    PlayerDataChanged(playerID);
×
1117
    return true;
×
1118
}
1119

1120
/**
1121
 *  Spielerstatus wechseln
1122
 */
1123
bool GameServer::OnGameMessage(const GameMessage_Player_Ready& msg)
×
1124
{
1125
    if(state != ServerState::Config)
×
1126
    {
1127
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1128
        return true;
×
1129
    }
1130
    int playerID = GetTargetPlayer(msg);
×
1131
    if(playerID < 0)
×
1132
        return true;
×
1133

1134
    JoinPlayerInfo& player = playerInfos[playerID];
×
1135

1136
    player.isReady = msg.ready;
×
1137

1138
    // countdown ggf abbrechen
1139
    if(!player.isReady && countdown.IsActive())
×
1140
        CancelCountdown();
×
1141

1142
    SendToAll(GameMessage_Player_Ready(playerID, msg.ready));
×
1143
    return true;
×
1144
}
1145

1146
bool GameServer::OnGameMessage(const GameMessage_MapRequest& msg)
×
1147
{
1148
    if(state != ServerState::Config)
×
1149
    {
1150
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1151
        return true;
×
1152
    }
1153
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1154
    if(!player)
×
1155
        return true;
×
1156

1157
    if(msg.requestInfo)
×
1158
    {
1159
        player->sendMsgAsync(new GameMessage_Map_Info(mapinfo.filepath.filename().string(), mapinfo.type,
×
1160
                                                      mapinfo.mapData.uncompressedLength, mapinfo.mapData.data.size(),
×
1161
                                                      mapinfo.luaData.uncompressedLength, mapinfo.luaData.data.size()));
×
1162
    } else if(player->isMapSending())
×
1163
    {
1164
        // Don't send again
1165
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1166
    } else
1167
    {
1168
        // Send map data
1169
        unsigned curPos = 0;
×
1170
        unsigned remainingSize = mapinfo.mapData.data.size();
×
1171
        while(remainingSize)
×
1172
        {
1173
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1174

1175
            player->sendMsgAsync(new GameMessage_Map_Data(true, curPos, &mapinfo.mapData.data[curPos], chunkSize));
×
1176
            curPos += chunkSize;
×
1177
            remainingSize -= chunkSize;
×
1178
        }
1179

1180
        // And lua data (if there is any)
1181
        RTTR_Assert(mapinfo.luaFilepath.empty() == mapinfo.luaData.data.empty());
×
1182
        RTTR_Assert(mapinfo.luaData.data.empty() == (mapinfo.luaData.uncompressedLength == 0));
×
1183
        curPos = 0;
×
1184
        remainingSize = mapinfo.luaData.data.size();
×
1185
        while(remainingSize)
×
1186
        {
1187
            unsigned chunkSize = std::min(MAP_PART_SIZE, remainingSize);
×
1188

1189
            player->sendMsgAsync(new GameMessage_Map_Data(false, curPos, &mapinfo.luaData.data[curPos], chunkSize));
×
1190
            curPos += chunkSize;
×
1191
            remainingSize -= chunkSize;
×
1192
        }
1193
        // estimate time. max 60 chunks/s (currently limited by framerate), assume 50 (~25kb/s)
1194
        auto numChunks = (mapinfo.mapData.data.size() + mapinfo.luaData.data.size()) / MAP_PART_SIZE;
×
1195
        player->setMapSending(std::chrono::seconds(numChunks / 50 + 1));
×
1196
    }
1197
    return true;
×
1198
}
1199

1200
bool GameServer::OnGameMessage(const GameMessage_Map_Checksum& msg)
×
1201
{
1202
    if(state != ServerState::Config)
×
1203
    {
1204
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1205
        return true;
×
1206
    }
1207
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1208
    if(!player)
×
1209
        return true;
×
1210

1211
    bool checksumok = (msg.mapChecksum == mapinfo.mapChecksum && msg.luaChecksum == mapinfo.luaChecksum);
×
1212

1213
    LOG.writeToFile("CLIENT%d >>> SERVER: NMS_MAP_CHECKSUM(%u) expected: %u, ok: %s\n") % unsigned(msg.senderPlayerID)
×
1214
      % msg.mapChecksum % mapinfo.mapChecksum % (checksumok ? "yes" : "no");
×
1215

1216
    // Send response. If map data was not sent yet, the client may retry
1217
    player->sendMsgAsync(new GameMessage_Map_ChecksumOK(checksumok, !player->isMapSending()));
×
1218

1219
    LOG.writeToFile("SERVER >>> CLIENT%d: NMS_MAP_CHECKSUM(%d)\n") % unsigned(msg.senderPlayerID) % checksumok;
×
1220

1221
    if(!checksumok)
×
1222
    {
1223
        if(player->isMapSending())
×
1224
            KickPlayer(msg.senderPlayerID, KickReason::WrongChecksum, __LINE__);
×
1225
    } else
1226
    {
1227
        JoinPlayerInfo& playerInfo = playerInfos[msg.senderPlayerID];
×
1228
        // Used? Then we got this twice or some error happened. Remove him
1229
        if(playerInfo.isUsed())
×
1230
            KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1231
        else
1232
        {
1233
            // Inform others about a new player
1234
            SendToAll(GameMessage_Player_New(msg.senderPlayerID, playerInfo.name));
×
1235

1236
            LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_NEW(%d, %s)\n") % unsigned(msg.senderPlayerID)
×
1237
              % playerInfo.name;
×
1238

1239
            // Mark as used and assign a unique color
1240
            // Do this before sending the player list to avoid sending useless updates
1241
            playerInfo.ps = PlayerState::Occupied;
×
1242
            CheckAndSetColor(msg.senderPlayerID, playerInfo.color);
×
1243

1244
            // Send remaining data and mark as active
1245
            player->sendMsgAsync(new GameMessage_Server_Name(config.gamename));
×
1246
            player->sendMsgAsync(new GameMessage_Player_List(playerInfos));
×
1247
            player->sendMsgAsync(new GameMessage_GGSChange(ggs_));
×
1248
            player->setActive();
×
1249
        }
1250
        AnnounceStatusChange();
×
1251
    }
1252
    return true;
×
1253
}
1254

1255
// speed change message
1256
bool GameServer::OnGameMessage(const GameMessage_Speed& msg)
×
1257
{
1258
    if(state != ServerState::Game)
×
1259
    {
1260
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1261
        return true;
×
1262
    }
1263
    framesinfo.gfLengthReq = FramesInfo::milliseconds32_t(msg.gf_length);
×
1264
    return true;
×
1265
}
1266

1267
bool GameServer::OnGameMessage(const GameMessage_GameCommand& msg)
×
1268
{
1269
    int targetPlayerId = GetTargetPlayer(msg);
×
1270
    if((state != ServerState::Game && state != ServerState::Loading) || targetPlayerId < 0
×
1271
       || (state == ServerState::Loading && !msg.cmds.gcs.empty()))
×
1272
    {
1273
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1274
        return true;
×
1275
    }
1276

1277
    if(!nwfInfo.addPlayerCmds(targetPlayerId, msg.cmds))
×
1278
        return true; // Ignore
×
1279
    GameServerPlayer* player = GetNetworkPlayer(targetPlayerId);
×
1280
    if(player)
×
1281
        player->setNotLagging();
×
1282
    SendToAll(GameMessage_GameCommand(targetPlayerId, msg.cmds.checksum, msg.cmds.gcs));
×
1283

1284
    return true;
×
1285
}
1286

1287
bool GameServer::OnGameMessage(const GameMessage_AsyncLog& msg)
×
1288
{
1289
    if(state != ServerState::Game)
×
1290
    {
1291
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1292
        return true;
×
1293
    }
1294
    bool foundPlayer = false;
×
1295
    for(AsyncLog& log : asyncLogs)
×
1296
    {
1297
        if(log.playerId != msg.senderPlayerID)
×
1298
            continue;
×
1299
        RTTR_Assert(!log.done);
×
1300
        if(log.done)
×
1301
            return true;
×
1302
        foundPlayer = true;
×
1303
        log.addData += msg.addData;
×
1304
        log.randEntries.insert(log.randEntries.end(), msg.entries.begin(), msg.entries.end());
×
1305
        if(msg.last)
×
1306
        {
1307
            LOG.write(_("Received async logs from %1% (%2% entries).\n")) % unsigned(log.playerId)
×
1308
              % log.randEntries.size();
×
1309
            log.done = true;
×
1310
        }
1311
    }
1312
    if(!foundPlayer)
×
1313
    {
1314
        LOG.write(_("Received async log from %1%, but did not expect it!\n")) % unsigned(msg.senderPlayerID);
×
1315
        return true;
×
1316
    }
1317

1318
    // Check if we have all logs
1319
    for(const AsyncLog& log : asyncLogs)
×
1320
    {
1321
        if(!log.done)
×
1322
            return true;
×
1323
    }
1324

1325
    LOG.write(_("Async logs received completely.\n"));
×
1326

1327
    const bfs::path asyncFilePath = SaveAsyncLog();
×
1328
    if(!asyncFilePath.empty())
×
1329
        SendAsyncLog(asyncFilePath);
×
1330

1331
    // Kick all players that have a different checksum from the host
1332
    AsyncChecksum hostChecksum;
×
1333
    for(const AsyncLog& log : asyncLogs)
×
1334
    {
1335
        if(playerInfos.at(log.playerId).isHost)
×
1336
        {
1337
            hostChecksum = log.checksum;
×
1338
            break;
×
1339
        }
1340
    }
1341
    for(const AsyncLog& log : asyncLogs)
×
1342
    {
1343
        if(log.checksum != hostChecksum)
×
1344
            KickPlayer(log.playerId, KickReason::Async, __LINE__);
×
1345
    }
1346
    return true;
×
1347
}
1348

1349
bool GameServer::OnGameMessage(const GameMessage_RemoveLua& msg)
×
1350
{
1351
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1352
    {
1353
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1354
        return true;
×
1355
    }
1356
    mapinfo.luaFilepath.clear();
×
1357
    mapinfo.luaData.Clear();
×
1358
    mapinfo.luaChecksum = 0;
×
1359
    SendToAll(msg);
×
1360
    CancelCountdown();
×
1361
    return true;
×
1362
}
1363

1364
bool GameServer::OnGameMessage(const GameMessage_Countdown& msg)
×
1365
{
1366
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1367
    {
1368
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1369
        return true;
×
1370
    }
1371

1372
    NetworkPlayer* nwPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1373
    if(!nwPlayer || countdown.IsActive())
×
1374
        return true;
×
1375

1376
    if(!ArePlayersReady())
×
1377
        nwPlayer->sendMsgAsync(new GameMessage_CancelCountdown(true));
×
1378
    else
1379
    {
1380
        // Just to make sure update all player infos
1381
        SendToAll(GameMessage_Player_List(playerInfos));
×
1382
        // Start countdown (except its single player)
1383
        if(networkPlayers.size() > 1)
×
1384
        {
1385
            countdown.Start(msg.countdown);
×
1386
            SendToAll(GameMessage_Countdown(countdown.GetRemainingSecs()));
×
1387
            LOG.writeToFile("SERVER >>> Countdown started(%d)\n") % countdown.GetRemainingSecs();
×
1388
        } else if(!StartGame())
×
1389
            Stop();
×
1390
    }
1391

1392
    return true;
×
1393
}
1394

1395
bool GameServer::OnGameMessage(const GameMessage_CancelCountdown& msg)
×
1396
{
1397
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1398
    {
1399
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1400
        return true;
×
1401
    }
1402

1403
    CancelCountdown();
×
1404
    return true;
×
1405
}
1406

1407
bool GameServer::OnGameMessage(const GameMessage_Pause& msg)
×
1408
{
1409
    if(IsHost(msg.senderPlayerID))
×
1410
        SetPaused(msg.paused);
×
1411
    return true;
×
1412
}
1413

1414
bool GameServer::OnGameMessage(const GameMessage_SkipToGF& msg)
×
1415
{
1416
    if(IsHost(msg.senderPlayerID))
×
1417
    {
1418
        skiptogf = msg.targetGF;
×
1419
        SendToAll(msg);
×
1420
    }
1421
    return true;
×
1422
}
1423

1424
bool GameServer::OnGameMessage(const GameMessage_GGSChange& msg)
×
1425
{
1426
    if(state != ServerState::Config || !IsHost(msg.senderPlayerID))
×
1427
    {
1428
        KickPlayer(msg.senderPlayerID, KickReason::InvalidMsg, __LINE__);
×
1429
        return true;
×
1430
    }
1431
    ggs_ = msg.ggs;
×
1432
    SendToAll(msg);
×
1433
    CancelCountdown();
×
1434
    return true;
×
1435
}
1436

1437
void GameServer::CancelCountdown()
×
1438
{
1439
    if(!countdown.IsActive())
×
1440
        return;
×
1441
    // Countdown-Stop allen mitteilen
1442
    countdown.Stop();
×
1443
    SendToAll(GameMessage_CancelCountdown());
×
1444
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_CANCELCOUNTDOWN\n");
×
1445
}
1446

1447
bool GameServer::ArePlayersReady() const
×
1448
{
1449
    // Alle Spieler da?
1450
    for(const JoinPlayerInfo& player : playerInfos)
×
1451
    {
1452
        // noch nicht alle spieler da -> feierabend!
1453
        if(player.ps == PlayerState::Free || (player.isHuman() && !player.isReady))
×
1454
            return false;
×
1455
    }
1456

1457
    std::set<unsigned> takenColors;
×
1458

1459
    // Check all players have different colors
1460
    for(const JoinPlayerInfo& player : playerInfos)
×
1461
    {
1462
        if(player.isUsed())
×
1463
        {
1464
            if(helpers::contains(takenColors, player.color))
×
1465
                return false;
×
1466
            takenColors.insert(player.color);
×
1467
        }
1468
    }
1469
    return true;
×
1470
}
1471

1472
void GameServer::PlayerDataChanged(unsigned playerIdx)
×
1473
{
1474
    CancelCountdown();
×
1475
    JoinPlayerInfo& player = GetJoinPlayer(playerIdx);
×
1476
    if(player.ps != PlayerState::AI && player.isReady)
×
1477
    {
1478
        player.isReady = false;
×
1479
        SendToAll(GameMessage_Player_Ready(playerIdx, false));
×
1480
    }
1481
}
×
1482

1483
bfs::path GameServer::SaveAsyncLog()
×
1484
{
1485
    // Get the highest common counter number and start from there (remove all others)
1486
    unsigned maxCtr = 0;
×
1487
    for(const AsyncLog& log : asyncLogs)
×
1488
    {
1489
        if(!log.randEntries.empty() && log.randEntries[0].counter > maxCtr)
×
1490
            maxCtr = log.randEntries[0].counter;
×
1491
    }
1492
    // Number of entries = max(asyncLogs[0..n].randEntries.size())
1493
    unsigned numEntries = 0;
×
1494
    for(AsyncLog& log : asyncLogs)
×
1495
    {
NEW
1496
        auto it = helpers::find_if(log.randEntries, [maxCtr](const auto& e) { return e.counter == maxCtr; });
×
1497
        log.randEntries.erase(log.randEntries.begin(), it);
×
1498
        if(numEntries < log.randEntries.size())
×
1499
            numEntries = log.randEntries.size();
×
1500
    }
1501
    // No entries :(
1502
    if(numEntries == 0 || asyncLogs.size() < 2u)
×
1503
        return "";
×
1504

1505
    // count identical lines
1506
    unsigned numIdentical = 0;
×
1507
    for(unsigned i = 0; i < numEntries; i++)
×
1508
    {
1509
        bool isIdentical = true;
×
1510
        if(i >= asyncLogs[0].randEntries.size())
×
1511
            break;
×
1512
        const RandomEntry& refEntry = asyncLogs[0].randEntries[i];
×
1513
        for(const AsyncLog& log : asyncLogs)
×
1514
        {
1515
            if(i >= log.randEntries.size())
×
1516
            {
1517
                isIdentical = false;
×
1518
                break;
×
1519
            }
1520
            const RandomEntry& curEntry = log.randEntries[i];
×
1521
            if(curEntry.maxExcl != refEntry.maxExcl || curEntry.rngState != refEntry.rngState
×
1522
               || curEntry.objId != refEntry.objId)
×
1523
            {
1524
                isIdentical = false;
×
1525
                break;
×
1526
            }
1527
        }
1528
        if(isIdentical)
×
1529
            ++numIdentical;
×
1530
        else
1531
            break;
×
1532
    }
1533

1534
    LOG.write(_("There are %1% identical async log entries.\n")) % numIdentical;
×
1535

1536
    bfs::path filePath =
1537
      RTTRCONFIG.ExpandPath(s25::folders::logs) / (s25util::Time::FormatTime("async_%Y-%m-%d_%H-%i-%s") + "Server.log");
×
1538

1539
    // open async log
1540
    bnw::ofstream file(filePath);
×
1541

1542
    if(file)
×
1543
    {
1544
        file << "Map: " << mapinfo.title << std::endl;
×
1545
        file << std::setfill(' ');
×
1546
        for(const AsyncLog& log : asyncLogs)
×
1547
        {
1548
            const JoinPlayerInfo& plInfo = playerInfos.at(log.playerId);
×
1549
            file << "Player " << std::setw(2) << unsigned(log.playerId) << (plInfo.isHost ? '#' : ' ') << "\t\""
×
1550
                 << plInfo.name << '"' << std::endl;
×
1551
            file << "System info: " << log.addData << std::endl;
×
1552
            file << "\tChecksum: " << std::setw(0) << log.checksum << std::endl;
×
1553
        }
1554
        for(const AsyncLog& log : asyncLogs)
×
1555
            file << "Checksum " << std::setw(2) << unsigned(log.playerId) << std::setw(0) << ": " << log.checksum
×
1556
                 << std::endl;
×
1557

1558
        // print identical lines, they help in tracing the bug
1559
        for(unsigned i = 0; i < numIdentical; i++)
×
1560
            file << "[ I ]: " << asyncLogs[0].randEntries[i] << "\n";
×
1561
        for(unsigned i = numIdentical; i < numEntries; i++)
×
1562
        {
1563
            for(const AsyncLog& log : asyncLogs)
×
1564
            {
1565
                if(i < log.randEntries.size())
×
1566
                    file << "[C" << std::setw(2) << unsigned(log.playerId) << std::setw(0)
×
1567
                         << "]: " << log.randEntries[i] << '\n';
×
1568
            }
1569
        }
1570

1571
        LOG.write(_("Async log saved at %1%\n")) % filePath;
×
1572
        return filePath;
×
1573
    } else
1574
    {
1575
        LOG.write(_("Failed to save async log at %1%\n")) % filePath;
×
1576
        return "";
×
1577
    }
1578
}
1579

1580
void GameServer::SendAsyncLog(const bfs::path& asyncLogFilePath)
×
1581
{
1582
    if(SETTINGS.global.submit_debug_data == 1
×
1583
#ifdef _WIN32
1584
       || (MessageBoxW(nullptr,
1585
                       boost::nowide::widen(_("The game clients are out of sync. Would you like to send debug "
1586
                                              "information to RttR to help us avoiding this in "
1587
                                              "the future? Thank you very much!"))
1588
                         .c_str(),
1589
                       boost::nowide::widen(_("Error")).c_str(),
1590
                       MB_YESNO | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND)
1591
           == IDYES)
1592
#endif
1593
    )
1594
    {
1595
        DebugInfo di;
×
1596
        LOG.write(_("Sending async logs %1%.\n")) % (di.SendAsyncLog(asyncLogFilePath) ? "succeeded" : "failed");
×
1597

1598
        di.SendReplay();
×
1599
    }
1600
}
×
1601

1602
void GameServer::CheckAndSetColor(unsigned playerIdx, unsigned newColor)
×
1603
{
1604
    RTTR_Assert(playerIdx < playerInfos.size());
×
1605
    RTTR_Assert(playerInfos.size() <= PLAYER_COLORS.size()); // Else we may not find a valid color!
×
1606

1607
    JoinPlayerInfo& player = playerInfos[playerIdx];
×
1608
    RTTR_Assert(player.isUsed()); // Should only set colors for taken spots
×
1609

1610
    // Get colors used by other players
1611
    std::set<unsigned> takenColors;
×
1612
    for(unsigned p = 0; p < playerInfos.size(); ++p)
×
1613
    {
1614
        // Skip self
1615
        if(p == playerIdx)
×
1616
            continue;
×
1617

1618
        JoinPlayerInfo& otherPlayer = playerInfos[p];
×
1619
        if(otherPlayer.isUsed())
×
1620
            takenColors.insert(otherPlayer.color);
×
1621
    }
1622

1623
    // Look for a unique color
1624
    int newColorIdx = JoinPlayerInfo::GetColorIdx(newColor);
×
1625
    while(helpers::contains(takenColors, newColor))
×
1626
        newColor = PLAYER_COLORS[(++newColorIdx) % PLAYER_COLORS.size()];
×
1627

1628
    if(player.color == newColor)
×
1629
        return;
×
1630

1631
    player.color = newColor;
×
1632

1633
    SendToAll(GameMessage_Player_Color(playerIdx, player.color));
×
1634
    LOG.writeToFile("SERVER >>> BROADCAST: NMS_PLAYER_TOGGLECOLOR(%d, %d)\n") % playerIdx % player.color;
×
1635
}
1636

1637
bool GameServer::OnGameMessage(const GameMessage_Player_Swap& msg)
×
1638
{
1639
    if(state != ServerState::Game && state != ServerState::Config)
×
1640
        return true;
×
1641
    int targetPlayer = GetTargetPlayer(msg);
×
1642
    if(targetPlayer < 0)
×
1643
        return true;
×
1644
    auto player1 = static_cast<uint8_t>(targetPlayer);
×
1645
    if(player1 == msg.player2 || msg.player2 >= playerInfos.size())
×
1646
        return true;
×
1647

1648
    SwapPlayer(player1, msg.player2);
×
1649
    return true;
×
1650
}
1651

1652
bool GameServer::OnGameMessage(const GameMessage_Player_SwapConfirm& msg)
×
1653
{
1654
    GameServerPlayer* player = GetNetworkPlayer(msg.senderPlayerID);
×
1655
    if(!player)
×
1656
        return true;
×
1657
    for(auto it = player->getPendingSwaps().begin(); it != player->getPendingSwaps().end(); ++it)
×
1658
    {
1659
        if(it->first == msg.player && it->second == msg.player2)
×
1660
        {
1661
            player->getPendingSwaps().erase(it);
×
1662
            break;
×
1663
        }
1664
    }
1665
    return true;
×
1666
}
1667

1668
void GameServer::SwapPlayer(const uint8_t player1, const uint8_t player2)
×
1669
{
1670
    // TODO: Swapping the player messes up the ids because our IDs are indizes. Usually this works because we use the
1671
    // sender player ID for messages received by the server and set the right ID for messages sent by the server.
1672
    // However (currently only) the host may send messages for another player. Those will not get the adjusted ID till
1673
    // he gets the swap message. So there is a short time, where the messages may be executed for the wrong player.
1674
    // Idea: Use actual IDs for players in messages (unique)
1675
    if(state == ServerState::Config)
×
1676
    {
1677
        // Swap player during match-making
1678
        // Swap everything
1679
        using std::swap;
1680
        swap(playerInfos[player1], playerInfos[player2]);
×
1681
        // In savegames some things cannot be changed
1682
        if(mapinfo.type == MapType::Savegame)
×
1683
            playerInfos[player1].FixSwappedSaveSlot(playerInfos[player2]);
×
1684
    } else if(state == ServerState::Game)
×
1685
    {
1686
        // Ingame we can only switch to a KI
1687
        if(playerInfos[player1].ps != PlayerState::Occupied || playerInfos[player2].ps != PlayerState::AI)
×
1688
            return;
×
1689

1690
        LOG.write("GameServer::ChangePlayer %i - %i \n") % unsigned(player1) % unsigned(player2);
×
1691
        using std::swap;
1692
        swap(playerInfos[player2].ps, playerInfos[player1].ps);
×
1693
        swap(playerInfos[player2].aiInfo, playerInfos[player1].aiInfo);
×
1694
        swap(playerInfos[player2].isHost, playerInfos[player1].isHost);
×
1695
    }
1696
    // Change ids of network players (if any). Get both first!
1697
    GameServerPlayer* newPlayer = GetNetworkPlayer(player2);
×
1698
    GameServerPlayer* oldPlayer = GetNetworkPlayer(player1);
×
1699
    if(newPlayer)
×
1700
        newPlayer->playerId = player1;
×
1701
    if(oldPlayer)
×
1702
        oldPlayer->playerId = player2;
×
1703
    SendToAll(GameMessage_Player_Swap(player1, player2));
×
1704
    const auto pSwap = std::make_pair(player1, player2);
×
1705
    for(GameServerPlayer& player : networkPlayers)
×
1706
    {
1707
        if(!player.isActive())
×
1708
            continue;
×
1709
        player.getPendingSwaps().push_back(pSwap);
×
1710
    }
1711
}
1712

1713
GameServerPlayer* GameServer::GetNetworkPlayer(unsigned playerId)
×
1714
{
1715
    for(GameServerPlayer& player : networkPlayers)
×
1716
    {
1717
        if(player.playerId == playerId)
×
1718
            return &player;
×
1719
    }
1720
    return nullptr;
×
1721
}
1722

1723
void GameServer::SetPaused(bool paused)
×
1724
{
1725
    if(framesinfo.isPaused == paused)
×
1726
        return;
×
1727
    framesinfo.isPaused = paused;
×
1728
    SendToAll(GameMessage_Pause(framesinfo.isPaused));
×
1729
    for(GameServerPlayer& player : networkPlayers)
×
1730
        player.setNotLagging();
×
1731
}
1732

1733
JoinPlayerInfo& GameServer::GetJoinPlayer(unsigned playerIdx)
×
1734
{
1735
    return playerInfos.at(playerIdx);
×
1736
}
1737

1738
bool GameServer::IsHost(unsigned playerIdx) const
×
1739
{
1740
    return playerIdx < playerInfos.size() && playerInfos[playerIdx].isHost;
×
1741
}
1742

1743
int GameServer::GetTargetPlayer(const GameMessageWithPlayer& msg)
×
1744
{
1745
    if(msg.player != 0xFF)
×
1746
    {
1747
        if(msg.player < playerInfos.size() && (msg.player == msg.senderPlayerID || IsHost(msg.senderPlayerID)))
×
1748
        {
1749
            GameServerPlayer* networkPlayer = GetNetworkPlayer(msg.senderPlayerID);
×
1750
            if(networkPlayer->isActive())
×
1751
                return msg.player;
×
1752
            unsigned result = msg.player;
×
1753
            // Apply pending swaps
1754
            for(auto& pSwap : networkPlayer->getPendingSwaps()) //-V522
×
1755
            {
1756
                if(pSwap.first == result)
×
1757
                    result = pSwap.second;
×
1758
                else if(pSwap.second == result)
×
1759
                    result = pSwap.first;
×
1760
            }
1761
            return result;
×
1762
        }
1763
    } else if(msg.senderPlayerID < playerInfos.size())
×
1764
        return msg.senderPlayerID;
×
1765
    return -1;
×
1766
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc