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

Return-To-The-Roots / s25client / 25632720335

10 May 2026 03:36PM UTC coverage: 50.314% (+0.07%) from 50.245%
25632720335

Pull #1925

github

web-flow
Merge ccf137a4c into 9d512408c
Pull Request #1925: Ignore isolated fish resources for fisheries

37 of 65 new or added lines in 4 files covered. (56.92%)

6 existing lines in 3 files now uncovered.

23133 of 45977 relevant lines covered (50.31%)

43227.1 hits per line

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

75.97
/libs/s25main/world/MapLoader.cpp
1
// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "world/MapLoader.h"
6
#include "Game.h"
7
#include "GamePlayer.h"
8
#include "GameWorldBase.h"
9
#include "GlobalGameSettings.h"
10
#include "PointOutput.h"
11
#include "RttrForeachPt.h"
12
#include "addons/const_addons.h"
13
#include "buildings/nobHQ.h"
14
#include "factories/BuildingFactory.h"
15
#include "helpers/IdRange.h"
16
#include "helpers/Range.h"
17
#include "helpers/containerUtils.h"
18
#include "helpers/mathFuncs.h"
19
#include "lua/GameDataLoader.h"
20
#include "pathfinding/PathConditionShip.h"
21
#include "random/Random.h"
22
#include "world/World.h"
23
#include "nodeObjs/noAnimal.h"
24
#include "nodeObjs/noEnvObject.h"
25
#include "nodeObjs/noGranite.h"
26
#include "nodeObjs/noStaticObject.h"
27
#include "nodeObjs/noTree.h"
28
#include "gameTypes/ShipDirection.h"
29
#include "gameData/MaxPlayers.h"
30
#include "gameData/TerrainDesc.h"
31
#include "libsiedler2/Archiv.h"
32
#include "libsiedler2/ArchivItem_Map.h"
33
#include "libsiedler2/ArchivItem_Map_Header.h"
34
#include "libsiedler2/prototypen.h"
35
#include "s25util/Log.h"
36
#include <boost/filesystem/operations.hpp>
37
#include <algorithm>
38
#include <map>
39
#include <queue>
40

41
class noBase;
42

43
MapLoader::MapLoader(GameWorldBase& world) : world_(world) {}
7✔
44

45
bool MapLoader::Load(const libsiedler2::ArchivItem_Map& map, Exploration exploration)
5✔
46
{
47
    GameDataLoader gdLoader(world_.GetDescriptionWriteable());
10✔
48
    if(!gdLoader.Load())
5✔
49
        return false;
×
50

51
    uint8_t gfxSet = map.getHeader().getGfxSet();
5✔
52
    DescIdx<LandscapeDesc> lt =
53
      world_.GetDescription().landscapes.find([gfxSet](const LandscapeDesc& l) { return l.s2Id == gfxSet; });
10✔
54
    world_.Init(MapExtent(map.getHeader().getWidth(), map.getHeader().getHeight()), lt); //-V807
5✔
55

56
    if(!InitNodes(map, exploration))
5✔
57
        return false;
×
58
    PlaceObjects(map);
5✔
59
    PlaceAnimals(map);
5✔
60
    if(!InitSeasAndHarbors(world_))
5✔
61
        return false;
×
62

63
    /// Schatten
64
    InitShadows(world_);
5✔
65

66
    // If we have explored FoW, create the FoW objects
67
    if(exploration == Exploration::FogOfWarExplored)
5✔
68
        SetMapExplored(world_);
×
69

70
    return true;
5✔
71
}
72

73
bool MapLoader::Load(const boost::filesystem::path& mapFilePath)
3✔
74
{
75
    // Map laden
76
    libsiedler2::Archiv mapArchiv;
6✔
77

78
    // Karteninformationen laden
79
    if(libsiedler2::loader::LoadMAP(mapFilePath, mapArchiv) != 0)
3✔
80
        return false;
×
81

82
    const libsiedler2::ArchivItem_Map& map = *static_cast<libsiedler2::ArchivItem_Map*>(mapArchiv[0]);
3✔
83

84
    if(!Load(map, world_.GetGGS().exploration))
3✔
85
        return false;
×
86
    if(!PlaceHQs())
3✔
87
        return false;
×
88

89
    world_.CreateTradeGraphs();
3✔
90

91
    return true;
3✔
92
}
93

94
bool MapLoader::LoadLuaScript(Game& game, ILocalGameState& localgameState, const boost::filesystem::path& luaFilePath)
3✔
95
{
96
    if(!bfs::exists(luaFilePath))
3✔
97
        return false;
×
98
    auto lua = std::make_unique<LuaInterfaceGame>(game, localgameState);
6✔
99
    if(!lua->loadScript(luaFilePath) || !lua->CheckScriptVersion())
3✔
100
        return false;
1✔
101
    game.SetLua(std::move(lua));
2✔
102
    return true;
2✔
103
}
104

105
bool MapLoader::PlaceHQs(bool addStartWares)
3✔
106
{
107
    std::vector<MapPoint> hqPositions = hqPositions_;
6✔
108
    if(world_.GetGGS().randomStartPosition)
3✔
109
        RANDOM_SHUFFLE2(hqPositions, 0);
1✔
110
    return PlaceHQs(world_, hqPositions, addStartWares);
6✔
111
}
112

113
void MapLoader::SetupResources(GameWorldBase& world, const bool fixFish)
3✔
114
{
115
    ResourceType target;
116
    switch(world.GetGGS().getSelection(AddonId::CHANGE_GOLD_DEPOSITS))
3✔
117
    {
118
        case 0:
3✔
119
        default: target = ResourceType::Gold; break;
3✔
NEW
120
        case 1: target = ResourceType::Nothing; break;
×
NEW
121
        case 2: target = ResourceType::Iron; break;
×
NEW
122
        case 3: target = ResourceType::Coal; break;
×
NEW
123
        case 4: target = ResourceType::Granite; break;
×
124
    }
125
    ConvertMineResourceTypes(world, ResourceType::Gold, target);
3✔
126
    PlaceAndFixWater(world);
3✔
127
    if(fixFish)
3✔
128
        RemoveUnusableFishResources(world);
3✔
129
}
3✔
130

131
void MapLoader::ConvertMineResourceTypes(GameWorldBase& world, ResourceType from, ResourceType to)
3✔
132
{
133
    // LOG.write(("Convert map resources from %i to %i\n", from, to);
134
    if(from == to)
3✔
135
        return;
3✔
136

NEW
137
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
×
138
    {
NEW
139
        Resource resources = world.GetNode(pt).resources;
×
140
        // Gibt es Ressourcen dieses Typs?
141
        // Wenn ja, dann umwandeln bzw löschen
NEW
142
        if(resources.getType() == from)
×
143
        {
NEW
144
            resources.setType(to);
×
NEW
145
            world.SetResource(pt, resources);
×
146
        }
147
    }
148
}
149

150
void MapLoader::PlaceAndFixWater(GameWorldBase& world)
3✔
151
{
152
    const bool waterEverywhere = world.GetGGS().getSelection(AddonId::EXHAUSTIBLE_WATER) == 1;
3✔
153

154
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
1,383✔
155
    {
156
        Resource curNodeResource = world.GetNode(pt).resources;
1,320✔
157

158
        if(curNodeResource.getType() == ResourceType::Nothing)
1,320✔
159
        {
160
            if(!waterEverywhere)
1,313✔
161
                continue;
1,320✔
162
        } else if(curNodeResource.getType() != ResourceType::Water)
7✔
163
            continue; // do not override maps resource.
7✔
164

NEW
165
        uint8_t minHumidity = 100;
×
NEW
166
        for(const DescIdx<TerrainDesc> tIdx : world.GetTerrainsAround(pt))
×
167
        {
NEW
168
            const uint8_t curHumidity = world.GetDescription().get(tIdx).humidity;
×
NEW
169
            if(curHumidity < minHumidity)
×
170
            {
NEW
171
                minHumidity = curHumidity;
×
NEW
172
                if(minHumidity == 0)
×
NEW
173
                    break;
×
174
            }
175
        }
NEW
176
        if(minHumidity)
×
177
        {
NEW
178
            curNodeResource =
×
NEW
179
              Resource(ResourceType::Water, waterEverywhere ? 7 : helpers::iround<uint8_t>(minHumidity * 7. / 100.));
×
180
        } else
NEW
181
            curNodeResource = Resource(ResourceType::Nothing, 0);
×
182

NEW
183
        world.SetResource(pt, curNodeResource);
×
184
    }
185
}
3✔
186

187
void MapLoader::RemoveUnusableFishResources(GameWorldBase& world)
3✔
188
{
189
    const auto isWaterPoint = [&world](const MapPoint nb) { return world.IsWaterPoint(nb); };
28✔
190
    for(const MapCoord y : helpers::range(world.GetHeight()))
132✔
191
    {
192
        // Optimization: When there was fish on the previous node (in the same row)
193
        // we do not need to check for isolated water points, as there is at least that water point
194
        bool previousHasFish = false;
60✔
195
        for(const MapCoord x : helpers::range(world.GetWidth()))
2,880✔
196
        {
197
            const MapPoint pt(x, y);
1,320✔
198
            bool hasFish = false;
1,320✔
199

200
            if(world.GetNode(pt).resources.has(ResourceType::Fish))
1,320✔
201
            {
202
                if(!isWaterPoint(pt))
7✔
NEW
203
                    world.SetResource(pt, Resource(ResourceType::Nothing, 0));
×
204
                else if(previousHasFish || helpers::contains_if(world.GetNeighbours(pt), isWaterPoint))
7✔
205
                    hasFish = true;
5✔
206
                else
207
                    world.SetResource(pt, Resource(ResourceType::Nothing, 0));
2✔
208
            }
209
            previousHasFish = hasFish;
1,320✔
210
        }
211
    }
212
}
3✔
213

214
void MapLoader::InitShadows(World& world)
5✔
215
{
216
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
70,805✔
217
        world.RecalcShadow(pt);
70,400✔
218
}
5✔
219

220
void MapLoader::SetMapExplored(World& world)
×
221
{
222
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
×
223
    {
224
        // For every player
NEW
225
        for(const auto i : helpers::range(MAX_PLAYERS))
×
226
        {
227
            // If we have FoW here, save it
228
            if(world.GetNode(pt).fow[i].visibility == Visibility::FogOfWar)
×
229
                world.SaveFOWNode(pt, i, 0);
×
230
        }
231
    }
232
}
×
233

234
DescIdx<TerrainDesc> MapLoader::getTerrainFromS2(uint8_t s2Id) const
140,800✔
235
{
236
    return world_.GetDescription().terrain.find([s2Id, landscape = world_.GetLandscapeType()](const TerrainDesc& t) {
140,800✔
237
        return t.s2Id == s2Id && t.landscape == landscape;
1,442,160✔
238
    });
140,800✔
239
}
240

241
bool MapLoader::InitNodes(const libsiedler2::ArchivItem_Map& map, Exploration exploration)
5✔
242
{
243
    using libsiedler2::MapLayer;
244
    // Init node data (everything except the objects, figures and BQ)
245
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
246
    {
247
        MapNode& node = world_.GetNodeInt(pt);
70,400✔
248

249
        std::fill(node.roads.begin(), node.roads.end(), PointRoad::None);
70,400✔
250
        node.altitude = map.getMapDataAt(MapLayer::Altitude, pt.x, pt.y);
70,400✔
251
        unsigned char t1 = map.getMapDataAt(MapLayer::Terrain1, pt.x, pt.y),
70,400✔
252
                      t2 = map.getMapDataAt(MapLayer::Terrain2, pt.x, pt.y);
70,400✔
253

254
        // Hafenplatz?
255
        if((t1 & libsiedler2::HARBOR_MASK) != 0)
70,400✔
256
            world_.harborData.push_back(HarborPos(pt));
×
257

258
        // Will be set later
259
        node.harborId.reset();
70,400✔
260

261
        node.t1 = getTerrainFromS2(t1 & 0x3F); // Only lower 6 bits
70,400✔
262
        node.t2 = getTerrainFromS2(t2 & 0x3F); // Only lower 6 bits
70,400✔
263
        if(!node.t1 || !node.t2)
70,400✔
264
            return false;
×
265

266
        unsigned char mapResource = map.getMapDataAt(MapLayer::Resources, pt.x, pt.y);
70,400✔
267
        Resource resource;
70,400✔
268
        // Wasser?
269
        if(mapResource == 0x20 || mapResource == 0x21)
70,400✔
270
            resource = Resource(ResourceType::Water, 7);
36,625✔
271
        else if(mapResource > 0x40 && mapResource < 0x48)
33,775✔
272
            resource = Resource(ResourceType::Coal, mapResource - 0x40);
9,815✔
273
        else if(mapResource > 0x48 && mapResource < 0x50)
23,960✔
274
            resource = Resource(ResourceType::Iron, mapResource - 0x48);
2,525✔
275
        else if(mapResource > 0x50 && mapResource < 0x58)
21,435✔
276
            resource = Resource(ResourceType::Gold, mapResource - 0x50);
1,660✔
277
        else if(mapResource > 0x58 && mapResource < 0x60)
19,775✔
278
            resource = Resource(ResourceType::Granite, mapResource - 0x58);
550✔
279
        else if(mapResource > 0x80 && mapResource < 0x90) // fish
19,225✔
280
            resource = Resource(ResourceType::Fish, 4);   // Use 4 fish
2,420✔
281
        node.resources = resource;
70,400✔
282

283
        node.reserved = false;
70,400✔
284
        node.owner = 0;
70,400✔
285
        std::fill(node.boundary_stones.begin(), node.boundary_stones.end(), 0);
70,400✔
286
        node.seaId.reset();
70,400✔
287

288
        Visibility fowVisibility;
289
        switch(exploration)
70,400✔
290
        {
291
            case Exploration::Disabled: fowVisibility = Visibility::Visible; break;
×
292
            case Exploration::Classic:
70,400✔
293
            case Exploration::FogOfWar: fowVisibility = Visibility::Invisible; break;
70,400✔
294
            case Exploration::FogOfWarExplored: fowVisibility = Visibility::FogOfWar; break;
×
295
            default: throw std::invalid_argument("Visibility for FoW");
×
296
        }
297

298
        // FOW-Zeug initialisieren
299
        for(auto& fow : node.fow)
633,600✔
300
        {
301
            fow = FoWNode();
563,200✔
302
            fow.visibility = fowVisibility;
563,200✔
303
        }
304

305
        RTTR_Assert(node.figures.empty());
70,400✔
306
    }
307
    return true;
5✔
308
}
309

310
void MapLoader::PlaceObjects(const libsiedler2::ArchivItem_Map& map)
5✔
311
{
312
    hqPositions_.clear();
5✔
313

314
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
315
    {
316
        using libsiedler2::MapLayer;
317
        unsigned char lc = map.getMapDataAt(MapLayer::ObjectIndex, pt.x, pt.y);
70,400✔
318
        noBase* obj = nullptr;
70,400✔
319

320
        switch(map.getMapDataAt(MapLayer::ObjectType, pt.x, pt.y))
70,400✔
321
        {
322
            // Player Startpos (provisorisch)
323
            case 0x80:
20✔
324
            {
325
                if(lc < MAX_PLAYERS)
20✔
326
                {
327
                    while(hqPositions_.size() <= lc)
40✔
328
                        hqPositions_.push_back(MapPoint::Invalid());
20✔
329
                    hqPositions_[lc] = pt;
20✔
330
                }
331
            }
332
            break;
20✔
333

334
            // Baum 1-4
335
            case 0xC4:
17,640✔
336
            {
337
                if(lc >= 0x30 && lc <= 0x3D)
17,640✔
338
                    obj = new noTree(pt, 0, 3);
5,610✔
339
                else if(lc >= 0x70 && lc <= 0x7D)
12,030✔
340
                    obj = new noTree(pt, 1, 3);
5,860✔
341
                else if(lc >= 0xB0 && lc <= 0xBD)
6,170✔
342
                    obj = new noTree(pt, 2, 3);
5,555✔
343
                else if(lc >= 0xF0 && lc <= 0xFD)
615✔
344
                    obj = new noTree(pt, 3, 3);
615✔
345
                else
346
                    LOG.write(_("Unknown tree1-4 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
347
            }
348
            break;
17,640✔
349

350
            // Baum 5-8
351
            case 0xC5:
×
352
            {
353
                if(lc >= 0x30 && lc <= 0x3D)
×
354
                    obj = new noTree(pt, 4, 3);
×
355
                else if(lc >= 0x70 && lc <= 0x7D)
×
356
                    obj = new noTree(pt, 5, 3);
×
357
                else if(lc >= 0xB0 && lc <= 0xBD)
×
358
                    obj = new noTree(pt, 6, 3);
×
359
                else if(lc >= 0xF0 && lc <= 0xFD)
×
360
                    obj = new noTree(pt, 7, 3);
×
361
                else
362
                    LOG.write(_("Unknown tree5-8 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
363
            }
364
            break;
×
365

366
            // Baum 9
367
            case 0xC6:
×
368
            {
369
                if(lc >= 0x30 && lc <= 0x3D)
×
370
                    obj = new noTree(pt, 8, 3);
×
371
                else
372
                    LOG.write(_("Unknown tree9 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
373
            }
374
            break;
×
375

376
            // Sonstiges Naturzeug ohne Funktion, nur zur Dekoration
377
            case 0xC8:
3,740✔
378
            case 0xC9: // Note: 0xC9 is actually a bug and should be 0xC8. But the random map generator produced that...
379
            {
380
                // "wasserstein" aus der map_?_z.lst
381
                if(lc == 0x0B)
3,740✔
382
                    obj = new noStaticObject(pt, 500 + lc);
×
383
                // Objekte aus der map_?_z.lst
384
                else if(lc <= 0x0F)
3,740✔
385
                    obj = new noEnvObject(pt, 500 + lc);
1,615✔
386
                // Objekte aus der map.lst
387
                else if(lc <= 0x14)
2,125✔
388
                    obj = new noEnvObject(pt, 542 + lc - 0x10);
1,580✔
389
                // exists in mis0bobs-mis5bobs -> take stranded ship
390
                else if(lc == 0x15)
545✔
391
                    obj = new noStaticObject(pt, 0, 0);
×
392
                // gate
393
                else if(lc == 0x16)
545✔
394
                    obj = new noStaticObject(pt, 560);
×
395
                // open gate
396
                else if(lc == 0x17)
545✔
397
                    obj = new noStaticObject(pt, 561);
×
398
                // Stalagmiten (mis1bobs)
399
                else if(lc <= 0x1E)
545✔
400
                    obj = new noStaticObject(pt, (lc - 0x18) * 2, 1);
×
401
                // toter Baum (mis1bobs)
402
                else if(lc <= 0x20)
545✔
403
                    obj = new noStaticObject(pt, 20 + (lc - 0x1F) * 2, 1);
×
404
                // Gerippe (mis1bobs)
405
                else if(lc == 0x21)
545✔
406
                    obj = new noStaticObject(pt, 30, 1);
×
407
                // Objekte aus der map.lst
408
                else if(lc <= 0x2B)
545✔
409
                    obj = new noEnvObject(pt, 550 + lc - 0x22);
545✔
410
                // tent, ruin of guardhouse, tower ruin, cross
411
                else if(lc <= 0x2E || lc == 0x30)
×
412
                    obj = new noStaticObject(pt, (lc - 0x2C) * 2, 2);
×
413
                // castle ruin
414
                else if(lc == 0x2F)
×
415
                    obj = new noStaticObject(pt, (lc - 0x2C) * 2, 2, 2);
×
416
                // small wiking with boat
417
                else if(lc == 0x31)
×
418
                    obj = new noStaticObject(pt, 0, 3);
×
419
                // Pile of wood
420
                else if(lc == 0x32)
×
421
                    obj = new noStaticObject(pt, 0, 4);
×
422
                // whale skeleton (head right)
423
                else if(lc == 0x33)
×
424
                    obj = new noStaticObject(pt, 0, 5);
×
425
                // The next 2 are non standard and only for access in RTTR (replaced in original by
426
                // whale skeleton (head left)
427
                else if(lc == 0x34)
×
428
                    obj = new noStaticObject(pt, 2, 5);
×
429
                // Cave
430
                else if(lc == 0x35)
×
431
                    obj = new noStaticObject(pt, 4, 5);
×
432
                else
433
                    LOG.write(_("Unknown nature object at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
434
            }
435
            break;
3,740✔
436

437
            // Granit Typ 1
438
            case 0xCC:
1,370✔
439
            {
440
                if(lc >= 0x01 && lc <= 0x06)
1,370✔
441
                    obj = new noGranite(GraniteType::One, lc - 1);
1,370✔
442
                else
443
                    LOG.write(_("Unknown granite type2 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
444
            }
445
            break;
1,370✔
446

447
            // Granit Typ 2
448
            case 0xCD:
1,395✔
449
            {
450
                if(lc >= 0x01 && lc <= 0x06)
1,395✔
451
                    obj = new noGranite(GraniteType::Two, lc - 1);
1,395✔
452
                else
453
                    LOG.write(_("Unknown granite type2 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
454
            }
455
            break;
1,395✔
456

457
            // Nichts
458
            case 0: break;
46,235✔
459

460
            default:
×
461
#ifndef NDEBUG
462
                unsigned unknownObj = map.getMapDataAt(MapLayer::ObjectType, pt.x, pt.y);
×
463
                LOG.write(_("Unknown object at %1%: (0x%2$x: 0x%3$x)\n")) % pt % unknownObj % unsigned(lc);
×
464
#endif // !NDEBUG
465
                break;
×
466
        }
467

468
        world_.GetNodeInt(pt).obj = obj;
70,400✔
469
    }
470
}
5✔
471

472
void MapLoader::PlaceAnimals(const libsiedler2::ArchivItem_Map& map)
5✔
473
{
474
    // Tiere auslesen
475
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
476
    {
477
        Species species;
478
        using libsiedler2::MapLayer;
479
        switch(map.getMapDataAt(MapLayer::Animals, pt.x, pt.y))
70,400✔
480
        {
481
            // TODO: Which id is the polar bear?
482
            case 1:
175✔
483
                species = (RANDOM.Rand(RANDOM_CONTEXT2(0), 2) == 0) ? Species::RabbitWhite : Species::RabbitGrey;
175✔
484
                break; // Random rabbit
175✔
485
            case 2: species = Species::Fox; break;
140✔
486
            case 3: species = Species::Stag; break;
×
487
            case 4: species = Species::Deer; break;
140✔
488
            case 5: species = Species::Duck; break;
×
489
            case 6: species = Species::Sheep; break;
70✔
490
            case 0:
69,875✔
491
            case 0xFF: // 0xFF is for (really) old S2 maps
492
                continue;
69,875✔
493
            default:
×
494
#ifndef NDEBUG
495
                unsigned unknownAnimal = map.getMapDataAt(MapLayer::Animals, pt.x, pt.y);
×
496
                LOG.write(_("Unknown animal species at %1%: (0x%2$x)\n")) % pt % unknownAnimal;
×
497
#endif // !NDEBUG
498
                continue;
69,875✔
499
        }
500

501
        world_.AddFigure(pt, std::make_unique<noAnimal>(species, pt)).StartLiving();
525✔
502
    }
503
}
5✔
504

505
bool MapLoader::PlaceHQs(GameWorldBase& world, const std::vector<MapPoint>& hqPositions, const bool addStartWares)
177✔
506
{
507
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
553✔
508
    {
509
        // Skip unused slots
510
        if(!world.GetPlayer(i).isUsed())
376✔
511
            continue;
13✔
512

513
        // Does the HQ have a position?
514
        if(i >= hqPositions.size() || !hqPositions[i].isValid())
363✔
515
        {
516
            LOG.write(_("Player %u does not have a valid start position!")) % i;
×
517
            return false;
×
518
        }
519

520
        auto* hq = checkedCast<nobHQ*>(BuildingFactory::CreateBuilding(world, BuildingType::Headquarters,
363✔
521
                                                                       hqPositions[i], i, world.GetPlayer(i).nation));
363✔
522
        if(addStartWares)
363✔
523
            hq->addStartWares();
8✔
524
    }
525
    return true;
177✔
526
}
527

528
bool MapLoader::InitSeasAndHarbors(World& world, const std::vector<MapPoint>& additionalHarbors)
27✔
529
{
530
    for(MapPoint pt : additionalHarbors)
185✔
531
        world.harborData.push_back(HarborPos(pt));
158✔
532
    // Clear current harbors and seas
533
    RTTR_FOREACH_PT(MapPoint, world.GetSize()) //-V807
192,697✔
534
    {
535
        MapNode& node = world.GetNodeInt(pt);
190,284✔
536
        node.seaId.reset();
190,284✔
537
        node.harborId.reset();
190,284✔
538
    }
539

540
    /// Determine all seas
541
    world.seas.clear();
27✔
542
    SeaId curSeaId(1);
27✔
543
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
192,697✔
544
    {
545
        // Point is not yet assigned a sea but should be
546
        if(!world.GetNode(pt).seaId && world.IsSeaPoint(pt))
190,284✔
547
        {
548
            const auto seaSize = MeasureSea(world, pt, curSeaId);
46✔
549
            world.seas.push_back(World::Sea(seaSize));
46✔
550
            curSeaId = curSeaId.next();
46✔
551
        }
552
    }
553

554
    /// Determine seas adjacent to the harbor places
555
    HarborId curHarborId(1);
27✔
556
    for(auto it = world.harborData.begin(); it != world.harborData.end();)
201✔
557
    {
558
        helpers::StrongIdVector<bool, SeaId> hasCoastAtSea(world.seas.size(), false);
348✔
559
        bool foundCoast = false;
174✔
560
        for(const auto dir : helpers::EnumRange<Direction>{})
2,784✔
561
        {
562
            SeaId seaId;
1,044✔
563
            // Skip point at NW as often there is no path from it if the harbor is north of an island
564
            if(dir != Direction::NorthWest)
1,044✔
565
            {
566
                seaId = world.GetSeaFromCoastalPoint(world.GetNeighbour(it->pos, dir));
870✔
567
                if(seaId)
870✔
568
                {
569
                    foundCoast = true;
226✔
570
                    // Only 1 coastal point per sea
571
                    if(hasCoastAtSea[seaId])
226✔
572
                        seaId.reset();
52✔
573
                    else
574
                        hasCoastAtSea[seaId] = true;
174✔
575
                }
576
            }
577
            it->seaIds[dir] = seaId;
1,044✔
578
        }
579
        if(!foundCoast)
174✔
580
        {
581
            LOG.write("Map Bug: Found harbor without coast at %1%. Removing!\n") % it->pos;
×
582
            it = world.harborData.erase(it);
×
583
        } else
584
        {
585
            world.GetNodeInt(it->pos).harborId = curHarborId;
174✔
586
            curHarborId = curHarborId.next();
174✔
587
            ++it;
174✔
588
        }
589
    }
590

591
    // Calculate the neighbors and distances
592
    CalcHarborPosNeighbors(world);
27✔
593

594
    // Validate
595
    for(const auto startHbId : helpers::idRange<HarborId>(world.harborData.size()))
201✔
596
    {
597
        const HarborPos& startHbPos = world.harborData[startHbId];
174✔
598
        for(const std::vector<HarborPos::Neighbor>& neighbors : startHbPos.neighbors)
1,218✔
599
        {
600
            for(const HarborPos::Neighbor& neighbor : neighbors)
1,664✔
601
            {
602
                if(world.CalcHarborDistance(neighbor.id, startHbId) != neighbor.distance)
620✔
603
                {
604
                    LOG.write("Bug: Harbor distance mismatch for harbors %1%->%2%: %3% != %4%\n") % startHbId
×
605
                      % neighbor.id % world.CalcHarborDistance(neighbor.id, startHbId) % neighbor.distance;
×
606
                    return false;
×
607
                }
608
            }
609
        }
610
    }
611
    return true;
27✔
612
}
613

614
// class for finding harbor neighbors
615
struct CalcHarborPosNeighborsNode
616
{
617
    CalcHarborPosNeighborsNode() = default; //-V730
618
    CalcHarborPosNeighborsNode(const MapPoint pt, unsigned distance) : pos(pt), distance(distance) {}
232,032✔
619

620
    MapPoint pos;
621
    unsigned distance;
622
};
623

624
/// Calculate the distance from each harbor to the others
625
void MapLoader::CalcHarborPosNeighbors(World& world)
27✔
626
{
627
    for(HarborPos& harbor : world.harborData)
201✔
628
    {
629
        for(const auto dir : helpers::EnumRange<ShipDirection>{})
2,784✔
630
            harbor.neighbors[dir].clear();
1,044✔
631
    }
632
    PathConditionShip shipPathChecker(world);
27✔
633

634
    // pre-calculate sea-points, as IsSeaPoint is rather expensive
635
    std::vector<int8_t> ptIsSeaPt(world.nodes.size()); //-V656
54✔
636

637
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
192,697✔
638
    {
639
        if(shipPathChecker.IsNodeOk(pt))
190,284✔
640
            ptIsSeaPt[world.GetIdx(pt)] = -1;
64,106✔
641
    }
642

643
    // FIFO queue used for a BFS
644
    std::queue<CalcHarborPosNeighborsNode> todo_list;
54✔
645

646
    for(const auto startHbId : helpers::idRange<HarborId>(world.harborData.size()))
201✔
647
    {
648
        RTTR_Assert(todo_list.empty());
174✔
649

650
        // Copy sea points to working flags. Possible values are
651
        // -1 - sea point, not already visited
652
        // 0 - visited or no sea point
653
        // 1 - Coast to a harbor
654
        std::vector<int8_t> ptToVisitOrHb(ptIsSeaPt);
348✔
655

656
        helpers::StrongIdVector<bool, HarborId> hbFound(world.harborData.size(), false);
348✔
657
        // For each sea, store the coastal point indices and their harbor
658
        helpers::StrongIdVector<std::multimap<unsigned, HarborId>, SeaId> coastToHarborPerSea(world.seas.size());
348✔
659
        std::vector<MapPoint> ownCoastalPoints;
348✔
660

661
        // mark coastal points around harbors
662
        for(const auto otherHbId : helpers::idRange<HarborId>(world.harborData.size()))
1,600✔
663
        {
664
            for(const auto dir : helpers::EnumRange<Direction>{})
22,816✔
665
            {
666
                SeaId seaId = world.GetSeaId(otherHbId, dir);
8,556✔
667
                // No sea? -> Next
668
                if(!seaId)
8,556✔
669
                    continue;
7,130✔
670
                const MapPoint coastPt = world.GetNeighbour(world.GetHarborPoint(otherHbId), dir);
1,426✔
671
                // This should not be marked for visit
672
                unsigned idx = world.GetIdx(coastPt);
1,426✔
673
                RTTR_Assert(ptToVisitOrHb[idx] != -1);
1,426✔
674
                if(otherHbId == startHbId)
1,426✔
675
                {
676
                    // This is our start harbor. Add the coast points around it to our todo list.
677
                    ownCoastalPoints.push_back(coastPt);
174✔
678
                } else
679
                {
680
                    ptToVisitOrHb[idx] = 1;
1,252✔
681
                    coastToHarborPerSea[seaId].insert(std::make_pair(idx, otherHbId));
1,252✔
682
                }
683
            }
684
        }
685

686
        for(const MapPoint& ownCoastPt : ownCoastalPoints)
348✔
687
        {
688
            // Special case: Get all harbors that share the coast point with us
689
            SeaId seaId = world.GetSeaFromCoastalPoint(ownCoastPt);
174✔
690
            auto const coastToHbs = coastToHarborPerSea[seaId].equal_range(world.GetIdx(ownCoastPt));
174✔
691
            for(auto it = coastToHbs.first; it != coastToHbs.second; ++it)
180✔
692
            {
693
                ShipDirection shipDir = world.GetShipDir(ownCoastPt, ownCoastPt);
6✔
694
                world.harborData[startHbId].neighbors[shipDir].push_back(HarborPos::Neighbor(it->second, 0));
6✔
695
                hbFound[it->second] = true;
6✔
696
            }
697
            todo_list.push(CalcHarborPosNeighborsNode(ownCoastPt, 0));
174✔
698
        }
699

700
        while(!todo_list.empty()) // as long as there are sea points on our todo list...
232,206✔
701
        {
702
            CalcHarborPosNeighborsNode curNode = todo_list.front();
232,032✔
703
            todo_list.pop();
232,032✔
704

705
            for(const auto dir : helpers::EnumRange<Direction>{})
3,712,512✔
706
            {
707
                MapPoint curPt = world.GetNeighbour(curNode.pos, dir);
1,392,192✔
708
                unsigned idx = world.GetIdx(curPt);
1,392,192✔
709

710
                const int8_t ptValue = ptToVisitOrHb[idx];
1,392,192✔
711
                // Already visited
712
                if(ptValue == 0)
1,392,192✔
713
                    continue;
1,160,334✔
714
                // Not reachable
715
                if(!shipPathChecker.IsEdgeOk(curNode.pos, dir))
231,874✔
716
                    continue;
16✔
717

718
                if(ptValue > 0) // found harbor(s)
231,858✔
719
                {
720
                    ShipDirection shipDir = world.GetShipDir(world.harborData[startHbId].pos, curPt);
597✔
721
                    SeaId seaId = world.GetSeaFromCoastalPoint(curPt);
597✔
722
                    auto const coastToHbs = coastToHarborPerSea[seaId].equal_range(idx);
597✔
723
                    for(auto it = coastToHbs.first; it != coastToHbs.second; ++it)
1,217✔
724
                    {
725
                        const HarborId otherHbId = it->second;
620✔
726
                        if(hbFound[otherHbId])
620✔
727
                            continue;
6✔
728

729
                        hbFound[otherHbId] = true;
614✔
730
                        world.harborData[startHbId].neighbors[shipDir].push_back(
1,228✔
731
                          HarborPos::Neighbor(otherHbId, curNode.distance + 1));
614✔
732

733
                        // Make this the only coastal point of this harbor for this sea
734
                        HarborPos& otherHb = world.harborData[otherHbId];
614✔
735
                        RTTR_Assert(seaId);
614✔
736
                        for(const auto hbDir : helpers::EnumRange<Direction>{})
9,824✔
737
                        {
738
                            if(otherHb.seaIds[hbDir] == seaId && world.GetNeighbour(otherHb.pos, hbDir) != curPt)
3,684✔
739
                                otherHb.seaIds[hbDir].reset();
×
740
                        }
741
                    }
742
                }
743
                todo_list.push(CalcHarborPosNeighborsNode(curPt, curNode.distance + 1));
231,858✔
744
                ptToVisitOrHb[idx] = 0; // mark as visited, so we do not go here again
231,858✔
745
            }
746
        }
747
    }
748
}
27✔
749

750
/// Vermisst ein neues Weltmeer von einem Punkt aus, indem es alle mit diesem Punkt verbundenen
751
/// Wasserpunkte mit der gleichen ID belegt und die Anzahl zur�ckgibt
752
unsigned MapLoader::MeasureSea(World& world, const MapPoint start, SeaId seaId)
46✔
753
{
754
    // Breitensuche von diesem Punkt aus durchf�hren
755
    std::vector<bool> visited(world.GetWidth() * world.GetHeight(), false);
92✔
756
    std::queue<MapPoint> todo;
46✔
757

758
    todo.push(start);
46✔
759
    visited[world.GetIdx(start)] = true;
46✔
760

761
    // Count of nodes (including start node)
762
    unsigned count = 0;
46✔
763

764
    while(!todo.empty())
64,152✔
765
    {
766
        MapPoint p = todo.front();
64,106✔
767
        todo.pop();
64,106✔
768

769
        RTTR_Assert(visited[world.GetIdx(p)]);
64,106✔
770
        world.GetNodeInt(p).seaId = seaId;
64,106✔
771

772
        for(const MapPoint neighbourPt : world.GetNeighbours(p))
448,742✔
773
        {
774
            if(visited[world.GetIdx(neighbourPt)])
384,636✔
775
                continue;
310,153✔
776
            visited[world.GetIdx(neighbourPt)] = true;
74,483✔
777

778
            // Ist das dort auch ein Meerespunkt?
779
            if(world.IsSeaPoint(neighbourPt))
74,483✔
780
                todo.push(neighbourPt);
64,060✔
781
        }
782

783
        ++count;
64,106✔
784
    }
785

786
    return count;
92✔
787
}
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