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

Return-To-The-Roots / s25client / 22100923347

17 Feb 2026 01:46PM UTC coverage: 50.81% (+0.001%) from 50.809%
22100923347

Pull #1895

github

web-flow
Merge aa19096bb into 6e122731f
Pull Request #1895: Ships: Fix crash when doing expedition between adjacent harbor places

5 of 9 new or added lines in 2 files covered. (55.56%)

5 existing lines in 1 file now uncovered.

22797 of 44867 relevant lines covered (50.81%)

41762.65 hits per line

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

68.99
/libs/s25main/nodeObjs/noShip.cpp
1
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "noShip.h"
6
#include "EventManager.h"
7
#include "GameEvent.h"
8
#include "GamePlayer.h"
9
#include "GlobalGameSettings.h"
10
#include "Loader.h"
11
#include "SerializedGameData.h"
12
#include "Ware.h"
13
#include "addons/const_addons.h"
14
#include "buildings/nobHarborBuilding.h"
15
#include "figures/noFigure.h"
16
#include "figures/nofAttacker.h"
17
#include "helpers/EnumArray.h"
18
#include "helpers/containerUtils.h"
19
#include "helpers/pointerContainerUtils.h"
20
#include "network/GameClient.h"
21
#include "notifications/ExpeditionNote.h"
22
#include "notifications/ShipNote.h"
23
#include "ogl/glArchivItem_Bitmap.h"
24
#include "ogl/glArchivItem_Bitmap_Player.h"
25
#include "postSystem/ShipPostMsg.h"
26
#include "random/Random.h"
27
#include "world/GameWorld.h"
28
#include "gameData/BuildingConsts.h"
29
#include "gameData/ShipNames.h"
30
#include "s25util/Log.h"
31
#include <array>
32

33
/// Zeit zum Beladen des Schiffes
34
const unsigned LOADING_TIME = 200;
35
/// Zeit zum Entladen des Schiffes
36
const unsigned UNLOADING_TIME = 200;
37

38
/// Maximaler Weg, der zurückgelegt werden kann bei einem Erkundungsschiff
39
const unsigned MAX_EXPLORATION_EXPEDITION_DISTANCE = 100;
40
/// Zeit (in GF), die das Schiff bei der Erkundungs-Expedition jeweils an einem Punkt ankert
41
const unsigned EXPLORATION_EXPEDITION_WAITING_TIME = 300;
42

43
/// Positionen der Flaggen am Schiff für die 6 unterschiedlichen Richtungen jeweils
44
constexpr std::array<helpers::EnumArray<DrawPoint, Direction>, 2> SHIPS_FLAG_POS = {{
45
  {{{-3, -77}, {-6, -71}, {-3, -71}, {-1, -71}, {5, -63}, {-1, -70}}}, // Standing (sails down)
46
  {{{3, -70}, {0, -64}, {3, -64}, {-1, -70}, {5, -63}, {5, -63}}}      // Driving
47
}};
48

49
noShip::noShip(const MapPoint pos, const unsigned char player)
21✔
50
    : noMovable(NodalObjectType::Ship, pos), ownerId_(player), state(State::Idle), seaId_(0), goal_harborId(0),
51
      goal_dir(0), name(RANDOM_ELEMENT(ship_names[world->GetPlayer(player).nation])), curRouteIdx(0), lost(false),
21✔
52
      remaining_sea_attackers(0), home_harbor(0), covered_distance(0)
42✔
53
{
54
    // Meer ermitteln, auf dem dieses Schiff fährt
55
    for(const auto dir : helpers::EnumRange<Direction>{})
336✔
56
    {
57
        unsigned short seaId = world->GetNeighbourNode(pos, dir).seaId;
126✔
58
        if(seaId)
126✔
59
            this->seaId_ = seaId;
118✔
60
    }
61

62
    // Auf irgendeinem Meer müssen wir ja sein
63
    RTTR_Assert(seaId_ > 0);
21✔
64
}
21✔
65

66
noShip::~noShip() = default;
42✔
67

68
void noShip::Serialize(SerializedGameData& sgd) const
×
69
{
70
    noMovable::Serialize(sgd);
×
71

72
    sgd.PushUnsignedChar(ownerId_);
×
73
    sgd.PushEnum<uint8_t>(state);
×
74
    sgd.PushUnsignedShort(seaId_);
×
75
    sgd.PushUnsignedInt(goal_harborId);
×
76
    sgd.PushUnsignedChar(goal_dir);
×
77
    sgd.PushString(name);
×
78
    sgd.PushUnsignedInt(curRouteIdx);
×
79
    sgd.PushBool(lost);
×
80
    sgd.PushUnsignedInt(remaining_sea_attackers);
×
81
    sgd.PushUnsignedInt(home_harbor);
×
82
    sgd.PushUnsignedInt(covered_distance);
×
83
    helpers::pushContainer(sgd, route_);
×
84
    sgd.PushObjectContainer(figures);
×
85
    sgd.PushObjectContainer(wares, true);
×
86
}
×
87

88
noShip::noShip(SerializedGameData& sgd, const unsigned obj_id)
×
89
    : noMovable(sgd, obj_id), ownerId_(sgd.PopUnsignedChar()), state(sgd.Pop<State>()), seaId_(sgd.PopUnsignedShort()),
×
90
      goal_harborId(sgd.PopUnsignedInt()), goal_dir(sgd.PopUnsignedChar()),
×
91
      name(sgd.GetGameDataVersion() < 2 ? sgd.PopLongString() : sgd.PopString()), curRouteIdx(sgd.PopUnsignedInt()),
×
92
      route_(sgd.GetGameDataVersion() < 7 ? sgd.PopUnsignedInt() : 0), lost(sgd.PopBool()),
×
93
      remaining_sea_attackers(sgd.PopUnsignedInt()), home_harbor(sgd.PopUnsignedInt()),
×
94
      covered_distance(sgd.PopUnsignedInt())
×
95
{
96
    helpers::popContainer(sgd, route_, sgd.GetGameDataVersion() < 7);
×
97
    sgd.PopObjectContainer(figures);
×
98
    sgd.PopObjectContainer(wares, GO_Type::Ware);
×
99
}
×
100

101
void noShip::Destroy()
×
102
{
103
    RTTR_Assert(figures.empty());
×
104
    RTTR_Assert(wares.empty());
×
105
    world->GetNotifications().publish(ShipNote(ShipNote::Destroyed, ownerId_, pos));
×
106
    // Schiff wieder abmelden
107
    world->GetPlayer(ownerId_).RemoveShip(this);
×
108
}
×
109

110
void noShip::Draw(DrawPoint drawPt)
×
111
{
112
    unsigned flag_drawing_type = 1;
×
113

114
    // Sind wir verloren? Dann immer stehend zeichnen
115
    if(lost)
×
116
    {
117
        DrawFixed(drawPt, true);
×
118
        return;
×
119
    }
120

121
    switch(state)
×
122
    {
123
        default: break;
×
124
        case State::Idle:
×
125
        case State::SeaattackWaiting:
126
        {
127
            DrawFixed(drawPt, false);
×
128
            flag_drawing_type = 0;
×
129
        }
130
        break;
×
131

132
        case State::Gotoharbor:
×
133
        {
134
            DrawDriving(drawPt);
×
135
        }
136
        break;
×
137
        case State::ExpeditionLoading:
×
138
        case State::ExpeditionUnloading:
139
        case State::TransportLoading:
140
        case State::TransportUnloading:
141
        case State::SeaattackLoading:
142
        case State::SeaattackUnloading:
143
        case State::ExplorationexpeditionLoading:
144
        case State::ExplorationexpeditionUnloading:
145
        {
146
            DrawFixed(drawPt, false);
×
147
        }
148
        break;
×
149
        case State::ExplorationexpeditionWaiting:
×
150
        case State::ExpeditionWaiting:
151
        {
152
            DrawFixed(drawPt, true);
×
153
        }
154
        break;
×
155
        case State::ExpeditionDriving:
×
156
        case State::TransportDriving:
157
        case State::SeaattackDrivingToDestination:
158
        case State::ExplorationexpeditionDriving:
159
        {
160
            DrawDrivingWithWares(drawPt);
×
161
        }
162
        break;
×
163
        case State::SeaattackReturnDriving:
×
164
        {
165
            if(!figures.empty() || !wares.empty())
×
166
                DrawDrivingWithWares(drawPt);
×
167
            else
168
                DrawDriving(drawPt);
×
169
        }
170
        break;
×
171
    }
172

173
    LOADER.GetPlayerImage("boot_z", 40 + GAMECLIENT.GetGlobalAnimation(6, 1, 1, GetObjId()))
×
174
      ->DrawFull(drawPt + SHIPS_FLAG_POS[flag_drawing_type][GetCurMoveDir()], COLOR_WHITE,
×
175
                 world->GetPlayer(ownerId_).color);
×
176
    // Second, white flag, only when on expedition, always swinging in the opposite direction
177
    if(state >= State::ExpeditionLoading && state <= State::ExpeditionDriving)
×
178
        LOADER.GetPlayerImage("boot_z", 40 + GAMECLIENT.GetGlobalAnimation(6, 1, 1, GetObjId() + 4))
×
179
          ->DrawFull(drawPt + SHIPS_FLAG_POS[flag_drawing_type][GetCurMoveDir()]);
×
180
}
181

182
/// Zeichnet das Schiff stehend mit oder ohne Waren
183
void noShip::DrawFixed(DrawPoint drawPt, const bool draw_wares)
×
184
{
185
    LOADER.GetImageN("boot_z", rttr::enum_cast(GetCurMoveDir() + 3u) * 2 + 1)->DrawFull(drawPt, COLOR_SHADOW);
×
186
    LOADER.GetImageN("boot_z", rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt);
×
187

188
    if(draw_wares)
×
189
        /// Waren zeichnen
190
        LOADER.GetImageN("boot_z", 30 + rttr::enum_cast(GetCurMoveDir() + 3u))->DrawFull(drawPt);
×
191
}
×
192

193
/// Zeichnet normales Fahren auf dem Meer ohne irgendwelche Güter
194
void noShip::DrawDriving(DrawPoint& drawPt)
×
195
{
196
    // Interpolieren zwischen beiden Knotenpunkten
197
    drawPt += CalcWalkingRelative();
×
198

199
    LOADER.GetImageN("boot_z", 13 + rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt, COLOR_SHADOW);
×
200
    LOADER.GetImageN("boot_z", 12 + rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt);
×
201
}
×
202

203
/// Zeichnet normales Fahren auf dem Meer mit Gütern
204
void noShip::DrawDrivingWithWares(DrawPoint& drawPt)
×
205
{
206
    DrawDriving(drawPt);
×
207
    /// Waren zeichnen
208
    LOADER.GetImageN("boot_z", 30 + rttr::enum_cast(GetCurMoveDir() + 3u))->DrawFull(drawPt);
×
209
}
×
210

211
void noShip::HandleEvent(const unsigned id)
409✔
212
{
213
    RTTR_Assert(current_ev);
409✔
214
    RTTR_Assert(current_ev->id == id);
409✔
215
    current_ev = nullptr;
409✔
216

217
    if(id == 0)
409✔
218
    {
219
        // Move event
220
        // neue Position einnehmen
221
        Walk();
378✔
222
        // entscheiden, was als nächstes zu tun ist
223
        Driven();
378✔
224
    } else
225
    {
226
        switch(state)
31✔
227
        {
228
            default:
×
229
                RTTR_Assert(false);
×
230
                LOG.write("Bug detected: Invalid state in ship event");
231
                break;
232
            case State::ExpeditionLoading:
2✔
233
                // Schiff ist nun bereit und Expedition kann beginnen
234
                state = State::ExpeditionWaiting;
2✔
235

236
                // Spieler benachrichtigen
237
                SendPostMessage(ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
2✔
238
                                                                        _("A ship is ready for an expedition."),
2✔
239
                                                                        PostCategory::Economy, *this));
2✔
240
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
2✔
241
                break;
2✔
242
            case State::ExplorationexpeditionLoading:
8✔
243
            case State::ExplorationexpeditionWaiting:
244
                // Schiff ist nun bereit und Expedition kann beginnen
245
                ContinueExplorationExpedition();
8✔
246
                break;
8✔
247
            case State::ExpeditionUnloading:
1✔
248
            {
249
                // Hafen herausfinden
250
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
1✔
251

252
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
1✔
253
                {
254
                    Inventory goods;
1✔
255
                    goods.goods[GoodType::Boards] = BUILDING_COSTS[BuildingType::HarborBuilding].boards;
1✔
256
                    goods.goods[GoodType::Stones] = BUILDING_COSTS[BuildingType::HarborBuilding].stones;
1✔
257
                    goods.people[Job::Builder] = 1;
1✔
258
                    static_cast<nobBaseWarehouse*>(hb)->AddGoods(goods, false);
1✔
259
                    // Wieder idlen und ggf. neuen Job suchen
260
                    StartIdling();
1✔
261
                    world->GetPlayer(ownerId_).GetJobForShip(*this);
1✔
262
                } else
263
                {
264
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
265
                    state = State::ExpeditionDriving;
×
266
                    HandleState_ExpeditionDriving();
×
267
                }
268
                break;
1✔
269
            }
270
            case State::ExplorationexpeditionUnloading:
3✔
271
            {
272
                // Hafen herausfinden
273
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
3✔
274

275
                unsigned old_visual_range = GetVisualRange();
3✔
276

277
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
3✔
278
                {
279
                    // Späher wieder entladen
280
                    Inventory goods;
3✔
281
                    goods.people[Job::Scout] = world->GetGGS().GetNumScoutsExpedition();
3✔
282
                    static_cast<nobBaseWarehouse*>(hb)->AddGoods(goods, false);
3✔
283
                    // Wieder idlen und ggf. neuen Job suchen
284
                    StartIdling();
3✔
285
                    world->GetPlayer(ownerId_).GetJobForShip(*this);
3✔
286
                } else
287
                {
288
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
289
                    state = State::ExplorationexpeditionDriving;
×
290
                    HandleState_ExplorationExpeditionDriving();
×
291
                }
292

293
                // Sichtbarkeiten neu berechnen
294
                world->RecalcVisibilitiesAroundPoint(pos, old_visual_range, ownerId_, nullptr);
3✔
295

296
                break;
3✔
297
            }
298
            case State::TransportLoading: StartTransport(); break;
4✔
299
            case State::TransportUnloading:
5✔
300
            case State::SeaattackUnloading:
301
            {
302
                // Hafen herausfinden
303
                RTTR_Assert(state == State::SeaattackUnloading || remaining_sea_attackers == 0);
5✔
304
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
5✔
305
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
5✔
306
                {
307
                    static_cast<nobHarborBuilding*>(hb)->ReceiveGoodsFromShip(figures, wares);
5✔
308
                    figures.clear();
5✔
309
                    wares.clear();
5✔
310

311
                    state = State::TransportUnloading;
5✔
312
                    // Hafen bescheid sagen, dass er das Schiff nun nutzen kann
313
                    static_cast<nobHarborBuilding*>(hb)->ShipArrived(*this);
5✔
314

315
                    // Hafen hat keinen Job für uns?
316
                    if(state == State::TransportUnloading)
5✔
317
                    {
318
                        // Wieder idlen und ggf. neuen Job suchen
319
                        StartIdling();
5✔
320
                        world->GetPlayer(ownerId_).GetJobForShip(*this);
5✔
321
                    }
322
                } else
323
                {
324
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
325
                    if(state == State::TransportUnloading)
×
326
                        FindUnloadGoal(State::TransportDriving);
×
327
                    else
328
                        FindUnloadGoal(State::SeaattackReturnDriving);
×
329
                }
330
                break;
5✔
331
            }
332
            case State::SeaattackLoading: StartSeaAttack(); break;
2✔
333
            case State::SeaattackWaiting:
6✔
334
            {
335
                // Nächsten Soldaten nach draußen beordern
336
                if(figures.empty())
6✔
337
                    break;
2✔
338

339
                // Evtl. ist ein Angreifer schon fertig und wieder an Board gegangen
340
                // der darf dann natürlich nicht noch einmal raus, sonst kann die schöne Reise
341
                // böse enden
342
                if(static_cast<nofAttacker&>(*figures.front()).IsSeaAttackCompleted())
4✔
343
                    break;
×
344

345
                auto& attacker = world->AddFigure(pos, std::move(figures.front()));
4✔
346
                figures.pop_front();
4✔
347

348
                current_ev = GetEvMgr().AddEvent(this, 30, 1);
4✔
349
                static_cast<nofAttacker&>(attacker).StartAttackOnOtherIsland(pos, GetObjId());
4✔
350
                break;
4✔
351
            }
352
        }
353
    }
354
}
409✔
355

356
void noShip::StartDriving(const Direction dir)
382✔
357
{
358
    const std::array<unsigned, 5> SHIP_SPEEDS = {35, 25, 20, 10, 5};
382✔
359

360
    StartMoving(dir, SHIP_SPEEDS[world->GetGGS().getSelection(AddonId::SHIP_SPEED)]);
382✔
361
}
382✔
362

363
void noShip::Driven()
380✔
364
{
365
    MapPoint enemy_territory_discovered(MapPoint::Invalid());
380✔
366
    world->RecalcMovingVisibilities(pos, ownerId_, GetVisualRange(), GetCurMoveDir(), &enemy_territory_discovered);
380✔
367

368
    // Feindliches Territorium entdeckt?
369
    if(enemy_territory_discovered.isValid())
380✔
370
    {
371
        // Send message if necessary
372
        if(world->GetPlayer(ownerId_).ShipDiscoveredHostileTerritory(enemy_territory_discovered))
25✔
373
            SendPostMessage(ownerId_, std::make_unique<PostMsg>(GetEvMgr().GetCurrentGF(),
1✔
374
                                                                _("A ship disovered an enemy territory"),
1✔
375
                                                                PostCategory::Military, enemy_territory_discovered));
2✔
376
    }
377

378
    switch(state)
380✔
379
    {
380
        case State::Gotoharbor: HandleState_GoToHarbor(); break;
40✔
381
        case State::ExpeditionDriving: HandleState_ExpeditionDriving(); break;
42✔
382
        case State::ExplorationexpeditionDriving: HandleState_ExplorationExpeditionDriving(); break;
189✔
383
        case State::TransportDriving: HandleState_TransportDriving(); break;
64✔
384
        case State::SeaattackDrivingToDestination: HandleState_SeaAttackDriving(); break;
31✔
385
        case State::SeaattackReturnDriving: HandleState_SeaAttackReturn(); break;
14✔
386
        default: RTTR_Assert(false); break;
×
387
    }
388
}
380✔
389

390
bool noShip::IsLoading() const
11✔
391
{
392
    return state == State::ExpeditionLoading || state == State::ExplorationexpeditionLoading
11✔
393
           || state == State::TransportLoading || state == State::SeaattackLoading;
22✔
394
}
395

396
bool noShip::IsUnloading() const
100✔
397
{
398
    return state == State::ExpeditionUnloading || state == State::ExplorationexpeditionUnloading
100✔
399
           || state == State::TransportUnloading || state == State::SeaattackUnloading;
200✔
400
}
401

402
bool noShip::IsOnBoard(const noFigure& figure) const
×
403
{
404
    return helpers::containsPtr(figures, &figure);
×
405
}
406

407
/// Gibt Sichtradius dieses Schiffes zurück
408
unsigned noShip::GetVisualRange() const
4,869✔
409
{
410
    // Erkundungsschiffe haben einen größeren Sichtbereich
411
    if(state >= State::ExplorationexpeditionLoading && state <= State::ExplorationexpeditionDriving)
4,869✔
412
        return VISUALRANGE_EXPLORATION_SHIP;
3,975✔
413
    else
414
        return VISUALRANGE_SHIP;
894✔
415
}
416

417
/// Fährt zum Hafen, um dort eine Mission (Expedition) zu erledigen
418
void noShip::GoToHarbor(const nobHarborBuilding& hb, const std::vector<Direction>& route)
9✔
419
{
420
    RTTR_Assert(state == State::Idle); // otherwise we might carry wares etc
9✔
421
    RTTR_Assert(figures.empty());
9✔
422
    RTTR_Assert(wares.empty());
9✔
423
    RTTR_Assert(remaining_sea_attackers == 0);
9✔
424

425
    state = State::Gotoharbor;
9✔
426

427
    goal_harborId = world->GetNode(hb.GetPos()).harborId;
9✔
428
    RTTR_Assert(goal_harborId);
9✔
429

430
    // Route merken
431
    this->route_ = route;
9✔
432
    curRouteIdx = 1;
9✔
433

434
    // losfahren
435
    StartDriving(route[0]);
9✔
436
}
9✔
437

438
/// Startet eine Expedition
439
void noShip::StartExpedition(unsigned homeHarborId)
2✔
440
{
441
    /// Schiff wird "beladen", also kurze Zeit am Hafen stehen, bevor wir bereit sind
442
    state = State::ExpeditionLoading;
2✔
443
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
2✔
444
    RTTR_Assert(homeHarborId);
2✔
445
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
2✔
446
    home_harbor = homeHarborId;
2✔
447
    goal_harborId = homeHarborId; // This is current goal (commands are relative to current goal)
2✔
448
}
2✔
449

450
/// Startet eine Erkundungs-Expedition
451
void noShip::StartExplorationExpedition(unsigned homeHarborId)
4✔
452
{
453
    /// Schiff wird "beladen", also kurze Zeit am Hafen stehen, bevor wir bereit sind
454
    state = State::ExplorationexpeditionLoading;
4✔
455
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
4✔
456
    covered_distance = 0;
4✔
457
    RTTR_Assert(homeHarborId);
4✔
458
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
4✔
459
    home_harbor = homeHarborId;
4✔
460
    goal_harborId = homeHarborId; // This is current goal (commands are relative to current goal)
4✔
461
    // Sichtbarkeiten neu berechnen
462
    world->MakeVisibleAroundPoint(pos, GetVisualRange(), ownerId_);
4✔
463
}
4✔
464

465
/// Fährt weiter zu einem Hafen
466
noShip::Result noShip::DriveToHarbour()
242✔
467
{
468
    if(!goal_harborId)
242✔
469
        return Result::HarborDoesntExist;
3✔
470

471
    MapPoint goal(world->GetHarborPoint(goal_harborId));
239✔
472
    RTTR_Assert(goal.isValid());
239✔
473

474
    // Existiert der Hafen überhaupt noch?
475
    if(world->GetGOT(goal) != GO_Type::NobHarborbuilding)
239✔
476
        return Result::HarborDoesntExist;
×
477

478
    return DriveToHarbourPlace();
239✔
479
}
480

481
/// Fährt weiter zu Hafenbauplatz
482
noShip::Result noShip::DriveToHarbourPlace()
396✔
483
{
484
    if(goal_harborId == 0)
396✔
485
        return Result::HarborDoesntExist;
×
486

487
    // Sind wir schon da?
488
    if(curRouteIdx == route_.size())
396✔
489
        return Result::GoalReached;
25✔
490

491
    MapPoint goalRoutePos;
371✔
492

493
    // Route überprüfen
494
    if(!world->CheckShipRoute(pos, route_, curRouteIdx, &goalRoutePos))
371✔
495
    {
496
        // Route kann nicht mehr passiert werden --> neue Route suchen
497
        if(!world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr))
×
498
        {
499
            // Wieder keine gefunden -> raus
500
            return Result::NoRouteFound;
×
501
        }
502

503
        // Wir fangen bei der neuen Route wieder von vorne an
504
        curRouteIdx = 0;
×
505
    } else if(goalRoutePos != world->GetCoastalPoint(goal_harborId, seaId_))
371✔
506
    {
507
        // Our goal point of the current route has changed
508
        // If we are close to it, recalculate the route
509
        RTTR_Assert(route_.size() >= curRouteIdx);
×
510
        if(route_.size() - curRouteIdx < 10)
×
511
        {
512
            if(!world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr))
×
513
                // Keiner gefunden -> raus
514
                return Result::NoRouteFound;
×
515

516
            curRouteIdx = 0;
×
517
        }
518
    }
519

520
    // Already arrived? (e. g. adjacent harbor)
521
    if(curRouteIdx == route_.size())
371✔
NEW
522
        return Result::GoalReached;
×
523
    else
524
        StartDriving(route_[curRouteIdx++]);
371✔
525

526
    return Result::Driving;
371✔
527
}
528

529
unsigned noShip::GetCurrentHarbor() const
3✔
530
{
531
    RTTR_Assert(state == State::ExpeditionWaiting);
3✔
532
    return goal_harborId;
3✔
533
}
534

535
unsigned noShip::GetTargetHarbor() const
42✔
536
{
537
    return goal_harborId;
42✔
538
}
539

540
unsigned noShip::GetHomeHarbor() const
11✔
541
{
542
    return home_harbor;
11✔
543
}
544

545
/// Weist das Schiff an, in einer bestimmten Richtung die Expedition fortzusetzen
546
void noShip::ContinueExpedition(const ShipDirection dir)
5✔
547
{
548
    if(state != State::ExpeditionWaiting)
5✔
549
        return;
2✔
550

551
    // Nächsten Hafenpunkt in dieser Richtung suchen
552
    unsigned new_goal = world->GetNextFreeHarborPoint(pos, goal_harborId, dir, ownerId_);
3✔
553

554
    // Auch ein Ziel gefunden?
555
    if(!new_goal)
3✔
556
        return;
1✔
557

558
    // Versuchen, Weg zu finden
559
    if(!world->FindShipPathToHarbor(pos, new_goal, seaId_, &route_, nullptr))
2✔
560
        return;
×
561

562
    // Dann fahren wir da mal hin
563
    curRouteIdx = 0;
2✔
564
    goal_harborId = new_goal;
2✔
565

566
    // Already arrived? (e. g. adjacent harbor)
567
    if(curRouteIdx == route_.size())
2✔
568
    {
NEW
569
        state = State::ExpeditionWaiting;
×
NEW
570
        return;
×
571
    } else
572
        state = State::ExpeditionDriving;
2✔
573

574
    StartDriving(route_[curRouteIdx++]);
2✔
575
}
576

577
/// Weist das Schiff an, eine Expedition abzubrechen (nur wenn es steht) und zum
578
/// Hafen zurückzukehren
579
void noShip::CancelExpedition()
3✔
580
{
581
    // Protect against double execution
582
    if(state != State::ExpeditionWaiting)
3✔
583
        return;
2✔
584

585
    // We are waiting. There should be no event!
586
    RTTR_Assert(!current_ev);
1✔
587

588
    // Zum Heimathafen zurückkehren
589
    // Oder sind wir schon dort?
590
    if(goal_harborId == home_harbor)
1✔
591
    {
592
        route_.clear();
×
593
        curRouteIdx = 0;
×
594
        state = State::ExpeditionDriving; // just in case the home harbor was destroyed
×
595
        HandleState_ExpeditionDriving();
×
596
    } else
597
    {
598
        state = State::ExpeditionDriving;
1✔
599
        goal_harborId = home_harbor;
1✔
600
        StartDrivingToHarborPlace();
1✔
601
        HandleState_ExpeditionDriving();
1✔
602
    }
603
}
604

605
/// Weist das Schiff an, an der aktuellen Position einen Hafen zu gründen
606
void noShip::FoundColony()
4✔
607
{
608
    if(state != State::ExpeditionWaiting)
4✔
609
        return;
2✔
610

611
    // Kolonie gründen
612
    if(world->FoundColony(goal_harborId, ownerId_, seaId_))
2✔
613
    {
614
        // For checks
615
        state = State::ExpeditionUnloading;
1✔
616
        // Dann idlen wir wieder
617
        StartIdling();
1✔
618
        // Neue Arbeit suchen
619
        world->GetPlayer(ownerId_).GetJobForShip(*this);
1✔
620
    } else // colony founding FAILED
621
        world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
1✔
622
}
623

624
void noShip::HandleState_GoToHarbor()
40✔
625
{
626
    // Hafen schon zerstört?
627
    if(goal_harborId == 0)
40✔
628
    {
629
        StartIdling();
1✔
630
        return;
1✔
631
    }
632

633
    Result res = DriveToHarbour();
39✔
634
    switch(res)
39✔
635
    {
636
        case Result::Driving: return; // Continue
32✔
637
        case Result::GoalReached:
7✔
638
        {
639
            MapPoint goal(world->GetHarborPoint(goal_harborId));
7✔
640
            RTTR_Assert(goal.isValid());
7✔
641
            // Go idle here (if harbor does not need it)
642
            StartIdling();
7✔
643
            // Hafen Bescheid sagen, dass wir da sind (falls er überhaupt noch existiert)
644
            noBase* hb = goal.isValid() ? world->GetNO(goal) : nullptr;
7✔
645
            if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
7✔
646
                static_cast<nobHarborBuilding*>(hb)->ShipArrived(*this);
7✔
647
        }
648
        break;
7✔
649
        case Result::NoRouteFound:
×
650
        {
651
            MapPoint goal(world->GetHarborPoint(goal_harborId));
×
652
            RTTR_Assert(goal.isValid());
×
653
            // Dem Hafen Bescheid sagen
654
            world->GetSpecObj<nobHarborBuilding>(goal)->ShipLost(this);
×
655
            StartIdling();
×
656
        }
657
        break;
×
658
        case Result::HarborDoesntExist: StartIdling(); break;
×
659
    }
660
}
661

662
void noShip::HandleState_ExpeditionDriving()
43✔
663
{
664
    Result res;
665
    // Zum Heimathafen fahren?
666
    if(home_harbor == goal_harborId)
43✔
667
        res = DriveToHarbour();
15✔
668
    else
669
        res = DriveToHarbourPlace();
28✔
670

671
    switch(res)
43✔
672
    {
673
        case Result::Driving: return;
40✔
674
        case Result::GoalReached:
3✔
675
        {
676
            // Haben wir unsere Expedition beendet?
677
            if(home_harbor == goal_harborId)
3✔
678
            {
679
                // Sachen wieder in den Hafen verladen
680
                state = State::ExpeditionUnloading;
1✔
681
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
682
            } else
683
            {
684
                // Warten auf weitere Anweisungen
685
                state = State::ExpeditionWaiting;
2✔
686

687
                // Spieler benachrichtigen
688
                SendPostMessage(
4✔
689
                  ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
6✔
690
                                                          _("A ship has reached the destination of its expedition."),
2✔
691
                                                          PostCategory::Economy, *this));
2✔
692
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
2✔
693
            }
694
        }
695
        break;
3✔
696
        case Result::NoRouteFound:
×
697
        case Result::HarborDoesntExist: // should only happen when an expedition is cancelled and the home harbor no
698
                                        // longer exists
699
        {
700
            if(home_harbor != goal_harborId && home_harbor != 0)
×
701
            {
702
                // Try to go back
703
                goal_harborId = home_harbor;
×
704
                HandleState_ExpeditionDriving();
×
705
            } else
706
                FindUnloadGoal(State::ExpeditionDriving); // Unload anywhere!
×
707
        }
708
        break;
×
709
    }
710
}
711

712
void noShip::HandleState_ExplorationExpeditionDriving()
197✔
713
{
714
    Result res;
715
    // Zum Heimathafen fahren?
716
    if(home_harbor == goal_harborId)
197✔
717
        res = DriveToHarbour();
101✔
718
    else
719
        res = DriveToHarbourPlace();
96✔
720

721
    switch(res)
197✔
722
    {
723
        case Result::Driving: return;
189✔
724
        case Result::GoalReached:
7✔
725
        {
726
            // Haben wir unsere Expedition beendet?
727
            if(home_harbor == goal_harborId)
7✔
728
            {
729
                // Dann sind wir fertig -> wieder entladen
730
                state = State::ExplorationexpeditionUnloading;
3✔
731
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
3✔
732
            } else
733
            {
734
                // Strecke, die wir gefahren sind, draufaddieren
735
                covered_distance += route_.size();
4✔
736
                // Erstmal kurz ausruhen an diesem Punkt und das Rohr ausfahren, um ein bisschen
737
                // auf der Insel zu gucken
738
                state = State::ExplorationexpeditionWaiting;
4✔
739
                current_ev = GetEvMgr().AddEvent(this, EXPLORATION_EXPEDITION_WAITING_TIME, 1);
4✔
740
            }
741
        }
742
        break;
7✔
743
        case Result::NoRouteFound:
1✔
744
        case Result::HarborDoesntExist:
745
            if(home_harbor != goal_harborId && home_harbor != 0)
1✔
746
            {
747
                // Try to go back
748
                goal_harborId = home_harbor;
×
749
                HandleState_ExplorationExpeditionDriving();
×
750
            } else
751
                FindUnloadGoal(State::ExplorationexpeditionDriving); // Unload anywhere!
1✔
752
            break;
1✔
753
    }
754
}
755

756
void noShip::HandleState_TransportDriving()
71✔
757
{
758
    Result res = DriveToHarbour();
71✔
759
    switch(res)
71✔
760
    {
761
        case Result::Driving: return;
64✔
762
        case Result::GoalReached:
5✔
763
        {
764
            // Waren abladen, dafür wieder kurze Zeit hier ankern
765
            state = State::TransportUnloading;
5✔
766
            current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
5✔
767
        }
768
        break;
5✔
769
        case Result::NoRouteFound:
2✔
770
        case Result::HarborDoesntExist:
771
        {
772
            RTTR_Assert(!remaining_sea_attackers);
2✔
773
            // Kein Hafen mehr?
774
            // Dann müssen alle Leute ihren Heimatgebäuden Bescheid geben, dass sie
775
            // nun nicht mehr kommen
776
            // Das Schiff muss einen Notlandeplatz ansteuern
777
            // LOG.write(("transport goal harbor doesnt exist player %i state %i pos %u,%u \n",player,state,x,y);
778
            for(auto& figure : figures)
2✔
779
            {
780
                figure->Abrogate();
×
781
                figure->SetGoalTonullptr();
×
782
            }
783

784
            for(auto& ware : wares)
4✔
785
            {
786
                ware->NotifyGoalAboutLostWare();
2✔
787
            }
788

789
            FindUnloadGoal(State::TransportDriving);
2✔
790
        }
791
        break;
2✔
792
    }
793
}
794

795
void noShip::HandleState_SeaAttackDriving()
33✔
796
{
797
    Result res = DriveToHarbourPlace();
33✔
798
    switch(res)
33✔
799
    {
800
        case Result::Driving: return; // OK
31✔
801
        case Result::GoalReached:
2✔
802
            // Ziel erreicht, dann stellen wir das Schiff hier hin und die Soldaten laufen nacheinander raus zum Ziel
803
            state = State::SeaattackWaiting;
2✔
804
            current_ev = GetEvMgr().AddEvent(this, 15, 1);
2✔
805
            remaining_sea_attackers = figures.size();
2✔
806
            break;
2✔
807
        case Result::NoRouteFound:
×
808
        case Result::HarborDoesntExist:
809
            RTTR_Assert(goal_harborId != home_harbor || home_harbor == 0);
×
810
            AbortSeaAttack();
×
811
            break;
×
812
    }
813
}
814

815
void noShip::HandleState_SeaAttackReturn()
16✔
816
{
817
    Result res = DriveToHarbour();
16✔
818
    switch(res)
16✔
819
    {
820
        case Result::Driving: return;
15✔
821
        case Result::GoalReached:
1✔
822
            // Entladen
823
            state = State::SeaattackUnloading;
1✔
824
            this->current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
825
            break;
1✔
826
        case Result::HarborDoesntExist:
×
827
        case Result::NoRouteFound: AbortSeaAttack(); break;
×
828
    }
829
}
830

831
/// Gibt zurück, ob das Schiff jetzt in der Lage wäre, eine Kolonie zu gründen
832
bool noShip::IsAbleToFoundColony() const
×
833
{
834
    // Warten wir gerade?
835
    if(state == State::ExpeditionWaiting)
×
836
    {
837
        // We must always have a goal harbor
838
        RTTR_Assert(goal_harborId);
×
839
        // Ist der Punkt, an dem wir gerade ankern, noch frei?
840
        if(world->IsHarborPointFree(goal_harborId, ownerId_))
×
841
            return true;
×
842
    }
843

844
    return false;
×
845
}
846

847
/// Gibt zurück, ob das Schiff einen bestimmten Hafen ansteuert
848
bool noShip::IsGoingToHarbor(const nobHarborBuilding& hb) const
80✔
849
{
850
    if(goal_harborId != hb.GetHarborPosID())
80✔
851
        return false;
69✔
852
    // Explicit switch to check all states
853
    switch(state)
11✔
854
    {
855
        case State::Idle:
1✔
856
        case State::ExpeditionLoading:
857
        case State::ExpeditionUnloading:
858
        case State::ExpeditionWaiting:
859
        case State::ExpeditionDriving:
860
        case State::ExplorationexpeditionLoading:
861
        case State::ExplorationexpeditionUnloading:
862
        case State::ExplorationexpeditionWaiting:
863
        case State::ExplorationexpeditionDriving:
864
        case State::SeaattackLoading:
865
        case State::SeaattackDrivingToDestination:
866
        case State::SeaattackWaiting: return false;
1✔
867
        case State::Gotoharbor:
10✔
868
        case State::TransportDriving:       // Driving to this harbor
869
        case State::TransportLoading:       // Loading at home harbor and going to goal
870
        case State::TransportUnloading:     // Unloading at this harbor
871
        case State::SeaattackUnloading:     // Unloading attackers at this harbor
872
        case State::SeaattackReturnDriving: // Returning attackers to this harbor
873
            return true;
10✔
874
    }
875
    RTTR_Assert(false);
×
876
    return false;
877
}
878

879
/// Belädt das Schiff mit Waren und Figuren, um eine Transportfahrt zu starten
880
void noShip::PrepareTransport(unsigned homeHarborId, MapPoint goal, std::list<std::unique_ptr<noFigure>> figures,
5✔
881
                              std::list<std::unique_ptr<Ware>> wares)
882
{
883
    RTTR_Assert(homeHarborId);
5✔
884
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
5✔
885
    this->home_harbor = homeHarborId;
5✔
886
    // ID von Zielhafen herausfinden
887
    noBase* nb = world->GetNO(goal);
5✔
888
    RTTR_Assert(nb->GetGOT() == GO_Type::NobHarborbuilding);
5✔
889
    this->goal_harborId = static_cast<nobHarborBuilding*>(nb)->GetHarborPosID();
5✔
890

891
    this->figures = std::move(figures);
5✔
892
    this->wares = std::move(wares);
5✔
893

894
    state = State::TransportLoading;
5✔
895
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
5✔
896
}
5✔
897

898
/// Belädt das Schiff mit Schiffs-Angreifern
899
void noShip::PrepareSeaAttack(unsigned homeHarborId, MapPoint goal, std::vector<std::unique_ptr<nofAttacker>> attackers)
2✔
900
{
901
    // Heimathafen merken
902
    RTTR_Assert(homeHarborId);
2✔
903
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
2✔
904
    home_harbor = homeHarborId;
2✔
905
    goal_harborId = world->GetHarborPointID(goal);
2✔
906
    RTTR_Assert(goal_harborId);
2✔
907
    figures.clear();
2✔
908
    for(auto& attacker : attackers)
6✔
909
    {
910
        attacker->StartShipJourney();
4✔
911
        attacker->SeaAttackStarted();
4✔
912
        figures.push_back(std::move(attacker));
4✔
913
    }
914
    state = State::SeaattackLoading;
2✔
915
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
2✔
916
}
2✔
917

918
/// Startet Schiffs-Angreiff
919
void noShip::StartSeaAttack()
2✔
920
{
921
    state = State::SeaattackDrivingToDestination;
2✔
922
    StartDrivingToHarborPlace();
2✔
923
    HandleState_SeaAttackDriving();
2✔
924
}
2✔
925

926
void noShip::AbortSeaAttack()
×
927
{
928
    RTTR_Assert(state != State::SeaattackWaiting); // figures are not aboard if this fails!
×
929
    RTTR_Assert(remaining_sea_attackers == 0);     // Some soldiers are still not aboard
×
930

931
    if((state == State::SeaattackLoading || state == State::SeaattackDrivingToDestination)
×
932
       && goal_harborId != home_harbor && home_harbor != 0)
×
933
    {
934
        // We did not start the attack yet and we can (possibly) go back to our home harbor
935
        // -> tell the soldiers we go back (like after an attack)
936
        goal_harborId = home_harbor;
×
937
        for(auto& figure : figures)
×
938
            checkedCast<nofAttacker*>(figure.get())->StartReturnViaShip(*this);
×
939
        if(state == State::SeaattackLoading)
×
940
        {
941
            // We are still loading (loading event must be active)
942
            // -> Use it to unload
943
            RTTR_Assert(current_ev);
×
944
            state = State::SeaattackUnloading;
×
945
        } else
946
        {
947
            // Else start driving back
948
            state = State::SeaattackReturnDriving;
×
949
            HandleState_SeaAttackReturn();
×
950
        }
×
951
    } else
952
    {
953
        // attack failed and we cannot go back to our home harbor
954
        // -> Tell figures that they won't go to their planned destination
955
        for(auto& figure : figures)
×
956
            checkedCast<nofAttacker*>(figure.get())->CancelSeaAttack();
×
957

958
        if(state == State::SeaattackLoading)
×
959
        {
960
            // Abort loading
961
            RTTR_Assert(current_ev);
×
962
            GetEvMgr().RemoveEvent(current_ev);
×
963
        }
964

965
        // Das Schiff muss einen Notlandeplatz ansteuern
966
        FindUnloadGoal(State::SeaattackReturnDriving);
×
967
    }
968
}
×
969

970
/// Fängt an zu einem Hafen zu fahren (berechnet Route usw.)
971
void noShip::StartDrivingToHarborPlace()
19✔
972
{
973
    if(!goal_harborId)
19✔
974
    {
975
        route_.clear();
1✔
976
        curRouteIdx = 0;
1✔
977
        return;
1✔
978
    }
979

980
    MapPoint coastalPos = world->GetCoastalPoint(goal_harborId, seaId_);
18✔
981
    if(pos == coastalPos)
18✔
982
        route_.clear();
1✔
983
    else
984
    {
985
        bool routeFound;
986
        // Use upper bound to distance by checking the distance between the harbors if we still have and are at the home
987
        // harbor
988
        if(home_harbor && pos == world->GetCoastalPoint(home_harbor, seaId_))
17✔
989
        {
990
            // Use the maximum distance between the harbors plus 6 fields
991
            unsigned maxDistance = world->CalcHarborDistance(home_harbor, goal_harborId) + 6;
8✔
992
            routeFound = world->FindShipPath(pos, coastalPos, maxDistance, &route_, nullptr);
8✔
993
        } else
994
            routeFound = world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr);
9✔
995
        if(!routeFound)
17✔
996
        {
997
            // todo
998
            RTTR_Assert(false);
×
999
            LOG.write("WARNING: Bug detected (GF: %u). Please report this with the savegame and "
1000
                      "replay.\nnoShip::StartDrivingToHarborPlace: Schiff hat keinen Weg gefunden!\nplayer %i state %i "
1001
                      "pos %u,%u goal "
1002
                      "coastal %u,%u goal-id %i goalpos %u,%u \n")
1003
              % GetEvMgr().GetCurrentGF() % unsigned(ownerId_) % unsigned(state) % pos.x % pos.y % coastalPos.x
1004
              % coastalPos.y % goal_harborId % world->GetHarborPoint(goal_harborId).x
1005
              % world->GetHarborPoint(goal_harborId).y;
1006
            goal_harborId = 0;
1007
            return;
1008
        }
1009
    }
1010
    curRouteIdx = 0;
18✔
1011
}
1012

1013
/// Startet die eigentliche Transportaktion, nachdem das Schiff beladen wurde
1014
void noShip::StartTransport()
4✔
1015
{
1016
    state = State::TransportDriving;
4✔
1017

1018
    StartDrivingToHarborPlace();
4✔
1019
    // Einfach weiterfahren
1020
    HandleState_TransportDriving();
4✔
1021
}
4✔
1022

1023
void noShip::FindUnloadGoal(State newState)
5✔
1024
{
1025
    state = newState;
5✔
1026
    // Das Schiff muss einen Notlandeplatz ansteuern
1027
    // Neuen Hafen suchen
1028
    if(world->GetPlayer(ownerId_).FindHarborForUnloading(this, pos, &goal_harborId, &route_, nullptr))
5✔
1029
    {
1030
        curRouteIdx = 0;
3✔
1031
        home_harbor = goal_harborId; // To allow unloading here
3✔
1032
        if(state == State::ExpeditionDriving)
3✔
1033
            HandleState_ExpeditionDriving();
×
1034
        else if(state == State::ExplorationexpeditionDriving)
3✔
1035
            HandleState_ExplorationExpeditionDriving();
×
1036
        else if(state == State::TransportDriving)
3✔
1037
            HandleState_TransportDriving();
3✔
1038
        else if(state == State::SeaattackReturnDriving)
×
1039
            HandleState_SeaAttackReturn();
×
1040
        else
1041
        {
1042
            RTTR_Assert(false);
×
1043
            LOG.write("Bug detected: Invalid state for FindUnloadGoal");
1044
            FindUnloadGoal(State::TransportDriving);
1045
        }
1046
    } else
1047
    {
1048
        // Ansonsten als verloren markieren, damit uns später Bescheid gesagt wird
1049
        // wenn es einen neuen Hafen gibt
1050
        home_harbor = goal_harborId = 0;
2✔
1051
        lost = true;
2✔
1052
    }
1053
}
5✔
1054

1055
/// Sagt dem Schiff, das ein bestimmter Hafen zerstört wurde
1056
void noShip::HarborDestroyed(nobHarborBuilding* hb)
12✔
1057
{
1058
    const unsigned destroyedHarborId = hb->GetHarborPosID();
12✔
1059
    // Almost every case of a destroyed harbor is handled when the ships event fires (the handler detects the destroyed
1060
    // harbor) So mostly we just reset the corresponding id
1061

1062
    if(destroyedHarborId == home_harbor)
12✔
1063
        home_harbor = 0;
4✔
1064

1065
    // Ist unser Ziel betroffen?
1066
    if(destroyedHarborId != goal_harborId)
12✔
1067
    {
1068
        return;
5✔
1069
    }
1070

1071
    State oldState = state;
7✔
1072

1073
    switch(state)
7✔
1074
    {
1075
        default:
4✔
1076
            // Just reset goal, but not for expeditions
1077
            if(!IsOnExpedition() && !IsOnExplorationExpedition())
4✔
1078
            {
1079
                goal_harborId = 0;
3✔
1080
            }
1081
            return; // Skip the rest
4✔
1082
        case State::TransportLoading:
3✔
1083
        case State::TransportUnloading:
1084
            // Tell wares and figures that they won't reach their goal
1085
            for(auto& figure : figures)
3✔
1086
            {
1087
                figure->Abrogate();
×
1088
                figure->SetGoalTonullptr();
×
1089
            }
1090
            for(auto& ware : wares)
6✔
1091
            {
1092
                // Notify goal only, if it is not the destroyed harbor. It already knows about that ;)
1093
                if(ware->GetGoal() != hb)
3✔
1094
                    ware->NotifyGoalAboutLostWare();
×
1095
                else
1096
                    ware->SetGoal(nullptr);
3✔
1097
            }
1098
            break;
3✔
1099
        case State::SeaattackLoading:
×
1100
            // We could also just set the goal harbor id to 0 but this can reuse the event
1101
            AbortSeaAttack();
×
1102
            break;
×
1103
        case State::SeaattackUnloading: break;
×
1104
    }
1105

1106
    // Are we currently getting the wares?
1107
    if(oldState == State::TransportLoading)
3✔
1108
    {
1109
        RTTR_Assert(current_ev);
1✔
1110
        if(home_harbor)
1✔
1111
        {
1112
            // Then save us some time and unload immediately
1113
            // goal is now the start harbor (if it still exists)
1114
            goal_harborId = home_harbor;
1✔
1115
            state = State::TransportUnloading;
1✔
1116
        } else
1117
        {
1118
            GetEvMgr().RemoveEvent(current_ev);
×
1119
            FindUnloadGoal(State::TransportDriving);
×
1120
        }
1121
    } else if(oldState == State::TransportUnloading || oldState == State::SeaattackUnloading)
2✔
1122
    {
1123
        // Remove current unload event
1124
        GetEvMgr().RemoveEvent(current_ev);
2✔
1125

1126
        if(oldState == State::SeaattackUnloading)
2✔
1127
            AbortSeaAttack();
×
1128
        else
1129
            FindUnloadGoal(State::TransportDriving);
2✔
1130
    }
1131
}
1132

1133
/// Fängt an mit idlen und setzt nötigen Sachen auf nullptr
1134
void noShip::StartIdling()
18✔
1135
{
1136
    // If those are not empty, then we are lost, not idling!
1137
    RTTR_Assert(figures.empty());
18✔
1138
    RTTR_Assert(wares.empty());
18✔
1139
    RTTR_Assert(remaining_sea_attackers == 0);
18✔
1140
    // Implicit contained wares/figures on expeditions
1141
    RTTR_Assert(!IsOnExplorationExpedition() || state == State::ExplorationexpeditionUnloading);
18✔
1142
    RTTR_Assert(!IsOnExpedition() || state == State::ExpeditionUnloading);
18✔
1143

1144
    home_harbor = 0;
18✔
1145
    goal_harborId = 0;
18✔
1146
    state = State::Idle;
18✔
1147
}
18✔
1148

1149
/// Sagt Bescheid, dass ein Schiffsangreifer nicht mehr mit nach Hause fahren will
1150
void noShip::SeaAttackerWishesNoReturn()
4✔
1151
{
1152
    RTTR_Assert(remaining_sea_attackers);
4✔
1153
    RTTR_Assert(state == State::SeaattackWaiting);
4✔
1154

1155
    --remaining_sea_attackers;
4✔
1156
    // Alle Soldaten an Bord
1157
    if(remaining_sea_attackers == 0)
4✔
1158
    {
1159
        // Andere Events ggf. erstmal abmelden
1160
        GetEvMgr().RemoveEvent(current_ev);
2✔
1161
        if(!figures.empty())
2✔
1162
        {
1163
            // Go back home. Note: home_harbor can be 0 if it was destroyed, allow this and let the state handlers
1164
            // handle that case later
1165
            goal_harborId = home_harbor;
2✔
1166
            state = State::SeaattackReturnDriving;
2✔
1167
            StartDrivingToHarborPlace();
2✔
1168
            HandleState_SeaAttackReturn();
2✔
1169
        } else
1170
        {
1171
            // Wenn keine Soldaten mehr da sind können wir auch erstmal idlen
1172
            StartIdling();
×
1173
            world->GetPlayer(ownerId_).GetJobForShip(*this);
×
1174
        }
1175
    }
1176
}
4✔
1177

1178
/// Schiffs-Angreifer sind nach dem Angriff wieder zurückgekehrt
1179
void noShip::AddReturnedAttacker(std::unique_ptr<nofAttacker> attacker)
4✔
1180
{
1181
    RTTR_Assert(!helpers::containsPtr(figures, attacker.get()));
4✔
1182

1183
    figures.push_back(std::move(attacker));
4✔
1184
    // Nun brauchen wir quasi einen Angreifer weniger
1185
    SeaAttackerWishesNoReturn();
4✔
1186
}
4✔
1187

1188
/// Weist das Schiff an, seine Erkundungs-Expedition fortzusetzen
1189
void noShip::ContinueExplorationExpedition()
8✔
1190
{
1191
    // Sind wir schon über unserem Limit, also zu weit gefahren
1192
    if(covered_distance >= MAX_EXPLORATION_EXPEDITION_DISTANCE)
8✔
1193
    {
1194
        // Dann steuern wir unseren Heimathafen an!
1195
        goal_harborId = home_harbor;
×
1196
    } else
1197
    {
1198
        // Find the next harbor spot to explore
1199
        std::vector<unsigned> hps;
16✔
1200
        if(goal_harborId)
8✔
1201
            hps = world->GetUnexploredHarborPoints(goal_harborId, seaId_, GetPlayerId());
8✔
1202

1203
        // No possible spots? -> Go home
1204
        if(hps.empty())
8✔
1205
            goal_harborId = home_harbor;
4✔
1206
        else
1207
        {
1208
            // Choose one randomly
1209
            goal_harborId = RANDOM_ELEMENT(hps);
4✔
1210
        }
1211
    }
1212

1213
    StartDrivingToHarborPlace();
8✔
1214
    state = State::ExplorationexpeditionDriving;
8✔
1215
    HandleState_ExplorationExpeditionDriving();
8✔
1216
}
8✔
1217

1218
/// Sagt dem Schiff, dass ein neuer Hafen erbaut wurde
1219
void noShip::NewHarborBuilt(nobHarborBuilding* hb)
11✔
1220
{
1221
    if(!lost)
11✔
1222
        return;
9✔
1223
    // Liegt der Hafen auch am Meer von diesem Schiff?
1224
    if(!world->IsHarborAtSea(hb->GetHarborPosID(), seaId_))
2✔
1225
        return;
×
1226

1227
    // LOG.write(("lost ship has new goal harbor player %i state %i pos %u,%u \n",player,state,x,y);
1228
    home_harbor = goal_harborId = hb->GetHarborPosID();
2✔
1229
    lost = false;
2✔
1230

1231
    StartDrivingToHarborPlace();
2✔
1232

1233
    switch(state)
2✔
1234
    {
1235
        case State::ExplorationexpeditionDriving:
2✔
1236
        case State::ExpeditionDriving:
1237
        case State::TransportDriving:
1238
        case State::SeaattackReturnDriving: Driven(); break;
2✔
1239
        default:
×
1240
            RTTR_Assert(false); // Das darf eigentlich nicht passieren
×
1241
            LOG.write("Bug detected: Invalid state in NewHarborBuilt");
1242
            break;
1243
    }
1244
}
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