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

Return-To-The-Roots / s25client / 22818081571

08 Mar 2026 09:14AM UTC coverage: 50.336% (+0.009%) from 50.327%
22818081571

push

github

web-flow
Merge pull request #1895 from Noseey/fix_ship_stuck_crash

234 of 308 new or added lines in 23 files covered. (75.97%)

20 existing lines in 3 files now uncovered.

23052 of 45796 relevant lines covered (50.34%)

43414.34 hits per line

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

69.35
/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)
22✔
50
    : noMovable(NodalObjectType::Ship, pos), ownerId_(player), state(State::Idle), goal_dir(0),
51
      name(RANDOM_ELEMENT(ship_names[world->GetPlayer(player).nation])), curRouteIdx(0), lost(false),
22✔
52
      remaining_sea_attackers(0), covered_distance(0)
44✔
53
{
54
    // Meer ermitteln, auf dem dieses Schiff fährt
55
    for(const auto dir : helpers::EnumRange<Direction>{})
352✔
56
    {
57
        SeaId seaId = world->GetNeighbourNode(pos, dir).seaId;
132✔
58
        if(seaId)
132✔
59
            this->seaId_ = seaId;
124✔
60
    }
61

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

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

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

72
    sgd.PushUnsignedChar(ownerId_);
×
73
    sgd.PushEnum<uint8_t>(state);
×
NEW
74
    sgd.PushUnsignedShort(seaId_.value());
×
NEW
75
    sgd.PushUnsignedInt(goalHarbor.value());
×
76
    sgd.PushUnsignedChar(goal_dir);
×
77
    sgd.PushString(name);
×
78
    sgd.PushUnsignedInt(curRouteIdx);
×
79
    sgd.PushBool(lost);
×
80
    sgd.PushUnsignedInt(remaining_sea_attackers);
×
NEW
81
    sgd.PushUnsignedInt(homeHarbor.value());
×
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()),
×
NEW
90
      goalHarbor(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()),
×
NEW
93
      remaining_sea_attackers(sgd.PopUnsignedInt()), homeHarbor(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)
428✔
212
{
213
    RTTR_Assert(current_ev);
428✔
214
    RTTR_Assert(current_ev->id == id);
428✔
215
    current_ev = nullptr;
428✔
216

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

236
                // Spieler benachrichtigen
237
                SendPostMessage(ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
3✔
238
                                                                        _("A ship is ready for an expedition."),
3✔
239
                                                                        PostCategory::Economy, *this));
3✔
240
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
3✔
241
                break;
3✔
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 = goalHarbor ? world->GetNO(world->GetHarborPoint(goalHarbor)) : 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 = goalHarbor ? world->GetNO(world->GetHarborPoint(goalHarbor)) : 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 = goalHarbor ? world->GetNO(world->GetHarborPoint(goalHarbor)) : 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
}
428✔
355

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

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

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

368
    // Feindliches Territorium entdeckt?
369
    if(enemy_territory_discovered.isValid())
398✔
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)
398✔
379
    {
380
        case State::Gotoharbor: HandleState_GoToHarbor(); break;
42✔
381
        case State::ExpeditionDriving: HandleState_ExpeditionDriving(); break;
58✔
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
}
398✔
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,906✔
409
{
410
    // Erkundungsschiffe haben einen größeren Sichtbereich
411
    if(state >= State::ExplorationexpeditionLoading && state <= State::ExplorationexpeditionDriving)
4,906✔
412
        return VISUALRANGE_EXPLORATION_SHIP;
3,975✔
413
    else
414
        return VISUALRANGE_SHIP;
931✔
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)
10✔
419
{
420
    RTTR_Assert(state == State::Idle); // otherwise we might carry wares etc
10✔
421
    RTTR_Assert(figures.empty());
10✔
422
    RTTR_Assert(wares.empty());
10✔
423
    RTTR_Assert(remaining_sea_attackers == 0);
10✔
424

425
    state = State::Gotoharbor;
10✔
426

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

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

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

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

450
/// Startet eine Erkundungs-Expedition
451
void noShip::StartExplorationExpedition(HarborId 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
    homeHarbor = homeHarborId;
4✔
460
    goalHarbor = 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()
244✔
467
{
468
    if(!goalHarbor)
244✔
469
        return Result::HarborDoesntExist;
3✔
470
    const MapPoint goal = world->GetHarborPoint(goalHarbor);
241✔
471

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

476
    return DriveToHarbourPlace();
241✔
477
}
478

479
/// Fährt weiter zu Hafenbauplatz
480
noShip::Result noShip::DriveToHarbourPlace()
419✔
481
{
482
    if(!goalHarbor)
419✔
483
        return Result::HarborDoesntExist;
×
484

485
    // Sind wir schon da?
486
    if(curRouteIdx == route_.size())
419✔
487
        return Result::GoalReached;
28✔
488

489
    MapPoint goalRoutePos;
391✔
490

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

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

514
            curRouteIdx = 0;
×
515
        }
516
    }
517

518
    RTTR_Assert(curRouteIdx < route_.size());
391✔
519
    StartDriving(route_[curRouteIdx++]);
391✔
520
    return Result::Driving;
391✔
521
}
522

523
HarborId noShip::GetCurrentHarbor() const
13✔
524
{
525
    RTTR_Assert(state == State::ExpeditionWaiting);
13✔
526
    return goalHarbor;
13✔
527
}
528

529
HarborId noShip::GetTargetHarbor() const
45✔
530
{
531
    return goalHarbor;
45✔
532
}
533

534
HarborId noShip::GetHomeHarbor() const
11✔
535
{
536
    return homeHarbor;
11✔
537
}
538

539
/// Weist das Schiff an, in einer bestimmten Richtung die Expedition fortzusetzen
540
void noShip::ContinueExpedition(const ShipDirection dir)
8✔
541
{
542
    if(state != State::ExpeditionWaiting)
8✔
543
        return;
3✔
544

545
    // Nächsten Hafenpunkt in dieser Richtung suchen
546
    HarborId new_goal = world->GetNextFreeHarborPoint(pos, goalHarbor, dir, ownerId_);
6✔
547

548
    // Auch ein Ziel gefunden?
549
    if(!new_goal)
6✔
550
        return;
1✔
551

552
    // Versuchen, Weg zu finden
553
    if(!world->FindShipPathToHarbor(pos, new_goal, seaId_, &route_, nullptr))
5✔
554
        return;
×
555

556
    // Dann fahren wir da mal hin
557
    curRouteIdx = 0;
5✔
558
    goalHarbor = new_goal;
5✔
559
    state = State::ExpeditionDriving;
5✔
560

561
    HandleState_ExpeditionDriving();
5✔
562
}
563

564
/// Weist das Schiff an, eine Expedition abzubrechen (nur wenn es steht) und zum
565
/// Hafen zurückzukehren
566
void noShip::CancelExpedition()
3✔
567
{
568
    // Protect against double execution
569
    if(state != State::ExpeditionWaiting)
3✔
570
        return;
2✔
571

572
    // We are waiting. There should be no event!
573
    RTTR_Assert(!current_ev);
1✔
574

575
    // Zum Heimathafen zurückkehren
576
    // Oder sind wir schon dort?
577
    if(goalHarbor == homeHarbor)
1✔
578
    {
579
        route_.clear();
×
580
        curRouteIdx = 0;
×
581
        state = State::ExpeditionDriving; // just in case the home harbor was destroyed
×
582
        HandleState_ExpeditionDriving();
×
583
    } else
584
    {
585
        state = State::ExpeditionDriving;
1✔
586
        goalHarbor = homeHarbor;
1✔
587
        StartDrivingToHarborPlace();
1✔
588
        HandleState_ExpeditionDriving();
1✔
589
    }
590
}
591

592
/// Weist das Schiff an, an der aktuellen Position einen Hafen zu gründen
593
void noShip::FoundColony()
4✔
594
{
595
    if(state != State::ExpeditionWaiting)
4✔
596
        return;
2✔
597

598
    // Kolonie gründen
599
    if(world->FoundColony(goalHarbor, ownerId_, seaId_))
2✔
600
    {
601
        // For checks
602
        state = State::ExpeditionUnloading;
1✔
603
        // Dann idlen wir wieder
604
        StartIdling();
1✔
605
        // Neue Arbeit suchen
606
        world->GetPlayer(ownerId_).GetJobForShip(*this);
1✔
607
    } else // colony founding FAILED
608
        world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
1✔
609
}
610

611
void noShip::HandleState_GoToHarbor()
42✔
612
{
613
    // Hafen schon zerstört?
614
    if(!goalHarbor)
42✔
615
    {
616
        StartIdling();
1✔
617
        return;
1✔
618
    }
619

620
    Result res = DriveToHarbour();
41✔
621
    switch(res)
41✔
622
    {
623
        case Result::Driving: return; // Continue
33✔
624
        case Result::GoalReached:
8✔
625
        {
626
            const MapPoint goal = world->GetHarborPoint(goalHarbor);
8✔
627
            // Go idle here (if harbor does not need it)
628
            StartIdling();
8✔
629
            // Hafen Bescheid sagen, dass wir da sind (falls er überhaupt noch existiert)
630
            noBase* hb = goal.isValid() ? world->GetNO(goal) : nullptr;
8✔
631
            if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
8✔
632
                static_cast<nobHarborBuilding*>(hb)->ShipArrived(*this);
8✔
633
        }
634
        break;
8✔
635
        case Result::NoRouteFound:
×
636
        {
NEW
637
            MapPoint goal(world->GetHarborPoint(goalHarbor));
×
638
            RTTR_Assert(goal.isValid());
×
639
            // Dem Hafen Bescheid sagen
640
            world->GetSpecObj<nobHarborBuilding>(goal)->ShipLost(this);
×
641
            StartIdling();
×
642
        }
643
        break;
×
644
        case Result::HarborDoesntExist: StartIdling(); break;
×
645
    }
646
}
647

648
void noShip::HandleState_ExpeditionDriving()
64✔
649
{
650
    Result res;
651
    // Zum Heimathafen fahren?
652
    if(homeHarbor == goalHarbor)
64✔
653
        res = DriveToHarbour();
15✔
654
    else
655
        res = DriveToHarbourPlace();
49✔
656

657
    switch(res)
64✔
658
    {
659
        case Result::Driving: return;
59✔
660
        case Result::GoalReached:
5✔
661
        {
662
            // Haben wir unsere Expedition beendet?
663
            if(homeHarbor == goalHarbor)
5✔
664
            {
665
                // Sachen wieder in den Hafen verladen
666
                state = State::ExpeditionUnloading;
1✔
667
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
668
            } else
669
            {
670
                // Warten auf weitere Anweisungen
671
                state = State::ExpeditionWaiting;
4✔
672

673
                // Spieler benachrichtigen
674
                SendPostMessage(
8✔
675
                  ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
12✔
676
                                                          _("A ship has reached the destination of its expedition."),
4✔
677
                                                          PostCategory::Economy, *this));
4✔
678
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
4✔
679
            }
680
        }
681
        break;
5✔
682
        case Result::NoRouteFound:
×
683
        case Result::HarborDoesntExist: // should only happen when an expedition is cancelled and the home harbor no
684
                                        // longer exists
685
        {
NEW
686
            if(homeHarbor != goalHarbor && homeHarbor)
×
687
            {
688
                // Try to go back
NEW
689
                goalHarbor = homeHarbor;
×
690
                HandleState_ExpeditionDriving();
×
691
            } else
692
                FindUnloadGoal(State::ExpeditionDriving); // Unload anywhere!
×
693
        }
694
        break;
×
695
    }
696
}
697

698
void noShip::HandleState_ExplorationExpeditionDriving()
197✔
699
{
700
    Result res;
701
    // Zum Heimathafen fahren?
702
    if(homeHarbor == goalHarbor)
197✔
703
        res = DriveToHarbour();
101✔
704
    else
705
        res = DriveToHarbourPlace();
96✔
706

707
    switch(res)
197✔
708
    {
709
        case Result::Driving: return;
189✔
710
        case Result::GoalReached:
7✔
711
        {
712
            // Haben wir unsere Expedition beendet?
713
            if(homeHarbor == goalHarbor)
7✔
714
            {
715
                // Dann sind wir fertig -> wieder entladen
716
                state = State::ExplorationexpeditionUnloading;
3✔
717
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
3✔
718
            } else
719
            {
720
                // Strecke, die wir gefahren sind, draufaddieren
721
                covered_distance += route_.size();
4✔
722
                // Erstmal kurz ausruhen an diesem Punkt und das Rohr ausfahren, um ein bisschen
723
                // auf der Insel zu gucken
724
                state = State::ExplorationexpeditionWaiting;
4✔
725
                current_ev = GetEvMgr().AddEvent(this, EXPLORATION_EXPEDITION_WAITING_TIME, 1);
4✔
726
            }
727
        }
728
        break;
7✔
729
        case Result::NoRouteFound:
1✔
730
        case Result::HarborDoesntExist:
731
            if(homeHarbor != goalHarbor && homeHarbor)
1✔
732
            {
733
                // Try to go back
NEW
734
                goalHarbor = homeHarbor;
×
735
                HandleState_ExplorationExpeditionDriving();
×
736
            } else
737
                FindUnloadGoal(State::ExplorationexpeditionDriving); // Unload anywhere!
1✔
738
            break;
1✔
739
    }
740
}
741

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

770
            for(auto& ware : wares)
4✔
771
            {
772
                ware->NotifyGoalAboutLostWare();
2✔
773
            }
774

775
            FindUnloadGoal(State::TransportDriving);
2✔
776
        }
777
        break;
2✔
778
    }
779
}
780

781
void noShip::HandleState_SeaAttackDriving()
33✔
782
{
783
    Result res = DriveToHarbourPlace();
33✔
784
    switch(res)
33✔
785
    {
786
        case Result::Driving: return; // OK
31✔
787
        case Result::GoalReached:
2✔
788
            // Ziel erreicht, dann stellen wir das Schiff hier hin und die Soldaten laufen nacheinander raus zum Ziel
789
            state = State::SeaattackWaiting;
2✔
790
            current_ev = GetEvMgr().AddEvent(this, 15, 1);
2✔
791
            remaining_sea_attackers = figures.size();
2✔
792
            break;
2✔
793
        case Result::NoRouteFound:
×
794
        case Result::HarborDoesntExist:
NEW
795
            RTTR_Assert(goalHarbor != homeHarbor || !homeHarbor);
×
796
            AbortSeaAttack();
×
797
            break;
×
798
    }
799
}
800

801
void noShip::HandleState_SeaAttackReturn()
16✔
802
{
803
    Result res = DriveToHarbour();
16✔
804
    switch(res)
16✔
805
    {
806
        case Result::Driving: return;
15✔
807
        case Result::GoalReached:
1✔
808
            // Entladen
809
            state = State::SeaattackUnloading;
1✔
810
            this->current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
811
            break;
1✔
812
        case Result::HarborDoesntExist:
×
813
        case Result::NoRouteFound: AbortSeaAttack(); break;
×
814
    }
815
}
816

817
/// Gibt zurück, ob das Schiff jetzt in der Lage wäre, eine Kolonie zu gründen
818
bool noShip::IsAbleToFoundColony() const
×
819
{
820
    // Warten wir gerade?
821
    if(state == State::ExpeditionWaiting)
×
822
    {
823
        // We must always have a goal harbor
NEW
824
        RTTR_Assert(goalHarbor);
×
825
        // Ist der Punkt, an dem wir gerade ankern, noch frei?
NEW
826
        if(world->IsHarborPointFree(goalHarbor, ownerId_))
×
827
            return true;
×
828
    }
829

830
    return false;
×
831
}
832

833
/// Gibt zurück, ob das Schiff einen bestimmten Hafen ansteuert
834
bool noShip::IsGoingToHarbor(const nobHarborBuilding& hb) const
82✔
835
{
836
    if(goalHarbor != hb.GetHarborPosID())
82✔
837
        return false;
71✔
838
    // Explicit switch to check all states
839
    switch(state)
11✔
840
    {
841
        case State::Idle:
1✔
842
        case State::ExpeditionLoading:
843
        case State::ExpeditionUnloading:
844
        case State::ExpeditionWaiting:
845
        case State::ExpeditionDriving:
846
        case State::ExplorationexpeditionLoading:
847
        case State::ExplorationexpeditionUnloading:
848
        case State::ExplorationexpeditionWaiting:
849
        case State::ExplorationexpeditionDriving:
850
        case State::SeaattackLoading:
851
        case State::SeaattackDrivingToDestination:
852
        case State::SeaattackWaiting: return false;
1✔
853
        case State::Gotoharbor:
10✔
854
        case State::TransportDriving:       // Driving to this harbor
855
        case State::TransportLoading:       // Loading at home harbor and going to goal
856
        case State::TransportUnloading:     // Unloading at this harbor
857
        case State::SeaattackUnloading:     // Unloading attackers at this harbor
858
        case State::SeaattackReturnDriving: // Returning attackers to this harbor
859
            return true;
10✔
860
    }
861
    RTTR_Assert(false);
×
862
    return false;
863
}
864

865
/// Belädt das Schiff mit Waren und Figuren, um eine Transportfahrt zu starten
866
void noShip::PrepareTransport(HarborId homeHarborId, MapPoint goal, std::list<std::unique_ptr<noFigure>> figures,
5✔
867
                              std::list<std::unique_ptr<Ware>> wares)
868
{
869
    RTTR_Assert(homeHarborId);
5✔
870
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
5✔
871
    this->homeHarbor = homeHarborId;
5✔
872
    // ID von Zielhafen herausfinden
873
    noBase* nb = world->GetNO(goal);
5✔
874
    RTTR_Assert(nb->GetGOT() == GO_Type::NobHarborbuilding);
5✔
875
    this->goalHarbor = static_cast<nobHarborBuilding*>(nb)->GetHarborPosID();
5✔
876

877
    this->figures = std::move(figures);
5✔
878
    this->wares = std::move(wares);
5✔
879

880
    state = State::TransportLoading;
5✔
881
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
5✔
882
}
5✔
883

884
/// Belädt das Schiff mit Schiffs-Angreifern
885
void noShip::PrepareSeaAttack(HarborId homeHarborId, MapPoint goal, std::vector<std::unique_ptr<nofAttacker>> attackers)
2✔
886
{
887
    // Heimathafen merken
888
    RTTR_Assert(homeHarborId);
2✔
889
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
2✔
890
    homeHarbor = homeHarborId;
2✔
891
    goalHarbor = world->GetHarborPointID(goal);
2✔
892
    RTTR_Assert(goalHarbor);
2✔
893
    figures.clear();
2✔
894
    for(auto& attacker : attackers)
6✔
895
    {
896
        attacker->StartShipJourney();
4✔
897
        attacker->SeaAttackStarted();
4✔
898
        figures.push_back(std::move(attacker));
4✔
899
    }
900
    state = State::SeaattackLoading;
2✔
901
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
2✔
902
}
2✔
903

904
/// Startet Schiffs-Angreiff
905
void noShip::StartSeaAttack()
2✔
906
{
907
    state = State::SeaattackDrivingToDestination;
2✔
908
    StartDrivingToHarborPlace();
2✔
909
    HandleState_SeaAttackDriving();
2✔
910
}
2✔
911

912
void noShip::AbortSeaAttack()
×
913
{
914
    RTTR_Assert(state != State::SeaattackWaiting); // figures are not aboard if this fails!
×
915
    RTTR_Assert(remaining_sea_attackers == 0);     // Some soldiers are still not aboard
×
916

NEW
917
    if((state == State::SeaattackLoading || state == State::SeaattackDrivingToDestination) && goalHarbor != homeHarbor
×
NEW
918
       && homeHarbor)
×
919
    {
920
        // We did not start the attack yet and we can (possibly) go back to our home harbor
921
        // -> tell the soldiers we go back (like after an attack)
NEW
922
        goalHarbor = homeHarbor;
×
923
        for(auto& figure : figures)
×
924
            checkedCast<nofAttacker*>(figure.get())->StartReturnViaShip(*this);
×
925
        if(state == State::SeaattackLoading)
×
926
        {
927
            // We are still loading (loading event must be active)
928
            // -> Use it to unload
929
            RTTR_Assert(current_ev);
×
930
            state = State::SeaattackUnloading;
×
931
        } else
932
        {
933
            // Else start driving back
934
            state = State::SeaattackReturnDriving;
×
935
            HandleState_SeaAttackReturn();
×
936
        }
937
    } else
938
    {
939
        // attack failed and we cannot go back to our home harbor
940
        // -> Tell figures that they won't go to their planned destination
941
        for(auto& figure : figures)
×
942
            checkedCast<nofAttacker*>(figure.get())->CancelSeaAttack();
×
943

944
        if(state == State::SeaattackLoading)
×
945
        {
946
            // Abort loading
947
            RTTR_Assert(current_ev);
×
948
            GetEvMgr().RemoveEvent(current_ev);
×
949
        }
950

951
        // Das Schiff muss einen Notlandeplatz ansteuern
952
        FindUnloadGoal(State::SeaattackReturnDriving);
×
953
    }
954
}
×
955

956
/// Fängt an zu einem Hafen zu fahren (berechnet Route usw.)
957
void noShip::StartDrivingToHarborPlace()
19✔
958
{
959
    if(!goalHarbor)
19✔
960
    {
961
        route_.clear();
1✔
962
        curRouteIdx = 0;
1✔
963
        return;
1✔
964
    }
965

966
    MapPoint coastalPos = world->GetCoastalPoint(goalHarbor, seaId_);
18✔
967
    if(pos == coastalPos)
18✔
968
        route_.clear();
1✔
969
    else
970
    {
971
        bool routeFound;
972
        // Use upper bound to distance by checking the distance between the harbors if we still have and are at the home
973
        // harbor
974
        if(homeHarbor && pos == world->GetCoastalPoint(homeHarbor, seaId_))
17✔
975
        {
976
            // Use the maximum distance between the harbors plus 6 fields
977
            unsigned maxDistance = world->CalcHarborDistance(homeHarbor, goalHarbor) + 6;
8✔
978
            routeFound = world->FindShipPath(pos, coastalPos, maxDistance, &route_, nullptr);
8✔
979
        } else
980
            routeFound = world->FindShipPathToHarbor(pos, goalHarbor, seaId_, &route_, nullptr);
9✔
981
        if(!routeFound)
17✔
982
        {
983
            // todo
984
            RTTR_Assert(false);
×
985
            LOG.write("WARNING: Bug detected (GF: %u). Please report this with the savegame and "
986
                      "replay.\nnoShip::StartDrivingToHarborPlace: Schiff hat keinen Weg gefunden!\nplayer %i state %i "
987
                      "pos %u,%u goal "
988
                      "coastal %u,%u goal-id %i goalpos %u,%u \n")
989
              % GetEvMgr().GetCurrentGF() % unsigned(ownerId_) % unsigned(state) % pos.x % pos.y % coastalPos.x
990
              % coastalPos.y % goalHarbor % world->GetHarborPoint(goalHarbor).x % world->GetHarborPoint(goalHarbor).y;
991
            goalHarbor.reset();
992
            return;
993
        }
994
    }
995
    curRouteIdx = 0;
18✔
996
}
997

998
/// Startet die eigentliche Transportaktion, nachdem das Schiff beladen wurde
999
void noShip::StartTransport()
4✔
1000
{
1001
    state = State::TransportDriving;
4✔
1002

1003
    StartDrivingToHarborPlace();
4✔
1004
    // Einfach weiterfahren
1005
    HandleState_TransportDriving();
4✔
1006
}
4✔
1007

1008
void noShip::FindUnloadGoal(State newState)
5✔
1009
{
1010
    state = newState;
5✔
1011
    // Das Schiff muss einen Notlandeplatz ansteuern
1012
    // Neuen Hafen suchen
1013
    if(world->GetPlayer(ownerId_).FindHarborForUnloading(this, pos, &goalHarbor, &route_, nullptr))
5✔
1014
    {
1015
        curRouteIdx = 0;
3✔
1016
        homeHarbor = goalHarbor; // To allow unloading here
3✔
1017
        if(state == State::ExpeditionDriving)
3✔
1018
            HandleState_ExpeditionDriving();
×
1019
        else if(state == State::ExplorationexpeditionDriving)
3✔
1020
            HandleState_ExplorationExpeditionDriving();
×
1021
        else if(state == State::TransportDriving)
3✔
1022
            HandleState_TransportDriving();
3✔
1023
        else if(state == State::SeaattackReturnDriving)
×
1024
            HandleState_SeaAttackReturn();
×
1025
        else
1026
        {
1027
            RTTR_Assert(false);
×
1028
            LOG.write("Bug detected: Invalid state for FindUnloadGoal");
1029
            FindUnloadGoal(State::TransportDriving);
1030
        }
1031
    } else
1032
    {
1033
        // Ansonsten als verloren markieren, damit uns später Bescheid gesagt wird
1034
        // wenn es einen neuen Hafen gibt
1035
        homeHarbor.reset();
2✔
1036
        goalHarbor.reset();
2✔
1037
        lost = true;
2✔
1038
    }
1039
}
5✔
1040

1041
/// Sagt dem Schiff, das ein bestimmter Hafen zerstört wurde
1042
void noShip::HarborDestroyed(nobHarborBuilding* hb)
12✔
1043
{
1044
    const HarborId destroyedHarborId = hb->GetHarborPosID();
12✔
1045
    // Almost every case of a destroyed harbor is handled when the ships event fires (the handler detects the destroyed
1046
    // harbor) So mostly we just reset the corresponding id
1047

1048
    if(destroyedHarborId == homeHarbor)
12✔
1049
        homeHarbor.reset();
4✔
1050

1051
    // Ist unser Ziel betroffen?
1052
    if(destroyedHarborId != goalHarbor)
12✔
1053
        return;
9✔
1054

1055
    State oldState = state;
7✔
1056

1057
    switch(state)
7✔
1058
    {
1059
        default:
4✔
1060
            // Just reset goal, but not for expeditions
1061
            if(!IsOnExpedition() && !IsOnExplorationExpedition())
4✔
1062
                goalHarbor.reset();
3✔
1063
            return; // Skip the rest
4✔
1064
        case State::TransportLoading:
3✔
1065
        case State::TransportUnloading:
1066
            // Tell wares and figures that they won't reach their goal
1067
            for(auto& figure : figures)
3✔
1068
            {
1069
                figure->Abrogate();
×
1070
                figure->SetGoalTonullptr();
×
1071
            }
1072
            for(auto& ware : wares)
6✔
1073
            {
1074
                // Notify goal only, if it is not the destroyed harbor. It already knows about that ;)
1075
                if(ware->GetGoal() != hb)
3✔
1076
                    ware->NotifyGoalAboutLostWare();
×
1077
                else
1078
                    ware->SetGoal(nullptr);
3✔
1079
            }
1080
            break;
3✔
1081
        case State::SeaattackLoading:
×
1082
            // We could also just set the goal harbor id to 0 but this can reuse the event
1083
            AbortSeaAttack();
×
1084
            break;
×
1085
        case State::SeaattackUnloading: break;
×
1086
    }
1087

1088
    // Are we currently getting the wares?
1089
    if(oldState == State::TransportLoading)
3✔
1090
    {
1091
        RTTR_Assert(current_ev);
1✔
1092
        if(homeHarbor)
1✔
1093
        {
1094
            // Then save us some time and unload immediately
1095
            // goal is now the start harbor (if it still exists)
1096
            goalHarbor = homeHarbor;
1✔
1097
            state = State::TransportUnloading;
1✔
1098
        } else
1099
        {
1100
            GetEvMgr().RemoveEvent(current_ev);
×
1101
            FindUnloadGoal(State::TransportDriving);
×
1102
        }
1103
    } else if(oldState == State::TransportUnloading || oldState == State::SeaattackUnloading)
2✔
1104
    {
1105
        // Remove current unload event
1106
        GetEvMgr().RemoveEvent(current_ev);
2✔
1107

1108
        if(oldState == State::SeaattackUnloading)
2✔
1109
            AbortSeaAttack();
×
1110
        else
1111
            FindUnloadGoal(State::TransportDriving);
2✔
1112
    }
1113
}
1114

1115
/// Fängt an mit idlen und setzt nötigen Sachen auf nullptr
1116
void noShip::StartIdling()
19✔
1117
{
1118
    // If those are not empty, then we are lost, not idling!
1119
    RTTR_Assert(figures.empty());
19✔
1120
    RTTR_Assert(wares.empty());
19✔
1121
    RTTR_Assert(remaining_sea_attackers == 0);
19✔
1122
    // Implicit contained wares/figures on expeditions
1123
    RTTR_Assert(!IsOnExplorationExpedition() || state == State::ExplorationexpeditionUnloading);
19✔
1124
    RTTR_Assert(!IsOnExpedition() || state == State::ExpeditionUnloading);
19✔
1125

1126
    homeHarbor.reset();
19✔
1127
    goalHarbor.reset();
19✔
1128
    state = State::Idle;
19✔
1129
}
19✔
1130

1131
/// Sagt Bescheid, dass ein Schiffsangreifer nicht mehr mit nach Hause fahren will
1132
void noShip::SeaAttackerWishesNoReturn()
4✔
1133
{
1134
    RTTR_Assert(remaining_sea_attackers);
4✔
1135
    RTTR_Assert(state == State::SeaattackWaiting);
4✔
1136

1137
    --remaining_sea_attackers;
4✔
1138
    // Alle Soldaten an Bord
1139
    if(remaining_sea_attackers == 0)
4✔
1140
    {
1141
        // Andere Events ggf. erstmal abmelden
1142
        GetEvMgr().RemoveEvent(current_ev);
2✔
1143
        if(!figures.empty())
2✔
1144
        {
1145
            // Go back home. Note: home_harbor can be 0 if it was destroyed, allow this and let the state handlers
1146
            // handle that case later
1147
            goalHarbor = homeHarbor;
2✔
1148
            state = State::SeaattackReturnDriving;
2✔
1149
            StartDrivingToHarborPlace();
2✔
1150
            HandleState_SeaAttackReturn();
2✔
1151
        } else
1152
        {
1153
            // Wenn keine Soldaten mehr da sind können wir auch erstmal idlen
1154
            StartIdling();
×
1155
            world->GetPlayer(ownerId_).GetJobForShip(*this);
×
1156
        }
1157
    }
1158
}
4✔
1159

1160
/// Schiffs-Angreifer sind nach dem Angriff wieder zurückgekehrt
1161
void noShip::AddReturnedAttacker(std::unique_ptr<nofAttacker> attacker)
4✔
1162
{
1163
    RTTR_Assert(!helpers::containsPtr(figures, attacker.get()));
4✔
1164

1165
    figures.push_back(std::move(attacker));
4✔
1166
    // Nun brauchen wir quasi einen Angreifer weniger
1167
    SeaAttackerWishesNoReturn();
4✔
1168
}
4✔
1169

1170
/// Weist das Schiff an, seine Erkundungs-Expedition fortzusetzen
1171
void noShip::ContinueExplorationExpedition()
8✔
1172
{
1173
    // Sind wir schon über unserem Limit, also zu weit gefahren
1174
    if(covered_distance >= MAX_EXPLORATION_EXPEDITION_DISTANCE)
8✔
1175
    {
1176
        // Dann steuern wir unseren Heimathafen an!
NEW
1177
        goalHarbor = homeHarbor;
×
1178
    } else
1179
    {
1180
        // Find the next harbor spot to explore
1181
        std::vector<HarborId> hps;
16✔
1182
        if(goalHarbor)
8✔
1183
            hps = world->GetUnexploredHarborPoints(goalHarbor, seaId_, GetPlayerId());
8✔
1184

1185
        // No possible spots? -> Go home
1186
        if(hps.empty())
8✔
1187
            goalHarbor = homeHarbor;
4✔
1188
        else
1189
        {
1190
            // Choose one randomly
1191
            goalHarbor = RANDOM_ELEMENT(hps);
4✔
1192
        }
1193
    }
1194

1195
    StartDrivingToHarborPlace();
8✔
1196
    state = State::ExplorationexpeditionDriving;
8✔
1197
    HandleState_ExplorationExpeditionDriving();
8✔
1198
}
8✔
1199

1200
/// Sagt dem Schiff, dass ein neuer Hafen erbaut wurde
1201
void noShip::NewHarborBuilt(nobHarborBuilding* hb)
11✔
1202
{
1203
    if(!lost)
11✔
1204
        return;
9✔
1205
    // Liegt der Hafen auch am Meer von diesem Schiff?
1206
    if(!world->IsHarborAtSea(hb->GetHarborPosID(), seaId_))
2✔
1207
        return;
×
1208

1209
    // LOG.write(("lost ship has new goal harbor player %i state %i pos %u,%u \n",player,state,x,y);
1210
    homeHarbor = goalHarbor = hb->GetHarborPosID();
2✔
1211
    lost = false;
2✔
1212

1213
    StartDrivingToHarborPlace();
2✔
1214

1215
    switch(state)
2✔
1216
    {
1217
        case State::ExplorationexpeditionDriving:
2✔
1218
        case State::ExpeditionDriving:
1219
        case State::TransportDriving:
1220
        case State::SeaattackReturnDriving: Driven(); break;
2✔
1221
        default:
×
1222
            RTTR_Assert(false); // Das darf eigentlich nicht passieren
×
1223
            LOG.write("Bug detected: Invalid state in NewHarborBuilt");
1224
            break;
1225
    }
1226
}
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