1
0
Fork 0

Compare commits

...

8 Commits

Author SHA1 Message Date
SamuXarick 47e17f90b3
Merge f0382c37ee into 9ce2aca949 2025-07-14 18:19:39 +00:00
Peter Nelson 9ce2aca949 Codechange: Get/pass ScriptStorage by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson 55098a2f2e Codechange: Get/pass engine by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson 7ff0c67f77 Codechange: Get/pass script controller by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson b2de1ff66f
Fix #14433: Broken road stop drawing due to incorrect modes conversion. (#14434)
The mask was treated as a single RoadStopDrawMode instead of a RoadStopDrawModes bitset.
2025-07-14 17:25:53 +01:00
Loïc Guilloux fc924161ab
Fix 0455627d: Don't draw timetable panel if no orders (#14441) 2025-07-14 14:18:54 +00:00
Peter Nelson 61a299bc99
Codechange: Use SpriteID as GlyphID for SpriteFontCache. (#14439)
This reduces the amount of lookups in the character map as rendering a cached layout no longer needs to do so.
2025-07-14 13:28:10 +01:00
SamuXarick f0382c37ee Fix #12193: [YAPF] Don't use the entire docking area when computing closest station tile
Don't use CalcClosestStationTile for ships. Instead, use a specialized GetShipDestinationTiles which creates a list of possible destination tiles. For docks, it only takes into consideration the tiles that pass both IsDockingTile and IsShipDestinationTile tests. For the other cases it just takes the ship's current dest_tile.

Modified CYapfDestinationTileWaterT class to accept multiple destinations. In this manner, the estimate cost is calculated for each of the destination tiles and the shortest estimate is returned. Some adaptation was necessary to make this possible to work for both the high- and low-level pathfinders and the existing functions. ChooseShipTrack and its FindWaterRegionPath brother both will take the same destination tiles which are calculated at either YapfShipChooseTrack or YapfShipCheckReverse.
2025-02-16 20:54:32 +00:00
16 changed files with 169 additions and 127 deletions

View File

@ -103,14 +103,14 @@ void SpriteFontCache::ClearFontCache()
const Sprite *SpriteFontCache::GetGlyph(GlyphID key) const Sprite *SpriteFontCache::GetGlyph(GlyphID key)
{ {
SpriteID sprite = this->GetUnicodeGlyph(static_cast<char32_t>(key & ~SPRITE_GLYPH)); SpriteID sprite = static_cast<SpriteID>(key & ~SPRITE_GLYPH);
if (sprite == 0) sprite = this->GetUnicodeGlyph('?'); if (sprite == 0) sprite = this->GetUnicodeGlyph('?');
return GetSprite(sprite, SpriteType::Font); return GetSprite(sprite, SpriteType::Font);
} }
uint SpriteFontCache::GetGlyphWidth(GlyphID key) uint SpriteFontCache::GetGlyphWidth(GlyphID key)
{ {
SpriteID sprite = this->GetUnicodeGlyph(static_cast<char32_t>(key & ~SPRITE_GLYPH)); SpriteID sprite = static_cast<SpriteID>(key & ~SPRITE_GLYPH);
if (sprite == 0) sprite = this->GetUnicodeGlyph('?'); if (sprite == 0) sprite = this->GetUnicodeGlyph('?');
return SpriteExists(sprite) ? GetSprite(sprite, SpriteType::Font)->width + ScaleFontTrad(this->fs != FS_NORMAL ? 1 : 0) : 0; return SpriteExists(sprite) ? GetSprite(sprite, SpriteType::Font)->width + ScaleFontTrad(this->fs != FS_NORMAL ? 1 : 0) : 0;
} }
@ -120,7 +120,7 @@ GlyphID SpriteFontCache::MapCharToGlyph(char32_t key, [[maybe_unused]] bool allo
assert(IsPrintable(key)); assert(IsPrintable(key));
SpriteID sprite = this->GetUnicodeGlyph(key); SpriteID sprite = this->GetUnicodeGlyph(key);
if (sprite == 0) return 0; if (sprite == 0) return 0;
return SPRITE_GLYPH | key; return SPRITE_GLYPH | sprite;
} }
bool SpriteFontCache::GetDrawGlyphShadow() bool SpriteFontCache::GetDrawGlyphShadow()

View File

@ -105,8 +105,8 @@ static ChangeInfoResult RoadStopChangeInfo(uint first, uint last, int prop, Byte
AddStringForMapping(GRFStringID{buf.ReadWord()}, [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; }); AddStringForMapping(GRFStringID{buf.ReadWord()}, [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; });
break; break;
case 0x0C: // The draw mode case 0x0C: // The draw modes
rs->draw_mode = static_cast<RoadStopDrawMode>(buf.ReadByte()); rs->draw_mode = static_cast<RoadStopDrawModes>(buf.ReadByte());
break; break;
case 0x0D: // Cargo types for random triggers case 0x0D: // Cargo types for random triggers

View File

@ -298,7 +298,7 @@ void DrawRoadStopTile(int x, int y, RoadType roadtype, const RoadStopSpec *spec,
RoadStopDrawModes draw_mode; RoadStopDrawModes draw_mode;
if (spec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) { if (spec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
draw_mode = static_cast<RoadStopDrawMode>(object.GetRegister(0x100)); draw_mode = static_cast<RoadStopDrawModes>(object.GetRegister(0x100));
} else { } else {
draw_mode = spec->draw_mode; draw_mode = spec->draw_mode;
} }

View File

@ -12,6 +12,40 @@
#include "../tile_cmd.h" #include "../tile_cmd.h"
#include "../waypoint_base.h" #include "../waypoint_base.h"
#include "../ship.h"
/**
* Creates a list containing possible destination tiles for a ship.
* @param v The ship
* return Vector of tiles filled with all possible destinations.
*/
inline std::vector<TileIndex> GetShipDestinationTiles(const Ship *v)
{
std::vector<TileIndex> dest_tiles;
if (v->current_order.IsType(OT_GOTO_STATION)) {
const StationID station = v->current_order.GetDestination().ToStationID();
const BaseStation *st = BaseStation::Get(station);
TileArea ta;
st->GetTileArea(&ta, StationType::Dock);
/* If the dock station is (temporarily) not present, use the station sign to drive near the station. */
if (ta.tile == INVALID_TILE) {
dest_tiles.push_back(st->xy);
} else {
for (const TileIndex &docking_tile : ta) {
if (!IsDockingTile(docking_tile) || !IsShipDestinationTile(docking_tile, station)) continue;
dest_tiles.push_back(docking_tile);
}
}
} else {
dest_tiles.push_back(v->dest_tile);
}
assert(!dest_tiles.empty());
return dest_tiles;
}
/** /**
* Calculates the tile of given station that is closest to a given tile * Calculates the tile of given station that is closest to a given tile

View File

@ -33,8 +33,7 @@ public:
typedef typename Node::Key Key; ///< key to hash tables. typedef typename Node::Key Key; ///< key to hash tables.
protected: protected:
TileIndex dest_tile; std::span<TileIndex> dest_tiles;
TrackdirBits dest_trackdirs;
StationID dest_station; StationID dest_station;
bool has_intermediate_dest = false; bool has_intermediate_dest = false;
@ -42,16 +41,13 @@ protected:
WaterRegionPatchDesc intermediate_dest_region_patch; WaterRegionPatchDesc intermediate_dest_region_patch;
public: public:
void SetDestination(const Ship *v) void SetDestination(const Ship *v, const std::span<TileIndex> destination_tiles)
{ {
this->dest_tiles = destination_tiles;
if (v->current_order.IsType(OT_GOTO_STATION)) { if (v->current_order.IsType(OT_GOTO_STATION)) {
this->dest_station = v->current_order.GetDestination().ToStationID(); this->dest_station = v->current_order.GetDestination().ToStationID();
this->dest_tile = CalcClosestStationTile(this->dest_station, v->tile, StationType::Dock);
this->dest_trackdirs = INVALID_TRACKDIR_BIT;
} else { } else {
this->dest_station = StationID::Invalid(); this->dest_station = StationID::Invalid();
this->dest_tile = v->dest_tile;
this->dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(v->dest_tile, TRANSPORT_WATER, 0));
} }
} }
@ -73,11 +69,8 @@ public:
/** Called by YAPF to detect if node ends in the desired destination. */ /** Called by YAPF to detect if node ends in the desired destination. */
inline bool PfDetectDestination(Node &n) inline bool PfDetectDestination(Node &n)
{ {
return this->PfDetectDestinationTile(n.segment_last_tile, n.segment_last_td); const TileIndex tile = n.segment_last_tile;
}
inline bool PfDetectDestinationTile(TileIndex tile, Trackdir trackdir)
{
if (this->has_intermediate_dest) { if (this->has_intermediate_dest) {
/* GetWaterRegionInfo is much faster than GetWaterRegionPatchInfo so we try that first. */ /* GetWaterRegionInfo is much faster than GetWaterRegionPatchInfo so we try that first. */
if (GetWaterRegionInfo(tile) != this->intermediate_dest_region_patch) return false; if (GetWaterRegionInfo(tile) != this->intermediate_dest_region_patch) return false;
@ -86,23 +79,14 @@ public:
if (this->dest_station != StationID::Invalid()) return IsDockingTile(tile) && IsShipDestinationTile(tile, this->dest_station); if (this->dest_station != StationID::Invalid()) return IsDockingTile(tile) && IsShipDestinationTile(tile, this->dest_station);
return tile == this->dest_tile && ((this->dest_trackdirs & TrackdirToTrackdirBits(trackdir)) != TRACKDIR_BIT_NONE); assert(this->dest_tiles.size() == 1);
return tile == this->dest_tiles.front();
} }
/** static inline int CalcEstimate(Node &n, TileIndex destination_tile)
* Called by YAPF to calculate cost estimate. Calculates distance to the destination
* adds it to the actual cost from origin and stores the sum to the Node::estimate.
*/
inline bool PfCalcEstimate(Node &n)
{ {
const TileIndex destination_tile = this->has_intermediate_dest ? this->intermediate_dest_tile : this->dest_tile;
static const int dg_dir_to_x_offs[] = { -1, 0, 1, 0 }; static const int dg_dir_to_x_offs[] = { -1, 0, 1, 0 };
static const int dg_dir_to_y_offs[] = { 0, 1, 0, -1 }; static const int dg_dir_to_y_offs[] = { 0, 1, 0, -1 };
if (this->PfDetectDestination(n)) {
n.estimate = n.cost;
return true;
}
TileIndex tile = n.segment_last_tile; TileIndex tile = n.segment_last_tile;
DiagDirection exitdir = TrackdirToExitdir(n.segment_last_td); DiagDirection exitdir = TrackdirToExitdir(n.segment_last_td);
@ -115,8 +99,33 @@ public:
int dmin = std::min(dx, dy); int dmin = std::min(dx, dy);
int dxy = abs(dx - dy); int dxy = abs(dx - dy);
int d = dmin * YAPF_TILE_CORNER_LENGTH + (dxy - 1) * (YAPF_TILE_LENGTH / 2); int d = dmin * YAPF_TILE_CORNER_LENGTH + (dxy - 1) * (YAPF_TILE_LENGTH / 2);
n.estimate = n.cost + d; int estimate = n.cost + d;
assert(n.estimate >= n.parent->estimate); assert(estimate >= n.parent->estimate);
return estimate;
}
/**
* Called by YAPF to calculate cost estimate. Calculates distance to the destination
* adds it to the actual cost from origin and stores the sum to the Node::estimate.
*/
inline bool PfCalcEstimate(Node &n)
{
if (this->PfDetectDestination(n)) {
n.estimate = n.cost;
return true;
}
int shortest_estimate = std::numeric_limits<int>::max();
if (this->has_intermediate_dest) {
shortest_estimate = this->CalcEstimate(n, this->intermediate_dest_tile);
} else {
for (const TileIndex &destination_tile : this->dest_tiles) {
int estimate = this->CalcEstimate(n, destination_tile);
if (estimate < shortest_estimate) shortest_estimate = estimate;
}
}
n.estimate = shortest_estimate;
return true; return true;
} }
}; };
@ -211,10 +220,10 @@ public:
return result; return result;
} }
static Trackdir ChooseShipTrack(const Ship *v, TileIndex tile, TrackdirBits forward_dirs, TrackdirBits reverse_dirs, static Trackdir ChooseShipTrack(const Ship *v, TileIndex tile, TrackdirBits forward_dirs, TrackdirBits reverse_dirs, const std::span<TileIndex> dest_tiles,
bool &path_found, ShipPathCache &path_cache, Trackdir &best_origin_dir) bool &path_found, ShipPathCache &path_cache, Trackdir &best_origin_dir)
{ {
const std::vector<WaterRegionPatchDesc> high_level_path = YapfShipFindWaterRegionPath(v, tile, NUMBER_OR_WATER_REGIONS_LOOKAHEAD + 1); const std::vector<WaterRegionPatchDesc> high_level_path = YapfShipFindWaterRegionPath(v, tile, NUMBER_OR_WATER_REGIONS_LOOKAHEAD + 1, dest_tiles);
if (high_level_path.empty()) { if (high_level_path.empty()) {
path_found = false; path_found = false;
/* Make the ship move around aimlessly. This prevents repeated pathfinder calls and clearly indicates that the ship is lost. */ /* Make the ship move around aimlessly. This prevents repeated pathfinder calls and clearly indicates that the ship is lost. */
@ -229,7 +238,7 @@ public:
/* Set origin and destination nodes */ /* Set origin and destination nodes */
pf.SetOrigin(v->tile, forward_dirs | reverse_dirs); pf.SetOrigin(v->tile, forward_dirs | reverse_dirs);
pf.SetDestination(v); pf.SetDestination(v, dest_tiles);
const bool is_intermediate_destination = static_cast<int>(high_level_path.size()) >= NUMBER_OR_WATER_REGIONS_LOOKAHEAD + 1; const bool is_intermediate_destination = static_cast<int>(high_level_path.size()) >= NUMBER_OR_WATER_REGIONS_LOOKAHEAD + 1;
if (is_intermediate_destination) pf.SetIntermediateDestination(high_level_path.back()); if (is_intermediate_destination) pf.SetIntermediateDestination(high_level_path.back());
@ -297,9 +306,10 @@ public:
* Called when leaving depot. * Called when leaving depot.
* @param v Ship. * @param v Ship.
* @param trackdir [out] the best of all possible reversed trackdirs. * @param trackdir [out] the best of all possible reversed trackdirs.
* @param dest_tiles list of destination tiles.
* @return true if the reverse direction is better. * @return true if the reverse direction is better.
*/ */
static bool CheckShipReverse(const Ship *v, Trackdir *trackdir) static bool CheckShipReverse(const Ship *v, Trackdir *trackdir, const std::span<TileIndex> dest_tiles)
{ {
bool path_found = false; bool path_found = false;
ShipPathCache dummy_cache; ShipPathCache dummy_cache;
@ -310,13 +320,13 @@ public:
const Trackdir reverse_dir = ReverseTrackdir(v->GetVehicleTrackdir()); const Trackdir reverse_dir = ReverseTrackdir(v->GetVehicleTrackdir());
const TrackdirBits forward_dirs = TrackdirToTrackdirBits(v->GetVehicleTrackdir()); const TrackdirBits forward_dirs = TrackdirToTrackdirBits(v->GetVehicleTrackdir());
const TrackdirBits reverse_dirs = TrackdirToTrackdirBits(reverse_dir); const TrackdirBits reverse_dirs = TrackdirToTrackdirBits(reverse_dir);
(void)ChooseShipTrack(v, v->tile, forward_dirs, reverse_dirs, path_found, dummy_cache, best_origin_dir); (void)ChooseShipTrack(v, v->tile, forward_dirs, reverse_dirs, dest_tiles, path_found, dummy_cache, best_origin_dir);
return path_found && best_origin_dir == reverse_dir; return path_found && best_origin_dir == reverse_dir;
} else { } else {
/* This gets called when a ship suddenly can't move forward, e.g. due to terraforming. */ /* This gets called when a ship suddenly can't move forward, e.g. due to terraforming. */
const DiagDirection entry = ReverseDiagDir(VehicleExitDir(v->direction, v->state)); const DiagDirection entry = ReverseDiagDir(VehicleExitDir(v->direction, v->state));
const TrackdirBits reverse_dirs = DiagdirReachesTrackdirs(entry) & TrackStatusToTrackdirBits(GetTileTrackStatus(v->tile, TRANSPORT_WATER, 0, entry)); const TrackdirBits reverse_dirs = DiagdirReachesTrackdirs(entry) & TrackStatusToTrackdirBits(GetTileTrackStatus(v->tile, TRANSPORT_WATER, 0, entry));
(void)ChooseShipTrack(v, v->tile, TRACKDIR_BIT_NONE, reverse_dirs, path_found, dummy_cache, best_origin_dir); (void)ChooseShipTrack(v, v->tile, TRACKDIR_BIT_NONE, reverse_dirs, dest_tiles, path_found, dummy_cache, best_origin_dir);
*trackdir = path_found && best_origin_dir != INVALID_TRACKDIR ? best_origin_dir : GetRandomTrackdir(reverse_dirs); *trackdir = path_found && best_origin_dir != INVALID_TRACKDIR ? best_origin_dir : GetRandomTrackdir(reverse_dirs);
return true; return true;
} }
@ -420,13 +430,15 @@ struct CYapfShip : CYapfT<CYapfShip_TypesT<CYapfShip, CFollowTrackWater, CShipNo
/** Ship controller helper - path finder invoker. */ /** Ship controller helper - path finder invoker. */
Track YapfShipChooseTrack(const Ship *v, TileIndex tile, bool &path_found, ShipPathCache &path_cache) Track YapfShipChooseTrack(const Ship *v, TileIndex tile, bool &path_found, ShipPathCache &path_cache)
{ {
std::vector<TileIndex> dest_tiles = GetShipDestinationTiles(v);
Trackdir best_origin_dir = INVALID_TRACKDIR; Trackdir best_origin_dir = INVALID_TRACKDIR;
const TrackdirBits origin_dirs = TrackdirToTrackdirBits(v->GetVehicleTrackdir()); const TrackdirBits origin_dirs = TrackdirToTrackdirBits(v->GetVehicleTrackdir());
const Trackdir td_ret = CYapfShip::ChooseShipTrack(v, tile, origin_dirs, TRACKDIR_BIT_NONE, path_found, path_cache, best_origin_dir); const Trackdir td_ret = CYapfShip::ChooseShipTrack(v, tile, origin_dirs, TRACKDIR_BIT_NONE, dest_tiles, path_found, path_cache, best_origin_dir);
return (td_ret != INVALID_TRACKDIR) ? TrackdirToTrack(td_ret) : INVALID_TRACK; return (td_ret != INVALID_TRACKDIR) ? TrackdirToTrack(td_ret) : INVALID_TRACK;
} }
bool YapfShipCheckReverse(const Ship *v, Trackdir *trackdir) bool YapfShipCheckReverse(const Ship *v, Trackdir *trackdir)
{ {
return CYapfShip::CheckShipReverse(v, trackdir); std::vector<TileIndex> dest_tiles = GetShipDestinationTiles(v);
return CYapfShip::CheckShipReverse(v, trackdir, dest_tiles);
} }

View File

@ -175,7 +175,7 @@ public:
inline char TransportTypeChar() const { return '^'; } inline char TransportTypeChar() const { return '^'; }
static std::vector<WaterRegionPatchDesc> FindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length) static std::vector<WaterRegionPatchDesc> FindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length, const std::span<TileIndex> dest_tiles)
{ {
const WaterRegionPatchDesc start_water_region_patch = GetWaterRegionPatchInfo(start_tile); const WaterRegionPatchDesc start_water_region_patch = GetWaterRegionPatchInfo(start_tile);
@ -184,18 +184,7 @@ public:
Tpf pf(std::min(static_cast<int>(Map::Size() * NODES_PER_REGION) / WATER_REGION_NUMBER_OF_TILES, MAX_NUMBER_OF_NODES)); Tpf pf(std::min(static_cast<int>(Map::Size() * NODES_PER_REGION) / WATER_REGION_NUMBER_OF_TILES, MAX_NUMBER_OF_NODES));
pf.SetDestination(start_water_region_patch); pf.SetDestination(start_water_region_patch);
if (v->current_order.IsType(OT_GOTO_STATION)) { for (const TileIndex &tile : dest_tiles) {
StationID station_id = v->current_order.GetDestination().ToStationID();
const BaseStation *station = BaseStation::Get(station_id);
TileArea tile_area;
station->GetTileArea(&tile_area, StationType::Dock);
for (const auto &tile : tile_area) {
if (IsDockingTile(tile) && IsShipDestinationTile(tile, station_id)) {
pf.AddOrigin(GetWaterRegionPatchInfo(tile));
}
}
} else {
TileIndex tile = v->dest_tile;
pf.AddOrigin(GetWaterRegionPatchInfo(tile)); pf.AddOrigin(GetWaterRegionPatchInfo(tile));
} }
@ -292,9 +281,10 @@ struct CYapfRegionWater : CYapfT<CYapfRegion_TypesT<CYapfRegionWater, CRegionNod
* @param v The ship to find a path for. * @param v The ship to find a path for.
* @param start_tile The tile to start searching from. * @param start_tile The tile to start searching from.
* @param max_returned_path_length The maximum length of the path that will be returned. * @param max_returned_path_length The maximum length of the path that will be returned.
* @param dest_tiles List of destination tiles.
* @returns A path of water region patches, or an empty vector if no path was found. * @returns A path of water region patches, or an empty vector if no path was found.
*/ */
std::vector<WaterRegionPatchDesc> YapfShipFindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length) std::vector<WaterRegionPatchDesc> YapfShipFindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length, const std::span<TileIndex> dest_tiles)
{ {
return CYapfRegionWater::FindWaterRegionPath(v, start_tile, max_returned_path_length); return CYapfRegionWater::FindWaterRegionPath(v, start_tile, max_returned_path_length, dest_tiles);
} }

View File

@ -15,6 +15,6 @@
struct Ship; struct Ship;
std::vector<WaterRegionPatchDesc> YapfShipFindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length); std::vector<WaterRegionPatchDesc> YapfShipFindWaterRegionPath(const Ship *v, TileIndex start_tile, int max_returned_path_length, const std::span<TileIndex> dest_tiles);
#endif /* YAPF_SHIP_REGIONS_H */ #endif /* YAPF_SHIP_REGIONS_H */

View File

@ -76,7 +76,7 @@ ScriptController::ScriptController(::CompanyID company) :
/* static */ uint ScriptController::GetTick() /* static */ uint ScriptController::GetTick()
{ {
return ScriptObject::GetActiveInstance().GetController()->ticks; return ScriptObject::GetActiveInstance().GetController().ticks;
} }
/* static */ int ScriptController::GetOpsTillSuspend() /* static */ int ScriptController::GetOpsTillSuspend()
@ -96,9 +96,9 @@ ScriptController::ScriptController(::CompanyID company) :
/* static */ HSQOBJECT ScriptController::Import(const std::string &library, const std::string &class_name, int version) /* static */ HSQOBJECT ScriptController::Import(const std::string &library, const std::string &class_name, int version)
{ {
ScriptController *controller = ScriptObject::GetActiveInstance().GetController(); ScriptController &controller = ScriptObject::GetActiveInstance().GetController();
Squirrel *engine = ScriptObject::GetActiveInstance().engine; Squirrel &engine = *ScriptObject::GetActiveInstance().engine;
HSQUIRRELVM vm = engine->GetVM(); HSQUIRRELVM vm = engine.GetVM();
ScriptInfo *lib = ScriptObject::GetActiveInstance().FindLibrary(library, version); ScriptInfo *lib = ScriptObject::GetActiveInstance().FindLibrary(library, version);
if (lib == nullptr) { if (lib == nullptr) {
@ -114,11 +114,11 @@ ScriptController::ScriptController(::CompanyID company) :
std::string fake_class; std::string fake_class;
LoadedLibraryList::iterator it = controller->loaded_library.find(library_name); LoadedLibraryList::iterator it = controller.loaded_library.find(library_name);
if (it != controller->loaded_library.end()) { if (it != controller.loaded_library.end()) {
fake_class = (*it).second; fake_class = (*it).second;
} else { } else {
int next_number = ++controller->loaded_library_count; int next_number = ++controller.loaded_library_count;
/* Create a new fake internal name */ /* Create a new fake internal name */
fake_class = fmt::format("_internalNA{}", next_number); fake_class = fmt::format("_internalNA{}", next_number);
@ -128,14 +128,14 @@ ScriptController::ScriptController(::CompanyID company) :
sq_pushstring(vm, fake_class); sq_pushstring(vm, fake_class);
sq_newclass(vm, SQFalse); sq_newclass(vm, SQFalse);
/* Load the library */ /* Load the library */
if (!engine->LoadScript(vm, lib->GetMainScript(), false)) { if (!engine.LoadScript(vm, lib->GetMainScript(), false)) {
throw sq_throwerror(vm, fmt::format("there was a compile error when importing '{}' version {}", library, version)); throw sq_throwerror(vm, fmt::format("there was a compile error when importing '{}' version {}", library, version));
} }
/* Create the fake class */ /* Create the fake class */
sq_newslot(vm, -3, SQFalse); sq_newslot(vm, -3, SQFalse);
sq_pop(vm, 1); sq_pop(vm, 1);
controller->loaded_library[library_name] = fake_class; controller.loaded_library[library_name] = fake_class;
} }
/* Find the real class inside the fake class (like 'sets.Vector') */ /* Find the real class inside the fake class (like 'sets.Vector') */

View File

@ -45,7 +45,7 @@ void SimpleCountedObject::Release()
* Get the storage associated with the current ScriptInstance. * Get the storage associated with the current ScriptInstance.
* @return The storage. * @return The storage.
*/ */
static ScriptStorage *GetStorage() static ScriptStorage &GetStorage()
{ {
return ScriptObject::GetActiveInstance().GetStorage(); return ScriptObject::GetActiveInstance().GetStorage();
} }
@ -65,7 +65,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
} }
ScriptObject::DisableDoCommandScope::DisableDoCommandScope() ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
: AutoRestoreBackup(GetStorage()->allow_do_command, false) : AutoRestoreBackup(GetStorage().allow_do_command, false)
{} {}
/* static */ ScriptInstance &ScriptObject::GetActiveInstance() /* static */ ScriptInstance &ScriptObject::GetActiveInstance()
@ -78,181 +78,181 @@ ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
/* static */ void ScriptObject::SetDoCommandDelay(uint ticks) /* static */ void ScriptObject::SetDoCommandDelay(uint ticks)
{ {
assert(ticks > 0); assert(ticks > 0);
GetStorage()->delay = ticks; GetStorage().delay = ticks;
} }
/* static */ uint ScriptObject::GetDoCommandDelay() /* static */ uint ScriptObject::GetDoCommandDelay()
{ {
return GetStorage()->delay; return GetStorage().delay;
} }
/* static */ void ScriptObject::SetDoCommandMode(ScriptModeProc *proc, ScriptObject *instance) /* static */ void ScriptObject::SetDoCommandMode(ScriptModeProc *proc, ScriptObject *instance)
{ {
GetStorage()->mode = proc; GetStorage().mode = proc;
GetStorage()->mode_instance = instance; GetStorage().mode_instance = instance;
} }
/* static */ ScriptModeProc *ScriptObject::GetDoCommandMode() /* static */ ScriptModeProc *ScriptObject::GetDoCommandMode()
{ {
return GetStorage()->mode; return GetStorage().mode;
} }
/* static */ ScriptObject *ScriptObject::GetDoCommandModeInstance() /* static */ ScriptObject *ScriptObject::GetDoCommandModeInstance()
{ {
return GetStorage()->mode_instance; return GetStorage().mode_instance;
} }
/* static */ void ScriptObject::SetDoCommandAsyncMode(ScriptAsyncModeProc *proc, ScriptObject *instance) /* static */ void ScriptObject::SetDoCommandAsyncMode(ScriptAsyncModeProc *proc, ScriptObject *instance)
{ {
GetStorage()->async_mode = proc; GetStorage().async_mode = proc;
GetStorage()->async_mode_instance = instance; GetStorage().async_mode_instance = instance;
} }
/* static */ ScriptAsyncModeProc *ScriptObject::GetDoCommandAsyncMode() /* static */ ScriptAsyncModeProc *ScriptObject::GetDoCommandAsyncMode()
{ {
return GetStorage()->async_mode; return GetStorage().async_mode;
} }
/* static */ ScriptObject *ScriptObject::GetDoCommandAsyncModeInstance() /* static */ ScriptObject *ScriptObject::GetDoCommandAsyncModeInstance()
{ {
return GetStorage()->async_mode_instance; return GetStorage().async_mode_instance;
} }
/* static */ void ScriptObject::SetLastCommand(const CommandDataBuffer &data, Commands cmd) /* static */ void ScriptObject::SetLastCommand(const CommandDataBuffer &data, Commands cmd)
{ {
ScriptStorage *s = GetStorage(); ScriptStorage &s = GetStorage();
Debug(script, 6, "SetLastCommand company={:02d} cmd={} data={}", s->root_company, cmd, FormatArrayAsHex(data)); Debug(script, 6, "SetLastCommand company={:02d} cmd={} data={}", s.root_company, cmd, FormatArrayAsHex(data));
s->last_data = data; s.last_data = data;
s->last_cmd = cmd; s.last_cmd = cmd;
} }
/* static */ bool ScriptObject::CheckLastCommand(const CommandDataBuffer &data, Commands cmd) /* static */ bool ScriptObject::CheckLastCommand(const CommandDataBuffer &data, Commands cmd)
{ {
ScriptStorage *s = GetStorage(); ScriptStorage &s = GetStorage();
Debug(script, 6, "CheckLastCommand company={:02d} cmd={} data={}", s->root_company, cmd, FormatArrayAsHex(data)); Debug(script, 6, "CheckLastCommand company={:02d} cmd={} data={}", s.root_company, cmd, FormatArrayAsHex(data));
if (s->last_cmd != cmd) return false; if (s.last_cmd != cmd) return false;
if (s->last_data != data) return false; if (s.last_data != data) return false;
return true; return true;
} }
/* static */ void ScriptObject::SetDoCommandCosts(Money value) /* static */ void ScriptObject::SetDoCommandCosts(Money value)
{ {
GetStorage()->costs = CommandCost(INVALID_EXPENSES, value); // Expense type is never read. GetStorage().costs = CommandCost(INVALID_EXPENSES, value); // Expense type is never read.
} }
/* static */ void ScriptObject::IncreaseDoCommandCosts(Money value) /* static */ void ScriptObject::IncreaseDoCommandCosts(Money value)
{ {
GetStorage()->costs.AddCost(value); GetStorage().costs.AddCost(value);
} }
/* static */ Money ScriptObject::GetDoCommandCosts() /* static */ Money ScriptObject::GetDoCommandCosts()
{ {
return GetStorage()->costs.GetCost(); return GetStorage().costs.GetCost();
} }
/* static */ void ScriptObject::SetLastError(ScriptErrorType last_error) /* static */ void ScriptObject::SetLastError(ScriptErrorType last_error)
{ {
GetStorage()->last_error = last_error; GetStorage().last_error = last_error;
} }
/* static */ ScriptErrorType ScriptObject::GetLastError() /* static */ ScriptErrorType ScriptObject::GetLastError()
{ {
return GetStorage()->last_error; return GetStorage().last_error;
} }
/* static */ void ScriptObject::SetLastCost(Money last_cost) /* static */ void ScriptObject::SetLastCost(Money last_cost)
{ {
GetStorage()->last_cost = last_cost; GetStorage().last_cost = last_cost;
} }
/* static */ Money ScriptObject::GetLastCost() /* static */ Money ScriptObject::GetLastCost()
{ {
return GetStorage()->last_cost; return GetStorage().last_cost;
} }
/* static */ void ScriptObject::SetRoadType(RoadType road_type) /* static */ void ScriptObject::SetRoadType(RoadType road_type)
{ {
GetStorage()->road_type = road_type; GetStorage().road_type = road_type;
} }
/* static */ RoadType ScriptObject::GetRoadType() /* static */ RoadType ScriptObject::GetRoadType()
{ {
return GetStorage()->road_type; return GetStorage().road_type;
} }
/* static */ void ScriptObject::SetRailType(RailType rail_type) /* static */ void ScriptObject::SetRailType(RailType rail_type)
{ {
GetStorage()->rail_type = rail_type; GetStorage().rail_type = rail_type;
} }
/* static */ RailType ScriptObject::GetRailType() /* static */ RailType ScriptObject::GetRailType()
{ {
return GetStorage()->rail_type; return GetStorage().rail_type;
} }
/* static */ void ScriptObject::SetLastCommandRes(bool res) /* static */ void ScriptObject::SetLastCommandRes(bool res)
{ {
GetStorage()->last_command_res = res; GetStorage().last_command_res = res;
} }
/* static */ bool ScriptObject::GetLastCommandRes() /* static */ bool ScriptObject::GetLastCommandRes()
{ {
return GetStorage()->last_command_res; return GetStorage().last_command_res;
} }
/* static */ void ScriptObject::SetLastCommandResData(CommandDataBuffer data) /* static */ void ScriptObject::SetLastCommandResData(CommandDataBuffer data)
{ {
GetStorage()->last_cmd_ret = std::move(data); GetStorage().last_cmd_ret = std::move(data);
} }
/* static */ const CommandDataBuffer &ScriptObject::GetLastCommandResData() /* static */ const CommandDataBuffer &ScriptObject::GetLastCommandResData()
{ {
return GetStorage()->last_cmd_ret; return GetStorage().last_cmd_ret;
} }
/* static */ void ScriptObject::SetCompany(::CompanyID company) /* static */ void ScriptObject::SetCompany(::CompanyID company)
{ {
if (GetStorage()->root_company == INVALID_OWNER) GetStorage()->root_company = company; if (GetStorage().root_company == INVALID_OWNER) GetStorage().root_company = company;
GetStorage()->company = company; GetStorage().company = company;
_current_company = company; _current_company = company;
} }
/* static */ ::CompanyID ScriptObject::GetCompany() /* static */ ::CompanyID ScriptObject::GetCompany()
{ {
return GetStorage()->company; return GetStorage().company;
} }
/* static */ ::CompanyID ScriptObject::GetRootCompany() /* static */ ::CompanyID ScriptObject::GetRootCompany()
{ {
return GetStorage()->root_company; return GetStorage().root_company;
} }
/* static */ bool ScriptObject::CanSuspend() /* static */ bool ScriptObject::CanSuspend()
{ {
Squirrel *squirrel = ScriptObject::GetActiveInstance().engine; Squirrel *squirrel = ScriptObject::GetActiveInstance().engine;
return GetStorage()->allow_do_command && squirrel->CanSuspend(); return GetStorage().allow_do_command && squirrel->CanSuspend();
} }
/* static */ ScriptEventQueue &ScriptObject::GetEventQueue() /* static */ ScriptEventQueue &ScriptObject::GetEventQueue()
{ {
return GetStorage()->event_queue; return GetStorage().event_queue;
} }
/* static */ ScriptLogTypes::LogData &ScriptObject::GetLogData() /* static */ ScriptLogTypes::LogData &ScriptObject::GetLogData()
{ {
return GetStorage()->log_data; return GetStorage().log_data;
} }
/* static */ void ScriptObject::SetCallbackVariable(int index, int value) /* static */ void ScriptObject::SetCallbackVariable(int index, int value)
{ {
if (static_cast<size_t>(index) >= GetStorage()->callback_value.size()) GetStorage()->callback_value.resize(index + 1); if (static_cast<size_t>(index) >= GetStorage().callback_value.size()) GetStorage().callback_value.resize(index + 1);
GetStorage()->callback_value[index] = value; GetStorage().callback_value[index] = value;
} }
/* static */ int ScriptObject::GetCallbackVariable(int index) /* static */ int ScriptObject::GetCallbackVariable(int index)
{ {
return GetStorage()->callback_value[index]; return GetStorage().callback_value[index];
} }
/* static */ CommandCallbackData *ScriptObject::GetDoCommandCallback() /* static */ CommandCallbackData *ScriptObject::GetDoCommandCallback()
@ -310,8 +310,8 @@ ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
IncreaseDoCommandCosts(res.GetCost()); IncreaseDoCommandCosts(res.GetCost());
if (!_generating_world) { if (!_generating_world) {
/* Charge a nominal fee for asynchronously executed commands */ /* Charge a nominal fee for asynchronously executed commands */
Squirrel *engine = ScriptObject::GetActiveInstance().engine; Squirrel &engine = *ScriptObject::GetActiveInstance().engine;
Squirrel::DecreaseOps(engine->GetVM(), 100); Squirrel::DecreaseOps(engine.GetVM(), 100);
} }
if (callback != nullptr) { if (callback != nullptr) {
/* Insert return value into to stack and throw a control code that /* Insert return value into to stack and throw a control code that

View File

@ -100,7 +100,7 @@ void ScriptInstance::Initialize(const std::string &main_script, const std::strin
void ScriptInstance::RegisterAPI() void ScriptInstance::RegisterAPI()
{ {
squirrel_register_std(this->engine); squirrel_register_std(*this->engine);
} }
bool ScriptInstance::LoadCompatibilityScript(std::string_view api_version, Subdirectory dir) bool ScriptInstance::LoadCompatibilityScript(std::string_view api_version, Subdirectory dir)
@ -318,9 +318,10 @@ void ScriptInstance::CollectGarbage()
} }
ScriptStorage *ScriptInstance::GetStorage() ScriptStorage &ScriptInstance::GetStorage()
{ {
return this->storage; assert(this->storage != nullptr);
return *this->storage;
} }
ScriptLogTypes::LogData &ScriptInstance::GetLogData() ScriptLogTypes::LogData &ScriptInstance::GetLogData()

View File

@ -91,7 +91,7 @@ public:
/** /**
* Get the storage of this script. * Get the storage of this script.
*/ */
class ScriptStorage *GetStorage(); class ScriptStorage &GetStorage();
/** /**
* Get the log pointer of this script. * Get the log pointer of this script.
@ -146,7 +146,11 @@ public:
/** /**
* Get the controller attached to the instance. * Get the controller attached to the instance.
*/ */
class ScriptController *GetController() { return controller; } class ScriptController &GetController()
{
assert(this->controller != nullptr);
return *this->controller;
}
/** /**
* Return the "this script died" value * Return the "this script died" value

View File

@ -536,7 +536,7 @@ void Squirrel::Initialize()
sq_setforeignptr(this->vm, this); sq_setforeignptr(this->vm, this);
sq_pushroottable(this->vm); sq_pushroottable(this->vm);
squirrel_register_global_std(this); squirrel_register_global_std(*this);
/* Set consts table as delegate of root table, so consts/enums defined via require() are accessible */ /* Set consts table as delegate of root table, so consts/enums defined via require() are accessible */
sq_pushconsttable(this->vm); sq_pushconsttable(this->vm);

View File

@ -82,20 +82,20 @@ SQInteger SquirrelStd::notifyallexceptions(HSQUIRRELVM vm)
return SQ_ERROR; return SQ_ERROR;
} }
void squirrel_register_global_std(Squirrel *engine) void squirrel_register_global_std(Squirrel &engine)
{ {
/* We don't use squirrel_helper here, as we want to register to the global /* We don't use squirrel_helper here, as we want to register to the global
* scope and not to a class. */ * scope and not to a class. */
engine->AddMethod("require", &SquirrelStd::require, ".s"); engine.AddMethod("require", &SquirrelStd::require, ".s");
engine->AddMethod("notifyallexceptions", &SquirrelStd::notifyallexceptions, ".b"); engine.AddMethod("notifyallexceptions", &SquirrelStd::notifyallexceptions, ".b");
} }
void squirrel_register_std(Squirrel *engine) void squirrel_register_std(Squirrel &engine)
{ {
/* We don't use squirrel_helper here, as we want to register to the global /* We don't use squirrel_helper here, as we want to register to the global
* scope and not to a class. */ * scope and not to a class. */
engine->AddMethod("min", &SquirrelStd::min, ".ii"); engine.AddMethod("min", &SquirrelStd::min, ".ii");
engine->AddMethod("max", &SquirrelStd::max, ".ii"); engine.AddMethod("max", &SquirrelStd::max, ".ii");
sqstd_register_mathlib(engine->GetVM()); sqstd_register_mathlib(engine.GetVM());
} }

View File

@ -52,12 +52,12 @@ public:
/** /**
* Register all standard functions we want to give to a script. * Register all standard functions we want to give to a script.
*/ */
void squirrel_register_std(Squirrel *engine); void squirrel_register_std(Squirrel &engine);
/** /**
* Register all standard functions that are available on first startup. * Register all standard functions that are available on first startup.
* @note this set is very limited, and is only meant to load other scripts and things like that. * @note this set is very limited, and is only meant to load other scripts and things like that.
*/ */
void squirrel_register_global_std(Squirrel *engine); void squirrel_register_global_std(Squirrel &engine);
#endif /* SQUIRREL_STD_HPP */ #endif /* SQUIRREL_STD_HPP */

View File

@ -3331,7 +3331,7 @@ draw_default_foundation:
auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100); auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100);
if (result.has_value()) { if (result.has_value()) {
if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) { if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
stop_draw_mode = static_cast<RoadStopDrawMode>(regs100[0]); stop_draw_mode = static_cast<RoadStopDrawModes>(regs100[0]);
} }
if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) { if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) {
draw_ground = true; draw_ground = true;

View File

@ -427,6 +427,7 @@ struct TimetableWindow : Window {
void DrawTimetablePanel(const Rect &r) const void DrawTimetablePanel(const Rect &r) const
{ {
const Vehicle *v = this->vehicle; const Vehicle *v = this->vehicle;
if (v->GetNumOrders() == 0) return;
Rect tr = r.Shrink(WidgetDimensions::scaled.framerect); Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
int i = this->vscroll->GetPosition(); int i = this->vscroll->GetPosition();
VehicleOrderID order_id = (i + 1) / 2; VehicleOrderID order_id = (i + 1) / 2;