From 51649e5873c8441e8bfab995e3e4d1d5953417aa Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Fri, 7 Aug 2026 16:22:36 +0200 Subject: [PATCH] Rework Ride and Vehicle headers into OpenRCT2 namespace (#26881) * Move vehicle flags to their own header * Move Ride, RideConstruction, RideRatings, Vehicle into OpenRCT2 namespace * Rename to SpecialDropdownElement as suggested --- src/openrct2-ui/ride/Construction.h | 4 +- src/openrct2-ui/windows/Windows.h | 4 +- .../actions/track/TrackPlaceAction.cpp | 1 + src/openrct2/config/Config.h | 5 +- src/openrct2/drawing/LightFX.h | 2 +- src/openrct2/entity/Guest.h | 3 +- src/openrct2/entity/Staff.h | 6 +- src/openrct2/libopenrct2.vcxproj | 1 + src/openrct2/object/RideObject.h | 4 +- src/openrct2/paint/entity/Paint.Vehicle.h | 10 +- src/openrct2/paint/track/TrackPaintGeneric.h | 4 +- .../track/coaster/TwisterRollerCoaster.h | 22 +- src/openrct2/paint/vehicle/VehiclePaint.h | 32 +- src/openrct2/park/Legacy.h | 7 +- src/openrct2/rct2/RCT2.h | 12 +- src/openrct2/ride/CableLift.h | 12 +- src/openrct2/ride/CarEntry.h | 7 +- src/openrct2/ride/MazeCost.h | 5 +- src/openrct2/ride/Ride.cpp | 10353 ++++++++-------- src/openrct2/ride/Ride.h | 1560 +-- src/openrct2/ride/RideAudio.h | 6 +- src/openrct2/ride/RideBreakdownMap.h | 23 +- src/openrct2/ride/RideConstruction.cpp | 3081 ++--- src/openrct2/ride/RideConstruction.h | 214 +- src/openrct2/ride/RideData.cpp | 660 +- src/openrct2/ride/RideData.h | 1299 +- src/openrct2/ride/RideEntry.h | 5 +- src/openrct2/ride/RideRatings.cpp | 4177 +++---- src/openrct2/ride/RideRatings.h | 18 +- src/openrct2/ride/RideTypes.h | 5 +- src/openrct2/ride/ShopItem.h | 8 +- src/openrct2/ride/Station.cpp | 675 +- src/openrct2/ride/Station.h | 13 +- src/openrct2/ride/TrackDesign.h | 35 +- src/openrct2/ride/TrackIteration.h | 3 +- src/openrct2/ride/TrackPaint.h | 32 +- src/openrct2/ride/TrainManager.h | 5 +- src/openrct2/ride/Vehicle.Animation.cpp | 1952 +-- src/openrct2/ride/Vehicle.MiniGolf.cpp | 2 +- src/openrct2/ride/Vehicle.Sound.cpp | 472 +- src/openrct2/ride/Vehicle.TrackMotion.cpp | 2797 ++--- src/openrct2/ride/Vehicle.cpp | 2798 ++--- src/openrct2/ride/Vehicle.h | 1066 +- src/openrct2/ride/VehicleFlags.h | 45 + src/openrct2/ride/VehicleSubpositionData.h | 7 +- src/openrct2/ride/rtd/coaster/WaterCoaster.h | 2 +- src/openrct2/ride/rtd/gentle/Circus.h | 2 +- src/openrct2/ride/rtd/gentle/GhostTrain.h | 2 +- src/openrct2/ride/rtd/gentle/Maze.h | 2 +- src/openrct2/ride/rtd/gentle/MiniGolf.h | 2 +- src/openrct2/ride/rtd/gentle/SpiralSlide.h | 2 +- src/openrct2/ride/rtd/thrill/Enterprise.h | 2 +- .../ride/rtd/thrill/MotionSimulator.h | 2 +- src/openrct2/ride/rtd/transport/Chairlift.h | 2 +- src/openrct2/ride/rtd/water/LogFlume.h | 2 +- .../scripting/bindings/ride/ScRide.cpp | 2 +- .../scripting/bindings/ride/ScRideStation.cpp | 2 +- .../bindings/ride/ScTrackSegment.cpp | 2 +- src/openrct2/world/Entrance.cpp | 6 +- 59 files changed, 15809 insertions(+), 15675 deletions(-) create mode 100644 src/openrct2/ride/VehicleFlags.h diff --git a/src/openrct2-ui/ride/Construction.h b/src/openrct2-ui/ride/Construction.h index 73bb33fb61..0c6268d284 100644 --- a/src/openrct2-ui/ride/Construction.h +++ b/src/openrct2-ui/ride/Construction.h @@ -27,7 +27,7 @@ namespace OpenRCT2 enum class RideConstructionState : uint8_t; - struct SpecialElement + struct SpecialDropdownElement { TrackElemType TrackType; bool Disabled; @@ -36,7 +36,7 @@ namespace OpenRCT2 struct SpecialElementsDropdownState { bool HasActiveElements = false; - std::vector Elements{}; + std::vector Elements{}; size_t PreferredNumRows{}; }; diff --git a/src/openrct2-ui/windows/Windows.h b/src/openrct2-ui/windows/Windows.h index 5ab77a6d4e..244f57c675 100644 --- a/src/openrct2-ui/windows/Windows.h +++ b/src/openrct2-ui/windows/Windows.h @@ -19,11 +19,9 @@ struct ScreenCoordsXY; struct StringWithArgs; -struct Ride; struct RideSelection; struct TrackDesign; struct TrackDesignFileRef; -struct Vehicle; enum class GuestListFilterType : int32_t; enum class ScatterToolDensity : uint8_t; @@ -36,7 +34,9 @@ namespace OpenRCT2 class Formatter; struct ObjectEntryDescriptor; struct Peep; + struct Ride; struct TileElement; + struct Vehicle; } // namespace OpenRCT2 namespace OpenRCT2::Drawing diff --git a/src/openrct2/actions/track/TrackPlaceAction.cpp b/src/openrct2/actions/track/TrackPlaceAction.cpp index 8ed9a7804d..600a6b0545 100644 --- a/src/openrct2/actions/track/TrackPlaceAction.cpp +++ b/src/openrct2/actions/track/TrackPlaceAction.cpp @@ -15,6 +15,7 @@ #include "../../core/Money.hpp" #include "../../core/Numerics.hpp" #include "../../management/Finance.h" +#include "../../ride/RideColour.h" #include "../../ride/RideData.h" #include "../../ride/Track.h" #include "../../ride/TrackData.h" diff --git a/src/openrct2/config/Config.h b/src/openrct2/config/Config.h index bfd35909f1..68acf54b8b 100644 --- a/src/openrct2/config/Config.h +++ b/src/openrct2/config/Config.h @@ -19,7 +19,10 @@ #undef interface #endif -enum class RideInspection : uint8_t; +namespace OpenRCT2 +{ + enum class RideInspection : uint8_t; +} namespace OpenRCT2::Config { diff --git a/src/openrct2/drawing/LightFX.h b/src/openrct2/drawing/LightFX.h index d7f73cafa1..0d1fe841f6 100644 --- a/src/openrct2/drawing/LightFX.h +++ b/src/openrct2/drawing/LightFX.h @@ -14,12 +14,12 @@ #include struct CoordsXY; -struct Vehicle; struct CoordsXYZ; namespace OpenRCT2 { struct EntityBase; + struct Vehicle; struct Viewport; } // namespace OpenRCT2 diff --git a/src/openrct2/entity/Guest.h b/src/openrct2/entity/Guest.h index 680b2cda5d..1c2a0feaaa 100644 --- a/src/openrct2/entity/Guest.h +++ b/src/openrct2/entity/Guest.h @@ -14,10 +14,11 @@ #include "Peep.h" struct CarEntry; -struct Vehicle; namespace OpenRCT2 { + struct Vehicle; + constexpr int8_t kPeepMaxThoughts = 5; constexpr int8_t kPeepHungerWarningThreshold = 25; diff --git a/src/openrct2/entity/Staff.h b/src/openrct2/entity/Staff.h index d142a197c6..769ecd9ac1 100644 --- a/src/openrct2/entity/Staff.h +++ b/src/openrct2/entity/Staff.h @@ -14,8 +14,6 @@ #include -struct Ride; - namespace OpenRCT2::Drawing { enum class Colour : uint8_t; @@ -24,12 +22,12 @@ namespace OpenRCT2::Drawing namespace OpenRCT2 { class DataSerialiser; + class PatrolArea; + struct Ride; struct TileElement; struct PathElement; - class PatrolArea; - enum class StaffType : uint8_t { handyman, diff --git a/src/openrct2/libopenrct2.vcxproj b/src/openrct2/libopenrct2.vcxproj index 3612209687..9dd84b11a2 100644 --- a/src/openrct2/libopenrct2.vcxproj +++ b/src/openrct2/libopenrct2.vcxproj @@ -602,6 +602,7 @@ + diff --git a/src/openrct2/object/RideObject.h b/src/openrct2/object/RideObject.h index 8bce4e2430..eb908c8e5a 100644 --- a/src/openrct2/object/RideObject.h +++ b/src/openrct2/object/RideObject.h @@ -15,10 +15,10 @@ #include -enum class RideCategory : uint8_t; - namespace OpenRCT2 { + enum class RideCategory : uint8_t; + class RideObject final : public Object { private: diff --git a/src/openrct2/paint/entity/Paint.Vehicle.h b/src/openrct2/paint/entity/Paint.Vehicle.h index 9ef2810750..42ab361c8f 100644 --- a/src/openrct2/paint/entity/Paint.Vehicle.h +++ b/src/openrct2/paint/entity/Paint.Vehicle.h @@ -11,7 +11,11 @@ #include -struct PaintSession; -struct Vehicle; +namespace OpenRCT2 +{ + struct Vehicle; +} -void PaintVehicle(PaintSession& session, const Vehicle& vehicle, int32_t imageDirection); +struct PaintSession; + +void PaintVehicle(PaintSession& session, const OpenRCT2::Vehicle& vehicle, int32_t imageDirection); diff --git a/src/openrct2/paint/track/TrackPaintGeneric.h b/src/openrct2/paint/track/TrackPaintGeneric.h index cbf40dcffc..e866c75c01 100644 --- a/src/openrct2/paint/track/TrackPaintGeneric.h +++ b/src/openrct2/paint/track/TrackPaintGeneric.h @@ -16,10 +16,10 @@ #include "../tile_element/Paint.TileElement.h" #include "Support.h" -struct Ride; - namespace OpenRCT2 { + struct Ride; + ImageId getPrimaryTrackColourWithSecondarySupportColour(const PaintSession& session); template diff --git a/src/openrct2/paint/track/coaster/TwisterRollerCoaster.h b/src/openrct2/paint/track/coaster/TwisterRollerCoaster.h index 85e7b98522..8a4e313a16 100644 --- a/src/openrct2/paint/track/coaster/TwisterRollerCoaster.h +++ b/src/openrct2/paint/track/coaster/TwisterRollerCoaster.h @@ -12,38 +12,38 @@ #include struct PaintSession; -struct Ride; struct SupportType; namespace OpenRCT2 { + struct Ride; struct TrackElement; -} +} // namespace OpenRCT2 void TwisterRCTrackBooster( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackDiagBrakes( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackDiagBlockBrakes( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackFlatTo60DegUpLongBase( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrack60DegUpToFlatLongBase( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackLeftLargeHalfLoopUp( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackRightLargeHalfLoopUp( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackLeftLargeHalfLoopDown( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TwisterRCTrackRightLargeHalfLoopDown( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); diff --git a/src/openrct2/paint/vehicle/VehiclePaint.h b/src/openrct2/paint/vehicle/VehiclePaint.h index 8bddfd7dd7..73d265fe96 100644 --- a/src/openrct2/paint/vehicle/VehiclePaint.h +++ b/src/openrct2/paint/vehicle/VehiclePaint.h @@ -13,7 +13,11 @@ struct PaintSession; struct CarEntry; -struct Vehicle; + +namespace OpenRCT2 +{ + struct Vehicle; +} struct VehicleBoundBox { @@ -28,40 +32,40 @@ struct VehicleBoundBox extern const VehicleBoundBox VehicleBoundboxes[16][224]; void VehicleVisualDefault( - PaintSession& session, int32_t imageDirection, int32_t z, const Vehicle* vehicle, const CarEntry* carEntry); -void VehicleVisualSplashEffect(PaintSession& session, int32_t z, const Vehicle* vehicle, const CarEntry* carEntry); + PaintSession& session, int32_t imageDirection, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); +void VehicleVisualSplashEffect(PaintSession& session, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); namespace OpenRCT2 { void VehicleVisualRotoDrop( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualObservationTower( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualRiverRapids( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualReverser( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualSplashBoatsOrWaterCoaster( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualLaunchedFreefall( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualVirginiaReel( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualSubmarine( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); void VehicleVisualMiniGolfPlayer( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle); + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle); void VehicleVisualMiniGolfBall( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle); + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle); void VehicleVisualClassicMiniSpinning( - PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const Vehicle* vehicle, + PaintSession& session, int32_t x, int32_t imageDirection, int32_t y, int32_t z, const OpenRCT2::Vehicle* vehicle, const CarEntry* carEntry); } // namespace OpenRCT2 diff --git a/src/openrct2/park/Legacy.h b/src/openrct2/park/Legacy.h index 27617bf37f..e0c8d38afe 100644 --- a/src/openrct2/park/Legacy.h +++ b/src/openrct2/park/Legacy.h @@ -35,11 +35,12 @@ namespace OpenRCT2 struct ObjectEntryDescriptor; class ObjectList; + + enum class SpecialElement : uint8_t; + using SpecialElements = FlagHolder; } // namespace OpenRCT2 using ride_type_t = uint16_t; -enum class SpecialElement : uint8_t; -using SpecialElements = FlagHolder; std::string_view MapToNewObjectIdentifier(std::string_view s); std::optional GetDATPathName(std::string_view newPathName); @@ -66,5 +67,5 @@ std::string_view GetClimateObjectIdFromLegacyClimateType(OpenRCT2::RCT12::Climat */ bool TrackTypeMustBeMadeInvisible(const OpenRCT2::TrackElement& trackElement, int32_t parkFileVersion = -1); -std::pair splitCombinedHelicesAndSpecialElements(uint8_t combinedValue); +std::pair splitCombinedHelicesAndSpecialElements(uint8_t combinedValue); std::pair splitCombinedNumDropsPoweredLifts(uint8_t combinedValue); diff --git a/src/openrct2/rct2/RCT2.h b/src/openrct2/rct2/RCT2.h index e94fed15af..d4097f66ed 100644 --- a/src/openrct2/rct2/RCT2.h +++ b/src/openrct2/rct2/RCT2.h @@ -22,12 +22,16 @@ struct RideObjectEntry; -enum class Breakdown : uint8_t; -enum class MechanicStatus : uint8_t; -enum class RideInvalidateFlag : uint8_t; enum class VehicleColourSettings : uint8_t; -using RideInvalidateFlags = FlagHolder; +namespace OpenRCT2 +{ + enum class Breakdown : uint8_t; + enum class MechanicStatus : uint8_t; + enum class RideInvalidateFlag : uint8_t; + + using RideInvalidateFlags = FlagHolder; +} // namespace OpenRCT2 namespace OpenRCT2::Editor { diff --git a/src/openrct2/ride/CableLift.h b/src/openrct2/ride/CableLift.h index 798ad0265a..a95627039b 100644 --- a/src/openrct2/ride/CableLift.h +++ b/src/openrct2/ride/CableLift.h @@ -11,8 +11,12 @@ #include -struct Vehicle; -struct Ride; +namespace OpenRCT2 +{ + struct Vehicle; + struct Ride; +} // namespace OpenRCT2 -Vehicle* CableLiftSegmentCreate( - Ride& ride, int32_t x, int32_t y, int32_t z, int32_t direction, uint16_t var_44, int32_t remaining_distance, bool head); +OpenRCT2::Vehicle* CableLiftSegmentCreate( + OpenRCT2::Ride& ride, int32_t x, int32_t y, int32_t z, int32_t direction, uint16_t var_44, int32_t remaining_distance, + bool head); diff --git a/src/openrct2/ride/CarEntry.h b/src/openrct2/ride/CarEntry.h index 65cd503545..57c8f72eae 100644 --- a/src/openrct2/ride/CarEntry.h +++ b/src/openrct2/ride/CarEntry.h @@ -23,7 +23,10 @@ namespace OpenRCT2::Audio enum class SoundId : uint8_t; } -enum class SoundRange : uint8_t; +namespace OpenRCT2 +{ + enum class SoundRange : uint8_t; +} enum class CarEntryAnimation : uint8_t { @@ -212,7 +215,7 @@ struct CarEntry uint8_t spinning_friction; OpenRCT2::Audio::SoundId friction_sound_id; // Only valid for front/default car of train uint8_t ReversedCarIndex; // When the car is reversed (using a turntable or reverser), it will be changed to this car. - SoundRange soundRange; + OpenRCT2::SoundRange soundRange; uint8_t double_sound_frequency; // (Doubles the velocity when working out the sound frequency {used on go karts}) uint8_t powered_acceleration; uint8_t powered_max_speed; diff --git a/src/openrct2/ride/MazeCost.h b/src/openrct2/ride/MazeCost.h index 191d3919a8..ce4f2f03b2 100644 --- a/src/openrct2/ride/MazeCost.h +++ b/src/openrct2/ride/MazeCost.h @@ -12,9 +12,10 @@ #include "../core/Money.hpp" struct CoordsXYZ; -struct Ride; namespace OpenRCT2 { + struct Ride; + money64 MazeCalculateCost(money64 constructionCost, const Ride& ride, const CoordsXYZ& loc); -} +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Ride.cpp b/src/openrct2/ride/Ride.cpp index 2a7cf0c143..be256aaf31 100644 --- a/src/openrct2/ride/Ride.cpp +++ b/src/openrct2/ride/Ride.cpp @@ -77,601 +77,603 @@ #include #include -using namespace OpenRCT2; -using namespace OpenRCT2::TrackMetadata; -using namespace OpenRCT2::Scripting; - -static constexpr auto kRideModeBlockSectionedCounterpart = std::to_array( - { - RideMode::normal, // RideMode::normal, - RideMode::continuousCircuitBlockSectioned, // RideMode::continuousCircuit, - RideMode::reverseInclineLaunchedShuttle, // RideMode::reverseInclineLaunchedShuttle, - RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunchPassthrough, - RideMode::shuttle, // RideMode::shuttle, - RideMode::boatHire, // RideMode::boatHire, - RideMode::upwardLaunch, // RideMode::upwardLaunch, - RideMode::rotatingLift, // RideMode::rotatingLift, - RideMode::stationToStation, // RideMode::stationToStation, - RideMode::singleRidePerAdmission, // RideMode::singleRidePerAdmission, - RideMode::unlimitedRidesPerAdmission, // RideMode::unlimitedRidesPerAdmission , - RideMode::maze, // RideMode::maze, - RideMode::race, // RideMode::race, - RideMode::dodgems, // RideMode::dodgems, - RideMode::swing, // RideMode::swing, - RideMode::shopStall, // RideMode::shopStall, - RideMode::rotation, // RideMode::rotation, - RideMode::forwardRotation, // RideMode::forwardRotation, - RideMode::backwardRotation, // RideMode::backwardRotation, - RideMode::filmAvengingAviators, // RideMode::filmAvengingAviators, - RideMode::mouseTails3DFilm, // RideMode::mouseTails3DFilm, - RideMode::spaceRings, // RideMode::spaceRings, - RideMode::beginners, // RideMode::beginners, - RideMode::limPoweredLaunch, // RideMode::limPoweredLaunch, - RideMode::filmThrillRiders, // RideMode::filmThrillRiders, - RideMode::stormChasers3DFilm, // RideMode::stormChasers3DFilm, - RideMode::spaceRaiders3DFilm, // RideMode::spaceRaiders3DFilm, - RideMode::intense, // RideMode::intense, - RideMode::berserk, // RideMode::berserk, - RideMode::hauntedHouse, // RideMode::hauntedHouse, - RideMode::circus, // RideMode::circus, - RideMode::downwardLaunch, // RideMode::downwardLaunch, - RideMode::crookedHouse, // RideMode::crookedHouse, - RideMode::freefallDrop, // RideMode::freefallDrop, - RideMode::continuousCircuitBlockSectioned, // RideMode::continuousCircuitBlockSectioned, - RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunch, - RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunchBlockSectioned, - }); -static_assert(kRideModeBlockSectionedCounterpart.size() == EnumValue(RideMode::count)); - -RideMode& operator++(RideMode& d, int) +namespace OpenRCT2 { - return d = (d == RideMode::count) ? RideMode::normal : static_cast(static_cast(d) + 1); -} + using namespace OpenRCT2::Entity::Yaw; + using namespace OpenRCT2::TrackMetadata; + using namespace OpenRCT2::Scripting; -static constexpr int32_t RideInspectionInterval[] = { - 10, 20, 30, 45, 60, 120, 0, 0, -}; - -// clang-format off -const StringId kRideInspectionIntervalNames[] = { - STR_EVERY_10_MINUTES, - STR_EVERY_20_MINUTES, - STR_EVERY_30_MINUTES, - STR_EVERY_45_MINUTES, - STR_EVERY_HOUR, - STR_EVERY_2_HOURS, - STR_NEVER, -}; -// clang-format on - -// A special instance of Ride that is used to draw previews such as the track designs. -static Ride _previewRide{}; - -struct StationIndexWithMessage -{ - ::StationIndex StationIndex; - StringId Message = kStringIdNone; -}; - -// Static function declarations -Staff* FindClosestMechanic(const CoordsXY& entrancePosition, int32_t forInspection); -static void RideBreakdownStatusUpdate(Ride& ride); -static void RideBreakdownUpdate(Ride& ride); -static void RideCallClosestMechanic(Ride& ride); -static void RideCallMechanic(Ride& ride, Peep* mechanic, int32_t forInspection); -static void RideEntranceExitConnected(Ride& ride); -static Breakdown RideGetNewBreakdownProblem(const Ride& ride); -static void RideInspectionUpdate(Ride& ride); -static void RideMechanicStatusUpdate(Ride& ride, MechanicStatus mechanicStatus); -static void RideMusicUpdate(Ride& ride); -static void RideShopConnected(const Ride& ride); - -RideId GetNextFreeRideId() -{ - auto& gameState = getGameState(); - for (RideId::UnderlyingType i = 0; i < gameState.rides.size(); i++) - { - if (gameState.rides[i].id.IsNull()) + static constexpr auto kRideModeBlockSectionedCounterpart = std::to_array( { - return RideId::FromUnderlying(i); + RideMode::normal, // RideMode::normal, + RideMode::continuousCircuitBlockSectioned, // RideMode::continuousCircuit, + RideMode::reverseInclineLaunchedShuttle, // RideMode::reverseInclineLaunchedShuttle, + RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunchPassthrough, + RideMode::shuttle, // RideMode::shuttle, + RideMode::boatHire, // RideMode::boatHire, + RideMode::upwardLaunch, // RideMode::upwardLaunch, + RideMode::rotatingLift, // RideMode::rotatingLift, + RideMode::stationToStation, // RideMode::stationToStation, + RideMode::singleRidePerAdmission, // RideMode::singleRidePerAdmission, + RideMode::unlimitedRidesPerAdmission, // RideMode::unlimitedRidesPerAdmission , + RideMode::maze, // RideMode::maze, + RideMode::race, // RideMode::race, + RideMode::dodgems, // RideMode::dodgems, + RideMode::swing, // RideMode::swing, + RideMode::shopStall, // RideMode::shopStall, + RideMode::rotation, // RideMode::rotation, + RideMode::forwardRotation, // RideMode::forwardRotation, + RideMode::backwardRotation, // RideMode::backwardRotation, + RideMode::filmAvengingAviators, // RideMode::filmAvengingAviators, + RideMode::mouseTails3DFilm, // RideMode::mouseTails3DFilm, + RideMode::spaceRings, // RideMode::spaceRings, + RideMode::beginners, // RideMode::beginners, + RideMode::limPoweredLaunch, // RideMode::limPoweredLaunch, + RideMode::filmThrillRiders, // RideMode::filmThrillRiders, + RideMode::stormChasers3DFilm, // RideMode::stormChasers3DFilm, + RideMode::spaceRaiders3DFilm, // RideMode::spaceRaiders3DFilm, + RideMode::intense, // RideMode::intense, + RideMode::berserk, // RideMode::berserk, + RideMode::hauntedHouse, // RideMode::hauntedHouse, + RideMode::circus, // RideMode::circus, + RideMode::downwardLaunch, // RideMode::downwardLaunch, + RideMode::crookedHouse, // RideMode::crookedHouse, + RideMode::freefallDrop, // RideMode::freefallDrop, + RideMode::continuousCircuitBlockSectioned, // RideMode::continuousCircuitBlockSectioned, + RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunch, + RideMode::poweredLaunchBlockSectioned, // RideMode::poweredLaunchBlockSectioned, + }); + static_assert(kRideModeBlockSectionedCounterpart.size() == EnumValue(RideMode::count)); + + RideMode& operator++(RideMode& d, int) + { + return d = (d == RideMode::count) ? RideMode::normal : static_cast(static_cast(d) + 1); + } + + static constexpr int32_t RideInspectionInterval[] = { + 10, 20, 30, 45, 60, 120, 0, 0, + }; + + // clang-format off + const StringId kRideInspectionIntervalNames[] = { + STR_EVERY_10_MINUTES, + STR_EVERY_20_MINUTES, + STR_EVERY_30_MINUTES, + STR_EVERY_45_MINUTES, + STR_EVERY_HOUR, + STR_EVERY_2_HOURS, + STR_NEVER, + }; + // clang-format on + + // A special instance of Ride that is used to draw previews such as the track designs. + static Ride _previewRide{}; + + struct StationIndexWithMessage + { + ::StationIndex StationIndex; + StringId Message = kStringIdNone; + }; + + // Static function declarations + Staff* FindClosestMechanic(const CoordsXY& entrancePosition, int32_t forInspection); + static void RideBreakdownStatusUpdate(Ride& ride); + static void RideBreakdownUpdate(Ride& ride); + static void RideCallClosestMechanic(Ride& ride); + static void RideCallMechanic(Ride& ride, Peep* mechanic, int32_t forInspection); + static void RideEntranceExitConnected(Ride& ride); + static Breakdown RideGetNewBreakdownProblem(const Ride& ride); + static void RideInspectionUpdate(Ride& ride); + static void RideMechanicStatusUpdate(Ride& ride, MechanicStatus mechanicStatus); + static void RideMusicUpdate(Ride& ride); + static void RideShopConnected(const Ride& ride); + + RideId GetNextFreeRideId() + { + auto& gameState = getGameState(); + for (RideId::UnderlyingType i = 0; i < gameState.rides.size(); i++) + { + if (gameState.rides[i].id.IsNull()) + { + return RideId::FromUnderlying(i); + } + } + return RideId::GetNull(); + } + + Ride* RideAllocateAtIndex(RideId index) + { + const auto idx = index.ToUnderlying(); + + auto& gameState = getGameState(); + gameState.ridesEndOfUsedRange = std::max(idx + 1, gameState.ridesEndOfUsedRange); + + auto result = &gameState.rides[idx]; + assert(result->id == RideId::GetNull()); + + // Initialize the ride to all the defaults. + *result = Ride{}; + + // Because it is default initialized to zero rather than the magic constant for Null, fill the array. + std::fill(std::begin(result->vehicles), std::end(result->vehicles), EntityId::GetNull()); + + result->id = index; + return result; + } + + Ride& RideGetTemporaryForPreview() + { + return _previewRide; + } + + static void RideReset(Ride& ride) + { + ride.id = RideId::GetNull(); + ride.type = kRideTypeNull; + ride.customName = {}; + ride.measurement = {}; + } + + void RideDelete(RideId id) + { + auto& gameState = getGameState(); + const auto idx = id.ToUnderlying(); + + assert(idx < gameState.rides.size()); + assert(gameState.rides[idx].type != kRideTypeNull); + + auto& ride = gameState.rides[idx]; + RideReset(ride); + + // Shrink maximum ride size. + while (gameState.ridesEndOfUsedRange > 0 && gameState.rides[gameState.ridesEndOfUsedRange - 1].id.IsNull()) + { + gameState.ridesEndOfUsedRange--; } } - return RideId::GetNull(); -} -Ride* RideAllocateAtIndex(RideId index) -{ - const auto idx = index.ToUnderlying(); - - auto& gameState = getGameState(); - gameState.ridesEndOfUsedRange = std::max(idx + 1, gameState.ridesEndOfUsedRange); - - auto result = &gameState.rides[idx]; - assert(result->id == RideId::GetNull()); - - // Initialize the ride to all the defaults. - *result = Ride{}; - - // Because it is default initialized to zero rather than the magic constant for Null, fill the array. - std::fill(std::begin(result->vehicles), std::end(result->vehicles), EntityId::GetNull()); - - result->id = index; - return result; -} - -Ride& RideGetTemporaryForPreview() -{ - return _previewRide; -} - -static void RideReset(Ride& ride) -{ - ride.id = RideId::GetNull(); - ride.type = kRideTypeNull; - ride.customName = {}; - ride.measurement = {}; -} - -void RideDelete(RideId id) -{ - auto& gameState = getGameState(); - const auto idx = id.ToUnderlying(); - - assert(idx < gameState.rides.size()); - assert(gameState.rides[idx].type != kRideTypeNull); - - auto& ride = gameState.rides[idx]; - RideReset(ride); - - // Shrink maximum ride size. - while (gameState.ridesEndOfUsedRange > 0 && gameState.rides[gameState.ridesEndOfUsedRange - 1].id.IsNull()) + Ride* GetRide(RideId index) { - gameState.ridesEndOfUsedRange--; - } -} + if (index.IsNull()) + { + return nullptr; + } + + auto& gameState = getGameState(); + const auto idx = index.ToUnderlying(); + if (idx >= gameState.rides.size()) + { + return nullptr; + } + + auto& ride = gameState.rides[idx]; + if (ride.type != kRideTypeNull) + { + assert(ride.id == index); + return &ride; + } -Ride* GetRide(RideId index) -{ - if (index.IsNull()) - { return nullptr; } - auto& gameState = getGameState(); - const auto idx = index.ToUnderlying(); - if (idx >= gameState.rides.size()) + const RideObjectEntry* GetRideEntryByIndex(ObjectEntryIndex index) { - return nullptr; + auto& objMgr = GetContext()->GetObjectManager(); + + auto obj = objMgr.GetLoadedObject(index); + if (obj == nullptr) + { + return nullptr; + } + + return static_cast(obj->GetLegacyData()); } - auto& ride = gameState.rides[idx]; - if (ride.type != kRideTypeNull) + std::string_view GetRideEntryName(ObjectEntryIndex index) { - assert(ride.id == index); - return &ride; - } + if (index >= getObjectEntryGroupCount(ObjectType::ride)) + { + LOG_ERROR("invalid index %d for ride type", index); + return {}; + } - return nullptr; -} - -const RideObjectEntry* GetRideEntryByIndex(ObjectEntryIndex index) -{ - auto& objMgr = GetContext()->GetObjectManager(); - - auto obj = objMgr.GetLoadedObject(index); - if (obj == nullptr) - { - return nullptr; - } - - return static_cast(obj->GetLegacyData()); -} - -std::string_view GetRideEntryName(ObjectEntryIndex index) -{ - if (index >= getObjectEntryGroupCount(ObjectType::ride)) - { - LOG_ERROR("invalid index %d for ride type", index); + auto objectEntry = ObjectEntryGetObject(ObjectType::ride, index); + if (objectEntry != nullptr) + { + return objectEntry->GetLegacyIdentifier(); + } return {}; } - auto objectEntry = ObjectEntryGetObject(ObjectType::ride, index); - if (objectEntry != nullptr) + const RideObjectEntry* Ride::getRideEntry() const { - return objectEntry->GetLegacyIdentifier(); + return GetRideEntryByIndex(subtype); } - return {}; -} -const RideObjectEntry* Ride::getRideEntry() const -{ - return GetRideEntryByIndex(subtype); -} - -int32_t RideGetCount() -{ - auto& gameState = getGameState(); - return static_cast(RideManager(gameState).size()); -} - -size_t Ride::getNumPrices() const -{ - size_t result = 0; - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::cashMachine || rtd.specialType == RtdSpecialType::firstAid) + int32_t RideGetCount() { - result = 0; + auto& gameState = getGameState(); + return static_cast(RideManager(gameState).size()); } - else if (rtd.specialType == RtdSpecialType::toilet) - { - result = 1; - } - else - { - result = 1; - auto rideEntry = getRideEntry(); - if (rideEntry != nullptr) + size_t Ride::getNumPrices() const + { + size_t result = 0; + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::cashMachine || rtd.specialType == RtdSpecialType::firstAid) { - if (flags.has(RideFlag::onRidePhoto)) - { - result++; - } - else if (rideEntry->shop_item[1] != ShopItem::none) - { - result++; - } + result = 0; } - } - return result; -} - -int32_t Ride::getAge() const -{ - return GetDate().GetMonthsElapsed() - buildDate; -} - -int32_t Ride::getTotalQueueLength() const -{ - int32_t queueLength = 0; - for (const auto& station : stations) - if (!station.Entrance.IsNull()) - queueLength += station.QueueLength; - return queueLength; -} - -int32_t Ride::getMaxQueueTime() const -{ - uint8_t queueTime = 0; - for (const auto& station : stations) - if (!station.Entrance.IsNull()) - queueTime = std::max(queueTime, station.QueueTime); - return static_cast(queueTime); -} - -Guest* Ride::getQueueHeadGuest(StationIndex stationIndex) const -{ - Guest* peep; - Guest* result = nullptr; - auto spriteIndex = getStation(stationIndex).LastPeepInQueue; - while ((peep = getGameState().entities.TryGetEntity(spriteIndex)) != nullptr) - { - spriteIndex = peep->guestNextInQueue; - result = peep; - } - return result; -} - -void Ride::updateQueueLength(StationIndex stationIndex) -{ - uint16_t count = 0; - Guest* peep; - auto& station = getStation(stationIndex); - auto spriteIndex = station.LastPeepInQueue; - while ((peep = getGameState().entities.TryGetEntity(spriteIndex)) != nullptr) - { - spriteIndex = peep->guestNextInQueue; - count++; - } - station.QueueLength = count; -} - -void Ride::queueInsertGuestAtFront(StationIndex stationIndex, Guest* peep) -{ - assert(stationIndex.ToUnderlying() < OpenRCT2::Limits::kMaxStationsPerRide); - assert(peep != nullptr); - - peep->guestNextInQueue = EntityId::GetNull(); - auto* queueHeadGuest = getQueueHeadGuest(peep->CurrentRideStation); - if (queueHeadGuest == nullptr) - { - getStation(peep->CurrentRideStation).LastPeepInQueue = peep->id; - } - else - { - queueHeadGuest->guestNextInQueue = peep->id; - } - updateQueueLength(peep->CurrentRideStation); -} - -/** - * - * rct2: 0x006AC916 - */ -void RideUpdateFavouritedStat() -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - ride.guestsFavourite = 0; - - for (auto peep : EntityList()) - { - if (!peep->favouriteRide.IsNull()) + else if (rtd.specialType == RtdSpecialType::toilet) { - auto ride = GetRide(peep->favouriteRide); - if (ride != nullptr) - { - ride->guestsFavourite = AddClamp(ride->guestsFavourite, 1u); - ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); - } - } - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByClass(WindowClass::rideList); -} - -/** - * - * rct2: 0x006AC3AB - */ -money64 Ride::calculateIncomePerHour() const -{ - // Get entry by ride to provide better reporting - const auto* entry = getRideEntry(); - if (entry == nullptr) - { - return 0; - } - auto customersPerHour = RideCustomersPerHour(*this); - money64 priceMinusCost = RideGetPrice(*this); - - ShopItem currentShopItem = entry->shop_item[0]; - if (currentShopItem != ShopItem::none) - { - priceMinusCost -= GetShopItemDescriptor(currentShopItem).Cost; - } - - currentShopItem = flags.has(RideFlag::onRidePhoto) ? getRideTypeDescriptor().PhotoItem : entry->shop_item[1]; - - if (currentShopItem != ShopItem::none) - { - const money64 shopItemProfit = price[1] - GetShopItemDescriptor(currentShopItem).Cost; - - if (GetShopItemDescriptor(currentShopItem).IsPhoto()) - { - const int32_t rideTicketsSold = totalCustomers - numSecondaryItemsSold; - - // Use the ratio between photo sold and total admissions to approximate the photo income(as not every guest will buy - // one). - // TODO: use data from the last 5 minutes instead of all-time values for a more accurate calculation - if (rideTicketsSold > 0) - { - priceMinusCost += ((static_cast(numSecondaryItemsSold) * shopItemProfit) / rideTicketsSold); - } + result = 1; } else { - priceMinusCost += shopItemProfit; - } + result = 1; - if (entry->shop_item[0] != ShopItem::none) - priceMinusCost /= 2; + auto rideEntry = getRideEntry(); + if (rideEntry != nullptr) + { + if (flags.has(RideFlag::onRidePhoto)) + { + result++; + } + else if (rideEntry->shop_item[1] != ShopItem::none) + { + result++; + } + } + } + return result; } - return customersPerHour * priceMinusCost; -} - -/** - * - * rct2: 0x006CAF80 - * ax result x - * bx result y - * dl ride index - * esi result map element - */ -bool RideTryGetOriginElement(const Ride& ride, CoordsXYE* output) -{ - TileElement* resultTileElement = nullptr; - - TileElementIterator it; - TileElementIteratorBegin(&it); - do + int32_t Ride::getAge() const { - if (it.element->getType() != TileElementType::track) - continue; - if (it.element->asTrack()->GetRideIndex() != ride.id) - continue; + return GetDate().GetMonthsElapsed() - buildDate; + } - // Found a track piece for target ride + int32_t Ride::getTotalQueueLength() const + { + int32_t queueLength = 0; + for (const auto& station : stations) + if (!station.Entrance.IsNull()) + queueLength += station.QueueLength; + return queueLength; + } - // Check if it's not the station or ??? (but allow end piece of station) - const auto& ted = GetTrackElementDescriptor(it.element->asTrack()->GetTrackType()); - bool specialTrackPiece - = (it.element->asTrack()->GetTrackType() != TrackElemType::beginStation - && it.element->asTrack()->GetTrackType() != TrackElemType::middleStation - && ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)); + int32_t Ride::getMaxQueueTime() const + { + uint8_t queueTime = 0; + for (const auto& station : stations) + if (!station.Entrance.IsNull()) + queueTime = std::max(queueTime, station.QueueTime); + return static_cast(queueTime); + } - // Set result tile to this track piece if first found track or a ??? - if (resultTileElement == nullptr || specialTrackPiece) + Guest* Ride::getQueueHeadGuest(StationIndex stationIndex) const + { + Guest* peep; + Guest* result = nullptr; + auto spriteIndex = getStation(stationIndex).LastPeepInQueue; + while ((peep = getGameState().entities.TryGetEntity(spriteIndex)) != nullptr) { - resultTileElement = it.element; + spriteIndex = peep->guestNextInQueue; + result = peep; + } + return result; + } - if (output != nullptr) + void Ride::updateQueueLength(StationIndex stationIndex) + { + uint16_t count = 0; + Guest* peep; + auto& station = getStation(stationIndex); + auto spriteIndex = station.LastPeepInQueue; + while ((peep = getGameState().entities.TryGetEntity(spriteIndex)) != nullptr) + { + spriteIndex = peep->guestNextInQueue; + count++; + } + station.QueueLength = count; + } + + void Ride::queueInsertGuestAtFront(StationIndex stationIndex, Guest* peep) + { + assert(stationIndex.ToUnderlying() < Limits::kMaxStationsPerRide); + assert(peep != nullptr); + + peep->guestNextInQueue = EntityId::GetNull(); + auto* queueHeadGuest = getQueueHeadGuest(peep->CurrentRideStation); + if (queueHeadGuest == nullptr) + { + getStation(peep->CurrentRideStation).LastPeepInQueue = peep->id; + } + else + { + queueHeadGuest->guestNextInQueue = peep->id; + } + updateQueueLength(peep->CurrentRideStation); + } + + /** + * + * rct2: 0x006AC916 + */ + void RideUpdateFavouritedStat() + { + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + ride.guestsFavourite = 0; + + for (auto peep : EntityList()) + { + if (!peep->favouriteRide.IsNull()) { - output->element = resultTileElement; - output->x = it.x * kCoordsXYStep; - output->y = it.y * kCoordsXYStep; + auto ride = GetRide(peep->favouriteRide); + if (ride != nullptr) + { + ride->guestsFavourite = AddClamp(ride->guestsFavourite, 1u); + ride->windowInvalidateFlags.set(RideInvalidateFlag::customers); + } } } - if (specialTrackPiece) + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByClass(WindowClass::rideList); + } + + /** + * + * rct2: 0x006AC3AB + */ + money64 Ride::calculateIncomePerHour() const + { + // Get entry by ride to provide better reporting + const auto* entry = getRideEntry(); + if (entry == nullptr) { - return true; + return 0; } - } while (TileElementIteratorNext(&it)); + auto customersPerHour = RideCustomersPerHour(*this); + money64 priceMinusCost = RideGetPrice(*this); - return resultTileElement != nullptr; -} - -void Ride::formatStatusTo(Formatter& ft) const -{ - if (flags.has(RideFlag::crashed)) - { - ft.Add(STR_CRASHED); - } - else if (flags.has(RideFlag::brokenDown)) - { - ft.Add(STR_BROKEN_DOWN); - } - else if (status == RideStatus::closed) - { - if (!getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + ShopItem currentShopItem = entry->shop_item[0]; + if (currentShopItem != ShopItem::none) { - if (numRiders != 0) + priceMinusCost -= GetShopItemDescriptor(currentShopItem).Cost; + } + + currentShopItem = flags.has(RideFlag::onRidePhoto) ? getRideTypeDescriptor().PhotoItem : entry->shop_item[1]; + + if (currentShopItem != ShopItem::none) + { + const money64 shopItemProfit = price[1] - GetShopItemDescriptor(currentShopItem).Cost; + + if (GetShopItemDescriptor(currentShopItem).IsPhoto()) { - ft.Add(numRiders == 1 ? STR_CLOSED_WITH_PERSON : STR_CLOSED_WITH_PEOPLE); - ft.Add(numRiders); + const int32_t rideTicketsSold = totalCustomers - numSecondaryItemsSold; + + // Use the ratio between photo sold and total admissions to approximate the photo income(as not every guest will + // buy one). + // TODO: use data from the last 5 minutes instead of all-time values for a more accurate calculation + if (rideTicketsSold > 0) + { + priceMinusCost += ((static_cast(numSecondaryItemsSold) * shopItemProfit) / rideTicketsSold); + } + } + else + { + priceMinusCost += shopItemProfit; + } + + if (entry->shop_item[0] != ShopItem::none) + priceMinusCost /= 2; + } + + return customersPerHour * priceMinusCost; + } + + /** + * + * rct2: 0x006CAF80 + * ax result x + * bx result y + * dl ride index + * esi result map element + */ + bool RideTryGetOriginElement(const Ride& ride, CoordsXYE* output) + { + TileElement* resultTileElement = nullptr; + + TileElementIterator it; + TileElementIteratorBegin(&it); + do + { + if (it.element->getType() != TileElementType::track) + continue; + if (it.element->asTrack()->GetRideIndex() != ride.id) + continue; + + // Found a track piece for target ride + + // Check if it's not the station or ??? (but allow end piece of station) + const auto& ted = GetTrackElementDescriptor(it.element->asTrack()->GetTrackType()); + bool specialTrackPiece + = (it.element->asTrack()->GetTrackType() != TrackElemType::beginStation + && it.element->asTrack()->GetTrackType() != TrackElemType::middleStation + && ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)); + + // Set result tile to this track piece if first found track or a ??? + if (resultTileElement == nullptr || specialTrackPiece) + { + resultTileElement = it.element; + + if (output != nullptr) + { + output->element = resultTileElement; + output->x = it.x * kCoordsXYStep; + output->y = it.y * kCoordsXYStep; + } + } + + if (specialTrackPiece) + { + return true; + } + } while (TileElementIteratorNext(&it)); + + return resultTileElement != nullptr; + } + + void Ride::formatStatusTo(Formatter& ft) const + { + if (flags.has(RideFlag::crashed)) + { + ft.Add(STR_CRASHED); + } + else if (flags.has(RideFlag::brokenDown)) + { + ft.Add(STR_BROKEN_DOWN); + } + else if (status == RideStatus::closed) + { + if (!getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + { + if (numRiders != 0) + { + ft.Add(numRiders == 1 ? STR_CLOSED_WITH_PERSON : STR_CLOSED_WITH_PEOPLE); + ft.Add(numRiders); + } + else + { + ft.Add(STR_CLOSED); + } } else { ft.Add(STR_CLOSED); } } - else + else if (status == RideStatus::simulating) { - ft.Add(STR_CLOSED); + ft.Add(STR_SIMULATING); } - } - else if (status == RideStatus::simulating) - { - ft.Add(STR_SIMULATING); - } - else if (status == RideStatus::testing) - { - ft.Add(STR_TEST_RUN); - } - else if (mode == RideMode::race && !flags.has(RideFlag::passStationNoStopping) && !raceWinner.IsNull()) - { - auto peep = getGameState().entities.GetEntity(raceWinner); - if (peep != nullptr) + else if (status == RideStatus::testing) { - ft.Add(STR_RACE_WON_BY); - peep->FormatNameTo(ft); + ft.Add(STR_TEST_RUN); + } + else if (mode == RideMode::race && !flags.has(RideFlag::passStationNoStopping) && !raceWinner.IsNull()) + { + auto peep = getGameState().entities.GetEntity(raceWinner); + if (peep != nullptr) + { + ft.Add(STR_RACE_WON_BY); + peep->FormatNameTo(ft); + } + else + { + ft.Add(STR_RACE_WON_BY); + ft.Add(kStringIdNone); + } + } + else if (!getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + { + ft.Add(numRiders == 1 ? STR_PERSON_ON_RIDE : STR_PEOPLE_ON_RIDE); + ft.Add(numRiders); } else { - ft.Add(STR_RACE_WON_BY); - ft.Add(kStringIdNone); + ft.Add(STR_OPEN); } } - else if (!getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + + int32_t Ride::getTotalLength() const { - ft.Add(numRiders == 1 ? STR_PERSON_ON_RIDE : STR_PEOPLE_ON_RIDE); - ft.Add(numRiders); - } - else - { - ft.Add(STR_OPEN); - } -} - -int32_t Ride::getTotalLength() const -{ - int32_t totalLength = 0; - for (int32_t i = 0; i < numStations; i++) - totalLength += stations[i].SegmentLength; - return totalLength; -} - -int32_t Ride::getTotalTime() const -{ - int32_t totalTime = 0; - for (int32_t i = 0; i < numStations; i++) - totalTime += stations[i].SegmentTime; - return totalTime; -} - -bool Ride::canHaveMultipleCircuits() const -{ - if (!getRideTypeDescriptor().flags.has(RtdFlag::allowMultipleCircuits)) - return false; - - // Only allow circuit or launch modes - if (mode != RideMode::continuousCircuit && mode != RideMode::reverseInclineLaunchedShuttle - && mode != RideMode::poweredLaunchPassthrough) - { - return false; + int32_t totalLength = 0; + for (int32_t i = 0; i < numStations; i++) + totalLength += stations[i].SegmentLength; + return totalLength; } - // Must have no more than one vehicle and one station - if (numTrains > 1 || numStations > 1) - return false; - - return true; -} - -bool Ride::supportsStatus(RideStatus s) const -{ - const auto& rtd = getRideTypeDescriptor(); - - switch (s) + int32_t Ride::getTotalTime() const { - case RideStatus::closed: - case RideStatus::open: - return true; - case RideStatus::simulating: - return (!rtd.flags.has(RtdFlag::noTestMode) && rtd.flags.has(RtdFlag::hasTrack)); - case RideStatus::testing: - return !rtd.flags.has(RtdFlag::noTestMode); - case RideStatus::count: // Meaningless but necessary to satisfy -Wswitch + int32_t totalTime = 0; + for (int32_t i = 0; i < numStations; i++) + totalTime += stations[i].SegmentTime; + return totalTime; + } + + bool Ride::canHaveMultipleCircuits() const + { + if (!getRideTypeDescriptor().flags.has(RtdFlag::allowMultipleCircuits)) return false; - } - // Unreachable - return false; -} -bool Ride::hasFailingBrakes() const -{ - return flags.has(RideFlag::brokenDown) && breakdownReasonPending == Breakdown::brakesFailure - && mechanicStatus != MechanicStatus::hasFixedStationBrakes; -} + // Only allow circuit or launch modes + if (mode != RideMode::continuousCircuit && mode != RideMode::reverseInclineLaunchedShuttle + && mode != RideMode::poweredLaunchPassthrough) + { + return false; + } + + // Must have no more than one vehicle and one station + if (numTrains > 1 || numStations > 1) + return false; + + return true; + } + + bool Ride::supportsStatus(RideStatus s) const + { + const auto& rtd = getRideTypeDescriptor(); + + switch (s) + { + case RideStatus::closed: + case RideStatus::open: + return true; + case RideStatus::simulating: + return (!rtd.flags.has(RtdFlag::noTestMode) && rtd.flags.has(RtdFlag::hasTrack)); + case RideStatus::testing: + return !rtd.flags.has(RtdFlag::noTestMode); + case RideStatus::count: // Meaningless but necessary to satisfy -Wswitch + return false; + } + // Unreachable + return false; + } + + bool Ride::hasFailingBrakes() const + { + return flags.has(RideFlag::brokenDown) && breakdownReasonPending == Breakdown::brakesFailure + && mechanicStatus != MechanicStatus::hasFixedStationBrakes; + } #pragma region Initialisation functions -/** - * - * rct2: 0x006ACA89 - */ -void RideInitAll() -{ - auto& gameState = getGameState(); - std::for_each(std::begin(gameState.rides), std::end(gameState.rides), RideReset); - gameState.ridesEndOfUsedRange = 0; -} - -/** - * - * rct2: 0x006B7A38 - */ -void ResetAllRideBuildDates() -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) + /** + * + * rct2: 0x006ACA89 + */ + void RideInitAll() { - ride.buildDate -= GetDate().GetMonthsElapsed(); + auto& gameState = getGameState(); + std::for_each(std::begin(gameState.rides), std::end(gameState.rides), RideReset); + gameState.ridesEndOfUsedRange = 0; + } + + /** + * + * rct2: 0x006B7A38 + */ + void ResetAllRideBuildDates() + { + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + { + ride.buildDate -= GetDate().GetMonthsElapsed(); + } } -} #pragma endregion @@ -681,1479 +683,1497 @@ void ResetAllRideBuildDates() #pragma region Update functions -/** - * - * rct2: 0x006ABE4C - */ -void Ride::updateAll() -{ - PROFILED_FUNCTION(); - - auto& gameState = getGameState(); - - // Remove all rides if scenario editor - if (gLegacyScene == LegacyScene::scenarioEditor) + /** + * + * rct2: 0x006ABE4C + */ + void Ride::updateAll() { - switch (getGameState().editorStep) + PROFILED_FUNCTION(); + + auto& gameState = getGameState(); + + // Remove all rides if scenario editor + if (gLegacyScene == LegacyScene::scenarioEditor) { - case Editor::Step::objectSelection: - case Editor::Step::landscapeEditor: - case Editor::Step::inventionsListSetUp: + switch (getGameState().editorStep) { - for (auto& ride : RideManager(gameState)) - ride.remove(); - break; + case Editor::Step::objectSelection: + case Editor::Step::landscapeEditor: + case Editor::Step::inventionsListSetUp: + { + for (auto& ride : RideManager(gameState)) + ride.remove(); + break; + } + case Editor::Step::optionsSelection: + case Editor::Step::objectiveSelection: + case Editor::Step::scenarioDetails: + case Editor::Step::saveScenario: + case Editor::Step::rollerCoasterDesigner: + case Editor::Step::designsManager: + case Editor::Step::invalid: + break; } - case Editor::Step::optionsSelection: - case Editor::Step::objectiveSelection: - case Editor::Step::scenarioDetails: - case Editor::Step::saveScenario: - case Editor::Step::rollerCoasterDesigner: - case Editor::Step::designsManager: - case Editor::Step::invalid: - break; + return; } - return; + + WindowUpdateViewportRideMusic(); + + // Update rides + for (auto& ride : RideManager(gameState)) + ride.update(); + + RideAudio::UpdateMusicChannels(); } - WindowUpdateViewportRideMusic(); - - // Update rides - for (auto& ride : RideManager(gameState)) - ride.update(); - - RideAudio::UpdateMusicChannels(); -} - -std::unique_ptr Ride::saveToTrackDesign(TrackDesignState& tds) const -{ - if (!flags.has(RideFlag::tested)) + std::unique_ptr Ride::saveToTrackDesign(TrackDesignState& tds) const { - ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, kStringIdNone, {}); - return nullptr; - } - - if (!RideHasRatings(*this)) - { - ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, kStringIdNone, {}); - return nullptr; - } - - auto td = std::make_unique(); - auto errMessage = td->CreateTrackDesign(tds, *this); - if (!errMessage.Successful) - { - ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, errMessage.Message, {}); - return nullptr; - } - if (errMessage.HasMessage()) - { - ContextShowError(errMessage.Message, kStringIdEmpty, {}); - } - - return td; -} - -RideStation& Ride::getStation(StationIndex stationIndex) -{ - return stations[stationIndex.ToUnderlying()]; -} - -StationIndex::UnderlyingType Ride::getStationNumber(StationIndex in) const -{ - StationIndex::UnderlyingType nullStationsSeen{ 0 }; - for (size_t i = 0; i < in.ToUnderlying(); i++) - { - if (stations[i].Start.IsNull()) + if (!flags.has(RideFlag::tested)) { - nullStationsSeen++; + ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, kStringIdNone, {}); + return nullptr; } - } - return in.ToUnderlying() - nullStationsSeen + 1; -} - -const RideStation& Ride::getStation(StationIndex stationIndex) const -{ - return stations[stationIndex.ToUnderlying()]; -} - -std::span Ride::getStations() -{ - return stations; -} - -std::span Ride::getStations() const -{ - return stations; -} - -StationIndex Ride::getStationIndex(const RideStation* station) const -{ - auto distance = std::distance(stations.data(), station); - Guard::Assert(distance >= 0 && distance < int32_t(std::size(stations))); - return StationIndex::FromUnderlying(distance); -} - -/** - * - * rct2: 0x006ABE73 - */ -void Ride::update() -{ - if (vehicleChangeTimeout != 0) - vehicleChangeTimeout--; - - RideMusicUpdate(*this); - - // Update stations - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::maze) - for (StationIndex::UnderlyingType i = 0; i < Limits::kMaxStationsPerRide; i++) - RideUpdateStation(*this, StationIndex::FromUnderlying(i)); - - // Update financial statistics - numCustomersTimeout++; - - if (numCustomersTimeout >= 960) - { - // This is meant to update about every 30 seconds - numCustomersTimeout = 0; - - // Shift number of customers history, start of the array is the most recent one - for (int32_t i = Limits::kCustomerHistorySize - 1; i > 0; i--) + if (!RideHasRatings(*this)) { - numCustomers[i] = numCustomers[i - 1]; + ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, kStringIdNone, {}); + return nullptr; } - numCustomers[0] = curNumCustomers; - curNumCustomers = 0; - windowInvalidateFlags.set(RideInvalidateFlag::customers); + auto td = std::make_unique(); + auto errMessage = td->CreateTrackDesign(tds, *this); + if (!errMessage.Successful) + { + ContextShowError(STR_CANT_SAVE_TRACK_DESIGN, errMessage.Message, {}); + return nullptr; + } + if (errMessage.HasMessage()) + { + ContextShowError(errMessage.Message, kStringIdEmpty, {}); + } - incomePerHour = calculateIncomePerHour(); - windowInvalidateFlags.set(RideInvalidateFlag::income); - - if (upkeepCost != kMoney64Undefined) - profit = incomePerHour - (upkeepCost * 16); + return td; } - // Ride specific updates - if (rtd.RideUpdate != nullptr) - rtd.RideUpdate(*this); - - RideBreakdownUpdate(*this); - - // Various things include news messages - if (flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection)) + RideStation& Ride::getStation(StationIndex stationIndex) { - // Breakdown updates originally were performed when (id == (gCurrentTicks / 2) & 0xFF) - // with the increased MAX_RIDES the update is tied to the first byte of the id this allows - // for identical balance with vanilla. - const auto updatingRideByte = static_cast((getGameState().currentTicks / 2) & 0xFF); - if (updatingRideByte == static_cast(id.ToUnderlying())) - RideBreakdownStatusUpdate(*this); + return stations[stationIndex.ToUnderlying()]; } - RideInspectionUpdate(*this); - - // If ride is simulating but crashed, reset the vehicles - if (status == RideStatus::simulating && flags.has(RideFlag::crashed)) + StationIndex::UnderlyingType Ride::getStationNumber(StationIndex in) const { - // We require this to execute right away during the simulation, always ignore network and queue. - auto gameAction = GameActions::RideSetStatusAction(id, RideStatus::simulating); - GameActions::ExecuteNested(&gameAction, getGameState()); + StationIndex::UnderlyingType nullStationsSeen{ 0 }; + for (size_t i = 0; i < in.ToUnderlying(); i++) + { + if (stations[i].Start.IsNull()) + { + nullStationsSeen++; + } + } + + return in.ToUnderlying() - nullStationsSeen + 1; } -} -/** - * - * rct2: 0x006AC489 - */ -void updateChairlift(Ride& ride) -{ - if (!ride.flags.has(RideFlag::onTrack)) - return; - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed) - && ride.breakdownReasonPending == Breakdown::safetyCutOut) - return; - - uint16_t oldChairliftBullwheelRotation = ride.chairliftBullwheelRotation >> 14; - ride.chairliftBullwheelRotation += ride.speed * 2048; - if (oldChairliftBullwheelRotation == ride.speed / 8) - return; - - auto bullwheelLoc = ride.chairliftBullwheelLocation[0].ToCoordsXYZ(); - MapInvalidateTileZoom1({ bullwheelLoc, bullwheelLoc.z, bullwheelLoc.z + (4 * kCoordsZStep) }); - - bullwheelLoc = ride.chairliftBullwheelLocation[1].ToCoordsXYZ(); - MapInvalidateTileZoom1({ bullwheelLoc, bullwheelLoc.z, bullwheelLoc.z + (4 * kCoordsZStep) }); -} - -/** - * - * rct2: 0x0069A3A2 - * edi: ride (in code as bytes offset from start of rides list) - * bl: happiness - */ -void Ride::updateSatisfaction(const uint8_t happiness) -{ - satisfactionNext += happiness; - satisfactionTimeout++; - if (satisfactionTimeout >= 20) + const RideStation& Ride::getStation(StationIndex stationIndex) const { - satisfaction = satisfactionNext >> 2; - satisfactionNext = 0; - satisfactionTimeout = 0; + return stations[stationIndex.ToUnderlying()]; + } + + std::span Ride::getStations() + { + return stations; + } + + std::span Ride::getStations() const + { + return stations; + } + + StationIndex Ride::getStationIndex(const RideStation* station) const + { + auto distance = std::distance(stations.data(), station); + Guard::Assert(distance >= 0 && distance < int32_t(std::size(stations))); + return StationIndex::FromUnderlying(distance); + } + + /** + * + * rct2: 0x006ABE73 + */ + void Ride::update() + { + if (vehicleChangeTimeout != 0) + vehicleChangeTimeout--; + + RideMusicUpdate(*this); + + // Update stations + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::maze) + for (StationIndex::UnderlyingType i = 0; i < Limits::kMaxStationsPerRide; i++) + RideUpdateStation(*this, StationIndex::FromUnderlying(i)); + + // Update financial statistics + numCustomersTimeout++; + + if (numCustomersTimeout >= 960) + { + // This is meant to update about every 30 seconds + numCustomersTimeout = 0; + + // Shift number of customers history, start of the array is the most recent one + for (int32_t i = Limits::kCustomerHistorySize - 1; i > 0; i--) + { + numCustomers[i] = numCustomers[i - 1]; + } + numCustomers[0] = curNumCustomers; + + curNumCustomers = 0; + windowInvalidateFlags.set(RideInvalidateFlag::customers); + + incomePerHour = calculateIncomePerHour(); + windowInvalidateFlags.set(RideInvalidateFlag::income); + + if (upkeepCost != kMoney64Undefined) + profit = incomePerHour - (upkeepCost * 16); + } + + // Ride specific updates + if (rtd.RideUpdate != nullptr) + rtd.RideUpdate(*this); + + RideBreakdownUpdate(*this); + + // Various things include news messages + if (flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection)) + { + // Breakdown updates originally were performed when (id == (gCurrentTicks / 2) & 0xFF) + // with the increased MAX_RIDES the update is tied to the first byte of the id this allows + // for identical balance with vanilla. + const auto updatingRideByte = static_cast((getGameState().currentTicks / 2) & 0xFF); + if (updatingRideByte == static_cast(id.ToUnderlying())) + RideBreakdownStatusUpdate(*this); + } + + RideInspectionUpdate(*this); + + // If ride is simulating but crashed, reset the vehicles + if (status == RideStatus::simulating && flags.has(RideFlag::crashed)) + { + // We require this to execute right away during the simulation, always ignore network and queue. + auto gameAction = GameActions::RideSetStatusAction(id, RideStatus::simulating); + GameActions::ExecuteNested(&gameAction, getGameState()); + } + } + + /** + * + * rct2: 0x006AC489 + */ + void updateChairlift(Ride& ride) + { + if (!ride.flags.has(RideFlag::onTrack)) + return; + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed) + && ride.breakdownReasonPending == Breakdown::safetyCutOut) + return; + + uint16_t oldChairliftBullwheelRotation = ride.chairliftBullwheelRotation >> 14; + ride.chairliftBullwheelRotation += ride.speed * 2048; + if (oldChairliftBullwheelRotation == ride.speed / 8) + return; + + auto bullwheelLoc = ride.chairliftBullwheelLocation[0].ToCoordsXYZ(); + MapInvalidateTileZoom1({ bullwheelLoc, bullwheelLoc.z, bullwheelLoc.z + (4 * kCoordsZStep) }); + + bullwheelLoc = ride.chairliftBullwheelLocation[1].ToCoordsXYZ(); + MapInvalidateTileZoom1({ bullwheelLoc, bullwheelLoc.z, bullwheelLoc.z + (4 * kCoordsZStep) }); + } + + /** + * + * rct2: 0x0069A3A2 + * edi: ride (in code as bytes offset from start of rides list) + * bl: happiness + */ + void Ride::updateSatisfaction(const uint8_t happiness) + { + satisfactionNext += happiness; + satisfactionTimeout++; + if (satisfactionTimeout >= 20) + { + satisfaction = satisfactionNext >> 2; + satisfactionNext = 0; + satisfactionTimeout = 0; + windowInvalidateFlags.set(RideInvalidateFlag::customers); + } + } + + /** + * + * rct2: 0x0069A3D7 + * Updates the ride popularity + * edi : ride + * bl : pop_amount + * pop_amount can be zero if peep visited but did not purchase. + */ + void Ride::updatePopularity(const uint8_t pop_amount) + { + popularityNext += pop_amount; + popularityTimeout++; + if (popularityTimeout < 25) + return; + + popularity = popularityNext; + popularityNext = 0; + popularityTimeout = 0; windowInvalidateFlags.set(RideInvalidateFlag::customers); } -} -/** - * - * rct2: 0x0069A3D7 - * Updates the ride popularity - * edi : ride - * bl : pop_amount - * pop_amount can be zero if peep visited but did not purchase. - */ -void Ride::updatePopularity(const uint8_t pop_amount) -{ - popularityNext += pop_amount; - popularityTimeout++; - if (popularityTimeout < 25) - return; - - popularity = popularityNext; - popularityNext = 0; - popularityTimeout = 0; - windowInvalidateFlags.set(RideInvalidateFlag::customers); -} - -/** rct2: 0x0098DDB8, 0x0098DDBA */ -static constexpr CoordsXY ride_spiral_slide_main_tile_offset[][4] = { - { - { 32, 32 }, - { 0, 32 }, - { 0, 0 }, - { 32, 0 }, - }, - { - { 32, 0 }, - { 0, 0 }, - { 0, -32 }, - { 32, -32 }, - }, - { - { 0, 0 }, - { -32, 0 }, - { -32, -32 }, - { 0, -32 }, - }, - { - { 0, 0 }, - { 0, 32 }, - { -32, 32 }, - { -32, 0 }, - }, -}; - -/** - * - * rct2: 0x006AC545 - */ - -void updateSpiralSlide(Ride& ride) -{ - if (getGameState().currentTicks & 3) - return; - if (!ride.slideInUse) - return; - - ride.spiralSlideProgress++; - if (ride.spiralSlideProgress >= 48) - { - ride.slideInUse = 0; - - auto* peep = getGameState().entities.GetEntity(ride.slidePeep); - if (peep != nullptr) + /** rct2: 0x0098DDB8, 0x0098DDBA */ + static constexpr CoordsXY ride_spiral_slide_main_tile_offset[][4] = { { - peep->spiralSlideSubstate = PeepSpiralSlideSubState::finishedSliding; + { 32, 32 }, + { 0, 32 }, + { 0, 0 }, + { 32, 0 }, + }, + { + { 32, 0 }, + { 0, 0 }, + { 0, -32 }, + { 32, -32 }, + }, + { + { 0, 0 }, + { -32, 0 }, + { -32, -32 }, + { 0, -32 }, + }, + { + { 0, 0 }, + { 0, 32 }, + { -32, 32 }, + { -32, 0 }, + }, + }; + + /** + * + * rct2: 0x006AC545 + */ + + void updateSpiralSlide(Ride& ride) + { + if (getGameState().currentTicks & 3) + return; + if (!ride.slideInUse) + return; + + ride.spiralSlideProgress++; + if (ride.spiralSlideProgress >= 48) + { + ride.slideInUse = 0; + + auto* peep = getGameState().entities.GetEntity(ride.slidePeep); + if (peep != nullptr) + { + peep->spiralSlideSubstate = PeepSpiralSlideSubState::finishedSliding; + } + } + + const uint8_t current_rotation = GetCurrentRotation(); + // Invalidate something related to station start + for (int32_t i = 0; i < Limits::kMaxStationsPerRide; i++) + { + if (ride.stations[i].Start.IsNull()) + continue; + + auto startLoc = ride.stations[i].Start; + + TileElement* tileElement = RideGetStationStartTrackElement(ride, StationIndex::FromUnderlying(i)); + if (tileElement == nullptr) + continue; + + int32_t rotation = tileElement->getDirection(); + startLoc += ride_spiral_slide_main_tile_offset[rotation][current_rotation]; + + MapInvalidateTileZoom0({ startLoc, tileElement->getBaseZ(), tileElement->getClearanceZ() }); } } - const uint8_t current_rotation = GetCurrentRotation(); - // Invalidate something related to station start - for (int32_t i = 0; i < Limits::kMaxStationsPerRide; i++) - { - if (ride.stations[i].Start.IsNull()) - continue; - - auto startLoc = ride.stations[i].Start; - - TileElement* tileElement = RideGetStationStartTrackElement(ride, StationIndex::FromUnderlying(i)); - if (tileElement == nullptr) - continue; - - int32_t rotation = tileElement->getDirection(); - startLoc += ride_spiral_slide_main_tile_offset[rotation][current_rotation]; - - MapInvalidateTileZoom0({ startLoc, tileElement->getBaseZ(), tileElement->getClearanceZ() }); - } -} - #pragma endregion #pragma region Breakdown and inspection functions -static uint8_t _breakdownProblemProbabilities[] = { - 25, // Breakdown::safetyCutOut - 12, // Breakdown::restraintsStuckClosed - 10, // Breakdown::restraintsStuckOpen - 13, // Breakdown::doorsStuckClosed - 10, // Breakdown::doorsStuckOpen - 6, // Breakdown::vehicleMalfunction - 0, // Breakdown::brakesFailure - 3, // Breakdown::controlFailure -}; + static uint8_t _breakdownProblemProbabilities[] = { + 25, // Breakdown::safetyCutOut + 12, // Breakdown::restraintsStuckClosed + 10, // Breakdown::restraintsStuckOpen + 13, // Breakdown::doorsStuckClosed + 10, // Breakdown::doorsStuckOpen + 6, // Breakdown::vehicleMalfunction + 0, // Breakdown::brakesFailure + 3, // Breakdown::controlFailure + }; -/** - * - * rct2: 0x006AC7C2 - */ -static void RideInspectionUpdate(Ride& ride) -{ - if (getGameState().currentTicks & 2047) - return; - if (gLegacyScene == LegacyScene::trackDesigner) - return; - - ride.lastInspection = AddClamp(ride.lastInspection, 1); - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - - int32_t inspectionIntervalMinutes = RideInspectionInterval[EnumValue(ride.inspectionInterval)]; - // An inspection interval of 0 minutes means the ride is set to never be inspected. - if (inspectionIntervalMinutes == 0) + /** + * + * rct2: 0x006AC7C2 + */ + static void RideInspectionUpdate(Ride& ride) { - ride.flags.unset(RideFlag::dueInspection); - return; - } - - if (ride.getRideTypeDescriptor().availableBreakdowns.isEmpty()) - return; - - if (inspectionIntervalMinutes > ride.lastInspection) - return; - - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection, RideFlag::crashed)) - return; - - // Inspect the first station that has an exit - ride.flags.set(RideFlag::dueInspection); - ride.mechanicStatus = MechanicStatus::calling; - - auto stationIndex = RideGetFirstValidStationExit(ride); - ride.inspectionStation = (!stationIndex.IsNull()) ? stationIndex : StationIndex::FromUnderlying(0); -} - -static int32_t getAgePenalty(const Ride& ride) -{ - auto years = DateGetYear(ride.getAge()); - switch (years) - { - case 0: - return 0; - case 1: - return ride.unreliabilityFactor / 8; - case 2: - return ride.unreliabilityFactor / 4; - case 3: - case 4: - return ride.unreliabilityFactor / 2; - case 5: - case 6: - case 7: - return ride.unreliabilityFactor; - default: - return ride.unreliabilityFactor * 2; - } -} - -/** - * - * rct2: 0x006AC622 - */ -static void RideBreakdownUpdate(Ride& ride) -{ - auto& gameState = getGameState(); - const auto currentTicks = gameState.currentTicks; - if (currentTicks & 255) - return; - - if (gLegacyScene == LegacyScene::trackDesigner) - return; - - if (ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) - ride.downtimeHistory[0]++; - - if (!(currentTicks & 8191)) - { - int32_t totalDowntime = 0; - - for (int32_t i = 0; i < Limits::kDowntimeHistorySize; i++) - { - totalDowntime += ride.downtimeHistory[i]; - } - - ride.downtime = std::min(totalDowntime / 2, 100); - - for (int32_t i = Limits::kDowntimeHistorySize - 1; i > 0; i--) - { - ride.downtimeHistory[i] = ride.downtimeHistory[i - 1]; - } - ride.downtimeHistory[0] = 0; + if (getGameState().currentTicks & 2047) + return; + if (gLegacyScene == LegacyScene::trackDesigner) + return; + ride.lastInspection = AddClamp(ride.lastInspection, 1); ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - } - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed)) - return; - if (ride.status == RideStatus::closed || ride.status == RideStatus::simulating) - return; - - if (!ride.canBreakDown()) - { - ride.reliability = kRideInitialReliability; - return; - } - - // Calculate breakdown probability? - int32_t unreliabilityAccumulator = ride.unreliabilityFactor + getAgePenalty(ride); - ride.reliability = static_cast(std::max(0, (ride.reliability - unreliabilityAccumulator))); - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - - // Random probability of a breakdown. Roughly this is 1 in - // - // (25000 - reliability) / 3 000 000 - // - // a 0.8% chance, less the breakdown factor which accumulates as the game - // continues. - if ((ride.reliability == 0 - || static_cast(ScenarioRand() & 0x2FFFFF) <= 1u + kRideInitialReliability - ride.reliability) - && !gameState.cheats.disableAllBreakdowns) - { - auto breakdownReason = RideGetNewBreakdownProblem(ride); - if (breakdownReason != Breakdown::none) - RidePrepareBreakdown(ride, breakdownReason); - } -} - -/** - * - * rct2: 0x006B7294 - */ -static Breakdown RideGetNewBreakdownProblem(const Ride& ride) -{ - // Brake failure is more likely when it's raining or heavily snowing (HeavySnow and Blizzard) - _breakdownProblemProbabilities[EnumValue(Breakdown::brakesFailure)] = Weather::isPrecipitating() ? 20 : 3; - - if (!ride.canBreakDown()) - return Breakdown::none; - - auto availableBreakdownProblems = ride.getRideTypeDescriptor().availableBreakdowns; - - // Calculate the total probability range for all possible breakdown problems - int32_t totalProbability = 0; - for (Breakdown breakdown : kAllBreakdownTypes) - { - if (availableBreakdownProblems.has(breakdown)) - totalProbability += _breakdownProblemProbabilities[EnumValue(breakdown)]; - } - - if (totalProbability == 0) - return Breakdown::none; - - // Choose a random number within this range - int32_t randomProbability = ScenarioRand() % totalProbability; - - // Find which problem range the random number lies - auto breakdownProblem = Breakdown::none; - for (Breakdown breakdown : kAllBreakdownTypes) - { - if (availableBreakdownProblems.has(breakdown)) + int32_t inspectionIntervalMinutes = RideInspectionInterval[EnumValue(ride.inspectionInterval)]; + // An inspection interval of 0 minutes means the ride is set to never be inspected. + if (inspectionIntervalMinutes == 0) { - breakdownProblem = breakdown; - randomProbability -= _breakdownProblemProbabilities[EnumValue(breakdown)]; + ride.flags.unset(RideFlag::dueInspection); + return; } - if (randomProbability < 0) - break; + + if (ride.getRideTypeDescriptor().availableBreakdowns.isEmpty()) + return; + + if (inspectionIntervalMinutes > ride.lastInspection) + return; + + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection, RideFlag::crashed)) + return; + + // Inspect the first station that has an exit + ride.flags.set(RideFlag::dueInspection); + ride.mechanicStatus = MechanicStatus::calling; + + auto stationIndex = RideGetFirstValidStationExit(ride); + ride.inspectionStation = (!stationIndex.IsNull()) ? stationIndex : StationIndex::FromUnderlying(0); } - if (breakdownProblem != Breakdown::brakesFailure) - return breakdownProblem; - - // Brakes failure can not happen if block brakes are used (so long as there is more than one vehicle) - // However if this is the case, brake failure should be taken out the equation, otherwise block brake - // rides have a lower probability to break down due to a random implementation reason. - if (ride.isBlockSectioned()) - if (ride.numTrains != 1) - return Breakdown::none; - - // If brakes failure is disabled, also take it out of the equation (see above comment why) - if (getGameState().cheats.disableBrakesFailure) - return Breakdown::none; - - auto monthsOld = ride.getAge(); - if (monthsOld < 16 || ride.reliabilityPercentage > 50) - return Breakdown::none; - - return Breakdown::brakesFailure; -} - -bool Ride::canBreakDown() const -{ - if (getRideTypeDescriptor().availableBreakdowns.isEmpty()) + static int32_t getAgePenalty(const Ride& ride) { - return false; + auto years = DateGetYear(ride.getAge()); + switch (years) + { + case 0: + return 0; + case 1: + return ride.unreliabilityFactor / 8; + case 2: + return ride.unreliabilityFactor / 4; + case 3: + case 4: + return ride.unreliabilityFactor / 2; + case 5: + case 6: + case 7: + return ride.unreliabilityFactor; + default: + return ride.unreliabilityFactor * 2; + } } - const auto* entry = getRideEntry(); - return entry != nullptr && !entry->flags.has(RideEntryFlag::cannotBreakDown); -} - -static void ChooseRandomTrainToBreakdownSafe(Ride& ride) -{ - // Prevent integer division by zero in case of hacked ride. - if (ride.numTrains == 0) - return; - - ride.brokenTrain = ScenarioRand() % ride.numTrains; - - // Prevent crash caused by accessing SPRITE_INDEX_NULL on hacked rides. - // This should probably be cleaned up on import instead. - while (ride.vehicles[ride.brokenTrain].IsNull() && ride.brokenTrain != 0) + /** + * + * rct2: 0x006AC622 + */ + static void RideBreakdownUpdate(Ride& ride) { - --ride.brokenTrain; - } -} + auto& gameState = getGameState(); + const auto currentTicks = gameState.currentTicks; + if (currentTicks & 255) + return; -/** - * - * rct2: 0x006B7348 - */ -void RidePrepareBreakdown(Ride& ride, Breakdown breakdownReason) -{ - StationIndex i; - Vehicle* vehicle; + if (gLegacyScene == LegacyScene::trackDesigner) + return; - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed)) - return; + if (ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) + ride.downtimeHistory[0]++; - ride.flags.set(RideFlag::breakdownPending); + if (!(currentTicks & 8191)) + { + int32_t totalDowntime = 0; - ride.breakdownReasonPending = breakdownReason; - ride.breakdownSoundModifier = 0; - ride.notFixedTimeout = 0; - ride.inspectionStation = StationIndex::FromUnderlying(0); // ensure set to something. - - switch (breakdownReason) - { - case Breakdown::safetyCutOut: - case Breakdown::controlFailure: - // Inspect first station with an exit - i = RideGetFirstValidStationExit(ride); - if (!i.IsNull()) + for (int32_t i = 0; i < Limits::kDowntimeHistorySize; i++) { - ride.inspectionStation = i; + totalDowntime += ride.downtimeHistory[i]; } - break; - case Breakdown::restraintsStuckClosed: - case Breakdown::restraintsStuckOpen: - case Breakdown::doorsStuckClosed: - case Breakdown::doorsStuckOpen: - // Choose a random train and car - ChooseRandomTrainToBreakdownSafe(ride); - if (ride.numCarsPerTrain != 0) - { - ride.brokenCar = ScenarioRand() % ride.numCarsPerTrain; + ride.downtime = std::min(totalDowntime / 2, 100); - // Set flag on broken car + for (int32_t i = Limits::kDowntimeHistorySize - 1; i > 0; i--) + { + ride.downtimeHistory[i] = ride.downtimeHistory[i - 1]; + } + ride.downtimeHistory[0] = 0; + + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + } + + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed)) + return; + if (ride.status == RideStatus::closed || ride.status == RideStatus::simulating) + return; + + if (!ride.canBreakDown()) + { + ride.reliability = kRideInitialReliability; + return; + } + + // Calculate breakdown probability? + int32_t unreliabilityAccumulator = ride.unreliabilityFactor + getAgePenalty(ride); + ride.reliability = static_cast(std::max(0, (ride.reliability - unreliabilityAccumulator))); + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + + // Random probability of a breakdown. Roughly this is 1 in + // + // (25000 - reliability) / 3 000 000 + // + // a 0.8% chance, less the breakdown factor which accumulates as the game + // continues. + if ((ride.reliability == 0 + || static_cast(ScenarioRand() & 0x2FFFFF) <= 1u + kRideInitialReliability - ride.reliability) + && !gameState.cheats.disableAllBreakdowns) + { + auto breakdownReason = RideGetNewBreakdownProblem(ride); + if (breakdownReason != Breakdown::none) + RidePrepareBreakdown(ride, breakdownReason); + } + } + + /** + * + * rct2: 0x006B7294 + */ + static Breakdown RideGetNewBreakdownProblem(const Ride& ride) + { + // Brake failure is more likely when it's raining or heavily snowing (HeavySnow and Blizzard) + _breakdownProblemProbabilities[EnumValue(Breakdown::brakesFailure)] = Weather::isPrecipitating() ? 20 : 3; + + if (!ride.canBreakDown()) + return Breakdown::none; + + auto availableBreakdownProblems = ride.getRideTypeDescriptor().availableBreakdowns; + + // Calculate the total probability range for all possible breakdown problems + int32_t totalProbability = 0; + for (Breakdown breakdown : kAllBreakdownTypes) + { + if (availableBreakdownProblems.has(breakdown)) + totalProbability += _breakdownProblemProbabilities[EnumValue(breakdown)]; + } + + if (totalProbability == 0) + return Breakdown::none; + + // Choose a random number within this range + int32_t randomProbability = ScenarioRand() % totalProbability; + + // Find which problem range the random number lies + auto breakdownProblem = Breakdown::none; + for (Breakdown breakdown : kAllBreakdownTypes) + { + if (availableBreakdownProblems.has(breakdown)) + { + breakdownProblem = breakdown; + randomProbability -= _breakdownProblemProbabilities[EnumValue(breakdown)]; + } + if (randomProbability < 0) + break; + } + + if (breakdownProblem != Breakdown::brakesFailure) + return breakdownProblem; + + // Brakes failure can not happen if block brakes are used (so long as there is more than one vehicle) + // However if this is the case, brake failure should be taken out the equation, otherwise block brake + // rides have a lower probability to break down due to a random implementation reason. + if (ride.isBlockSectioned()) + if (ride.numTrains != 1) + return Breakdown::none; + + // If brakes failure is disabled, also take it out of the equation (see above comment why) + if (getGameState().cheats.disableBrakesFailure) + return Breakdown::none; + + auto monthsOld = ride.getAge(); + if (monthsOld < 16 || ride.reliabilityPercentage > 50) + return Breakdown::none; + + return Breakdown::brakesFailure; + } + + bool Ride::canBreakDown() const + { + if (getRideTypeDescriptor().availableBreakdowns.isEmpty()) + { + return false; + } + + const auto* entry = getRideEntry(); + return entry != nullptr && !entry->flags.has(RideEntryFlag::cannotBreakDown); + } + + static void ChooseRandomTrainToBreakdownSafe(Ride& ride) + { + // Prevent integer division by zero in case of hacked ride. + if (ride.numTrains == 0) + return; + + ride.brokenTrain = ScenarioRand() % ride.numTrains; + + // Prevent crash caused by accessing SPRITE_INDEX_NULL on hacked rides. + // This should probably be cleaned up on import instead. + while (ride.vehicles[ride.brokenTrain].IsNull() && ride.brokenTrain != 0) + { + --ride.brokenTrain; + } + } + + /** + * + * rct2: 0x006B7348 + */ + void RidePrepareBreakdown(Ride& ride, Breakdown breakdownReason) + { + StationIndex i; + Vehicle* vehicle; + + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::crashed)) + return; + + ride.flags.set(RideFlag::breakdownPending); + + ride.breakdownReasonPending = breakdownReason; + ride.breakdownSoundModifier = 0; + ride.notFixedTimeout = 0; + ride.inspectionStation = StationIndex::FromUnderlying(0); // ensure set to something. + + switch (breakdownReason) + { + case Breakdown::safetyCutOut: + case Breakdown::controlFailure: + // Inspect first station with an exit + i = RideGetFirstValidStationExit(ride); + if (!i.IsNull()) + { + ride.inspectionStation = i; + } + + break; + case Breakdown::restraintsStuckClosed: + case Breakdown::restraintsStuckOpen: + case Breakdown::doorsStuckClosed: + case Breakdown::doorsStuckOpen: + // Choose a random train and car + ChooseRandomTrainToBreakdownSafe(ride); + if (ride.numCarsPerTrain != 0) + { + ride.brokenCar = ScenarioRand() % ride.numCarsPerTrain; + + // Set flag on broken car + vehicle = getGameState().entities.GetEntity(ride.vehicles[ride.brokenTrain]); + if (vehicle != nullptr) + { + vehicle = vehicle->GetCar(ride.brokenCar); + } + if (vehicle != nullptr) + { + vehicle->flags.set(VehicleFlag::carIsBroken); + } + } + break; + case Breakdown::vehicleMalfunction: + // Choose a random train + ChooseRandomTrainToBreakdownSafe(ride); + ride.brokenCar = 0; + + // Set flag on broken train, first car vehicle = getGameState().entities.GetEntity(ride.vehicles[ride.brokenTrain]); if (vehicle != nullptr) { - vehicle = vehicle->GetCar(ride.brokenCar); + vehicle->flags.set(VehicleFlag::trainIsBroken); } - if (vehicle != nullptr) + break; + case Breakdown::brakesFailure: + // Original code generates a random number but does not use it + // Unsure if this was supposed to choose a random station (or random station with an exit) + i = RideGetFirstValidStationExit(ride); + if (!i.IsNull()) { - vehicle->flags.set(VehicleFlag::carIsBroken); + ride.inspectionStation = i; + } + break; + default: + break; + } +#ifdef ENABLE_SCRIPTING + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + if (hookEngine.HasSubscriptions(HookType::rideBreakDown)) + { + auto ctx = GetContext()->GetScriptEngine().GetContext(); + JSValue obj = JS_NewObject(ctx); + + JS_SetPropertyStr(ctx, obj, "rideId", JS_NewInt32(ctx, ride.id.ToUnderlying())); + + auto it = kBreakdownMap.find(breakdownReason); + if (it != kBreakdownMap.end()) + JS_SetPropertyStr(ctx, obj, "breakdownReason", JS_NewString(ctx, it->first.data())); + else + JS_SetPropertyStr(ctx, obj, "breakdownReason", JS_NewString(ctx, "none")); + + hookEngine.Call(HookType::rideBreakDown, obj, true); + } +#endif + } + + /** + * + * rct2: 0x006B74FA + */ + void RideBreakdownAddNewsItem(const Ride& ride) + { + if (Config::Get().notifications.rideBrokenDown) + { + Formatter ft; + ride.formatNameTo(ft); + News::AddItemToQueue(News::ItemType::ride, STR_RIDE_IS_BROKEN_DOWN, ride.id.ToUnderlying(), ft); + } + } + + /** + * + * rct2: 0x006B75C8 + */ + static void RideBreakdownStatusUpdate(Ride& ride) + { + // Warn player if ride hasn't been fixed for ages + if (ride.flags.has(RideFlag::brokenDown)) + { + ride.notFixedTimeout++; + // When there has been a full 255 timeout ticks this + // will force timeout ticks to keep issuing news every + // 16 ticks. Note there is no reason to do this. + if (ride.notFixedTimeout == 0) + ride.notFixedTimeout -= 16; + + if (!(ride.notFixedTimeout & 15) && ride.mechanicStatus != MechanicStatus::fixing + && ride.mechanicStatus != MechanicStatus::hasFixedStationBrakes) + { + if (Config::Get().notifications.rideWarnings) + { + Formatter ft; + ride.formatNameTo(ft); + News::AddItemToQueue(News::ItemType::ride, STR_RIDE_IS_STILL_NOT_FIXED, ride.id.ToUnderlying(), ft); } } - break; - case Breakdown::vehicleMalfunction: - // Choose a random train - ChooseRandomTrainToBreakdownSafe(ride); - ride.brokenCar = 0; + } - // Set flag on broken train, first car - vehicle = getGameState().entities.GetEntity(ride.vehicles[ride.brokenTrain]); - if (vehicle != nullptr) - { - vehicle->flags.set(VehicleFlag::trainIsBroken); - } - break; - case Breakdown::brakesFailure: - // Original code generates a random number but does not use it - // Unsure if this was supposed to choose a random station (or random station with an exit) - i = RideGetFirstValidStationExit(ride); - if (!i.IsNull()) - { - ride.inspectionStation = i; - } - break; - default: - break; + RideMechanicStatusUpdate(ride, ride.mechanicStatus); } -#ifdef ENABLE_SCRIPTING - auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - if (hookEngine.HasSubscriptions(HookType::rideBreakDown)) + + /** + * + * rct2: 0x006B762F + */ + static void RideMechanicStatusUpdate(Ride& ride, MechanicStatus mechanicStatus) { - auto ctx = GetContext()->GetScriptEngine().GetContext(); - JSValue obj = JS_NewObject(ctx); - - JS_SetPropertyStr(ctx, obj, "rideId", JS_NewInt32(ctx, ride.id.ToUnderlying())); - - auto it = kBreakdownMap.find(breakdownReason); - if (it != kBreakdownMap.end()) - JS_SetPropertyStr(ctx, obj, "breakdownReason", JS_NewString(ctx, it->first.data())); - else - JS_SetPropertyStr(ctx, obj, "breakdownReason", JS_NewString(ctx, "none")); - - hookEngine.Call(HookType::rideBreakDown, obj, true); - } -#endif -} - -/** - * - * rct2: 0x006B74FA - */ -void RideBreakdownAddNewsItem(const Ride& ride) -{ - if (Config::Get().notifications.rideBrokenDown) - { - Formatter ft; - ride.formatNameTo(ft); - News::AddItemToQueue(News::ItemType::ride, STR_RIDE_IS_BROKEN_DOWN, ride.id.ToUnderlying(), ft); - } -} - -/** - * - * rct2: 0x006B75C8 - */ -static void RideBreakdownStatusUpdate(Ride& ride) -{ - // Warn player if ride hasn't been fixed for ages - if (ride.flags.has(RideFlag::brokenDown)) - { - ride.notFixedTimeout++; - // When there has been a full 255 timeout ticks this - // will force timeout ticks to keep issuing news every - // 16 ticks. Note there is no reason to do this. - if (ride.notFixedTimeout == 0) - ride.notFixedTimeout -= 16; - - if (!(ride.notFixedTimeout & 15) && ride.mechanicStatus != MechanicStatus::fixing - && ride.mechanicStatus != MechanicStatus::hasFixedStationBrakes) + // Turn a pending breakdown into a breakdown. + if ((mechanicStatus == MechanicStatus::undefined || mechanicStatus == MechanicStatus::calling + || mechanicStatus == MechanicStatus::heading) + && ride.flags.has(RideFlag::breakdownPending) && !ride.flags.has(RideFlag::brokenDown)) { - if (Config::Get().notifications.rideWarnings) + auto breakdownReason = ride.breakdownReasonPending; + if (breakdownReason == Breakdown::safetyCutOut || breakdownReason == Breakdown::brakesFailure + || breakdownReason == Breakdown::controlFailure) { - Formatter ft; - ride.formatNameTo(ft); - News::AddItemToQueue(News::ItemType::ride, STR_RIDE_IS_STILL_NOT_FIXED, ride.id.ToUnderlying(), ft); + ride.flags.set(RideFlag::brokenDown); + ride.windowInvalidateFlags.set( + RideInvalidateFlag::maintenance, RideInvalidateFlag::list, RideInvalidateFlag::main); + ride.breakdownReason = breakdownReason; + RideBreakdownAddNewsItem(ride); } } - } - - RideMechanicStatusUpdate(ride, ride.mechanicStatus); -} - -/** - * - * rct2: 0x006B762F - */ -static void RideMechanicStatusUpdate(Ride& ride, MechanicStatus mechanicStatus) -{ - // Turn a pending breakdown into a breakdown. - if ((mechanicStatus == MechanicStatus::undefined || mechanicStatus == MechanicStatus::calling - || mechanicStatus == MechanicStatus::heading) - && ride.flags.has(RideFlag::breakdownPending) && !ride.flags.has(RideFlag::brokenDown)) - { - auto breakdownReason = ride.breakdownReasonPending; - if (breakdownReason == Breakdown::safetyCutOut || breakdownReason == Breakdown::brakesFailure - || breakdownReason == Breakdown::controlFailure) + switch (mechanicStatus) { - ride.flags.set(RideFlag::brokenDown); - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance, RideInvalidateFlag::list, RideInvalidateFlag::main); - ride.breakdownReason = breakdownReason; - RideBreakdownAddNewsItem(ride); - } - } - switch (mechanicStatus) - { - case MechanicStatus::undefined: - if (ride.flags.has(RideFlag::brokenDown)) + case MechanicStatus::undefined: + if (ride.flags.has(RideFlag::brokenDown)) + { + ride.mechanicStatus = MechanicStatus::calling; + } + break; + case MechanicStatus::calling: + if (ride.getRideTypeDescriptor().availableBreakdowns.isEmpty()) + { + ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection); + break; + } + + RideCallClosestMechanic(ride); + break; + case MechanicStatus::heading: { - ride.mechanicStatus = MechanicStatus::calling; - } - break; - case MechanicStatus::calling: - if (ride.getRideTypeDescriptor().availableBreakdowns.isEmpty()) - { - ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection); + auto mechanic = RideGetMechanic(ride); + bool rideNeedsRepair = ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown); + if (mechanic == nullptr + || (mechanic->State != PeepState::headingToInspection && mechanic->State != PeepState::answering) + || mechanic->CurrentRide != ride.id) + { + ride.mechanicStatus = MechanicStatus::calling; + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + RideMechanicStatusUpdate(ride, MechanicStatus::calling); + } + // if the ride is broken down, but a mechanic was heading for an inspection, update orders to fix + else if (rideNeedsRepair && mechanic->State == PeepState::headingToInspection) + { + // updates orders for mechanic already heading to inspect ride + // forInspection == false means start repair (goes to PeepState::answering) + RideCallMechanic(ride, mechanic, false); + } break; } - - RideCallClosestMechanic(ride); - break; - case MechanicStatus::heading: - { - auto mechanic = RideGetMechanic(ride); - bool rideNeedsRepair = ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown); - if (mechanic == nullptr - || (mechanic->State != PeepState::headingToInspection && mechanic->State != PeepState::answering) - || mechanic->CurrentRide != ride.id) + case MechanicStatus::fixing: { - ride.mechanicStatus = MechanicStatus::calling; - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - RideMechanicStatusUpdate(ride, MechanicStatus::calling); + auto mechanic = RideGetMechanic(ride); + if (mechanic == nullptr + || (mechanic->State != PeepState::headingToInspection && mechanic->State != PeepState::fixing + && mechanic->State != PeepState::inspecting && mechanic->State != PeepState::answering)) + { + ride.mechanicStatus = MechanicStatus::calling; + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + RideMechanicStatusUpdate(ride, MechanicStatus::calling); + } + break; } - // if the ride is broken down, but a mechanic was heading for an inspection, update orders to fix - else if (rideNeedsRepair && mechanic->State == PeepState::headingToInspection) - { - // updates orders for mechanic already heading to inspect ride - // forInspection == false means start repair (goes to PeepState::answering) - RideCallMechanic(ride, mechanic, false); - } - break; + default: + break; } - case MechanicStatus::fixing: - { - auto mechanic = RideGetMechanic(ride); - if (mechanic == nullptr - || (mechanic->State != PeepState::headingToInspection && mechanic->State != PeepState::fixing - && mechanic->State != PeepState::inspecting && mechanic->State != PeepState::answering)) - { - ride.mechanicStatus = MechanicStatus::calling; - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - RideMechanicStatusUpdate(ride, MechanicStatus::calling); - } - break; - } - default: - break; } -} -/** - * - * rct2: 0x006B796C - */ -static void RideCallMechanic(Ride& ride, Peep* mechanic, int32_t forInspection) -{ - mechanic->SetState(forInspection ? PeepState::headingToInspection : PeepState::answering); - mechanic->SubState = 0; - ride.mechanicStatus = MechanicStatus::heading; - ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); - ride.mechanic = mechanic->id; - mechanic->CurrentRide = ride.id; - mechanic->CurrentRideStation = ride.inspectionStation; -} - -/** - * - * rct2: 0x006B76AB - */ -static void RideCallClosestMechanic(Ride& ride) -{ - auto forInspection = !ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown); - auto mechanic = RideFindClosestMechanic(ride, forInspection); - if (mechanic != nullptr) - RideCallMechanic(ride, mechanic, forInspection); -} - -Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection) -{ - const auto stationIndex = ride.inspectionStation.IsNull() ? RideGetFirstValidStationExit(ride) : ride.inspectionStation; - if (stationIndex.IsNull()) - return nullptr; - - // Get either exit position or entrance position if there is no exit - const auto& station = ride.getStation(stationIndex); - TileCoordsXYZD location = station.Exit; - if (location.IsNull()) + /** + * + * rct2: 0x006B796C + */ + static void RideCallMechanic(Ride& ride, Peep* mechanic, int32_t forInspection) { - location = station.Entrance; - if (station.Entrance.IsNull()) + mechanic->SetState(forInspection ? PeepState::headingToInspection : PeepState::answering); + mechanic->SubState = 0; + ride.mechanicStatus = MechanicStatus::heading; + ride.windowInvalidateFlags.set(RideInvalidateFlag::maintenance); + ride.mechanic = mechanic->id; + mechanic->CurrentRide = ride.id; + mechanic->CurrentRideStation = ride.inspectionStation; + } + + /** + * + * rct2: 0x006B76AB + */ + static void RideCallClosestMechanic(Ride& ride) + { + auto forInspection = !ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown); + auto mechanic = RideFindClosestMechanic(ride, forInspection); + if (mechanic != nullptr) + RideCallMechanic(ride, mechanic, forInspection); + } + + Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection) + { + const auto stationIndex = ride.inspectionStation.IsNull() ? RideGetFirstValidStationExit(ride) : ride.inspectionStation; + if (stationIndex.IsNull()) return nullptr; + + // Get either exit position or entrance position if there is no exit + const auto& station = ride.getStation(stationIndex); + TileCoordsXYZD location = station.Exit; + if (location.IsNull()) + { + location = station.Entrance; + if (station.Entrance.IsNull()) + return nullptr; + } + + // Get station start track element and position + auto mapLocation = location.ToCoordsXYZ(); + TileElement* tileElement = RideGetStationExitElement(mapLocation); + if (tileElement == nullptr) + return nullptr; + + // Set x,y to centre of the station exit for the mechanic search. + auto centreMapLocation = mapLocation.ToTileCentre(); + + return FindClosestMechanic(centreMapLocation, forInspection); } - // Get station start track element and position - auto mapLocation = location.ToCoordsXYZ(); - TileElement* tileElement = RideGetStationExitElement(mapLocation); - if (tileElement == nullptr) - return nullptr; - - // Set x,y to centre of the station exit for the mechanic search. - auto centreMapLocation = mapLocation.ToTileCentre(); - - return FindClosestMechanic(centreMapLocation, forInspection); -} - -/** - * - * rct2: 0x006B774B (forInspection = 0) - * rct2: 0x006B78C3 (forInspection = 1) - */ -Staff* FindClosestMechanic(const CoordsXY& entrancePosition, int32_t forInspection) -{ - Staff* closestMechanic = nullptr; - uint32_t closestDistance = std::numeric_limits::max(); - - for (auto peep : EntityList()) + /** + * + * rct2: 0x006B774B (forInspection = 0) + * rct2: 0x006B78C3 (forInspection = 1) + */ + Staff* FindClosestMechanic(const CoordsXY& entrancePosition, int32_t forInspection) { - if (!peep->isMechanic()) - continue; + Staff* closestMechanic = nullptr; + uint32_t closestDistance = std::numeric_limits::max(); - if (!forInspection) + for (auto peep : EntityList()) { - if (peep->State == PeepState::headingToInspection) + if (!peep->isMechanic()) + continue; + + if (!forInspection) { - if (peep->SubState >= 4) + if (peep->State == PeepState::headingToInspection) + { + if (peep->SubState >= 4) + continue; + } + else if (peep->State != PeepState::patrolling) + continue; + + if (!(peep->staffOrders & STAFF_ORDERS_FIX_RIDES)) continue; } - else if (peep->State != PeepState::patrolling) + else + { + if (peep->State != PeepState::patrolling || !(peep->staffOrders & STAFF_ORDERS_INSPECT_RIDES)) + continue; + } + + auto location = entrancePosition.ToTileStart(); + if (MapIsLocationInPark(location)) + if (!peep->isLocationInPatrol(location)) + continue; + + if (peep->x == kLocationNull) continue; - if (!(peep->staffOrders & STAFF_ORDERS_FIX_RIDES)) - continue; - } - else - { - if (peep->State != PeepState::patrolling || !(peep->staffOrders & STAFF_ORDERS_INSPECT_RIDES)) - continue; + // Manhattan distance + uint32_t distance = std::abs(peep->x - entrancePosition.x) + std::abs(peep->y - entrancePosition.y); + if (distance < closestDistance) + { + closestDistance = distance; + closestMechanic = peep; + } } - auto location = entrancePosition.ToTileStart(); - if (MapIsLocationInPark(location)) - if (!peep->isLocationInPatrol(location)) - continue; - - if (peep->x == kLocationNull) - continue; - - // Manhattan distance - uint32_t distance = std::abs(peep->x - entrancePosition.x) + std::abs(peep->y - entrancePosition.y); - if (distance < closestDistance) - { - closestDistance = distance; - closestMechanic = peep; - } + return closestMechanic; } - return closestMechanic; -} - -Staff* RideGetMechanic(const Ride& ride) -{ - auto staff = getGameState().entities.GetEntity(ride.mechanic); - if (staff != nullptr && staff->isMechanic()) + Staff* RideGetMechanic(const Ride& ride) { - return staff; - } - return nullptr; -} - -Staff* RideGetAssignedMechanic(const Ride& ride) -{ - if (ride.flags.has(RideFlag::brokenDown)) - { - if (ride.mechanicStatus == MechanicStatus::heading || ride.mechanicStatus == MechanicStatus::fixing - || ride.mechanicStatus == MechanicStatus::hasFixedStationBrakes) + auto staff = getGameState().entities.GetEntity(ride.mechanic); + if (staff != nullptr && staff->isMechanic()) { - return RideGetMechanic(ride); + return staff; } + return nullptr; } - return nullptr; -} + Staff* RideGetAssignedMechanic(const Ride& ride) + { + if (ride.flags.has(RideFlag::brokenDown)) + { + if (ride.mechanicStatus == MechanicStatus::heading || ride.mechanicStatus == MechanicStatus::fixing + || ride.mechanicStatus == MechanicStatus::hasFixedStationBrakes) + { + return RideGetMechanic(ride); + } + } + + return nullptr; + } #pragma endregion #pragma region Music functions -/** - * - * Calculates the sample rate for ride music. - */ -static int32_t RideMusicSampleRate(const Ride& ride) -{ - int32_t sampleRate = 22050; - - // Alter sample rate for a power cut effect - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) + /** + * + * Calculates the sample rate for ride music. + */ + static int32_t RideMusicSampleRate(const Ride& ride) { - sampleRate = ride.breakdownSoundModifier * 70; - if (ride.breakdownReasonPending != Breakdown::controlFailure) - sampleRate *= -1; - sampleRate += 22050; + int32_t sampleRate = 22050; + + // Alter sample rate for a power cut effect + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) + { + sampleRate = ride.breakdownSoundModifier * 70; + if (ride.breakdownReasonPending != Breakdown::controlFailure) + sampleRate *= -1; + sampleRate += 22050; + } + + return sampleRate; } - return sampleRate; -} - -/** - * - * Ride music slows down upon breaking. If it's completely broken, no music should play. - */ -static bool RideMusicBreakdownEffect(Ride& ride) -{ - // Oscillate parameters for a power cut effect when breaking down - if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) + /** + * + * Ride music slows down upon breaking. If it's completely broken, no music should play. + */ + static bool RideMusicBreakdownEffect(Ride& ride) { - if (ride.breakdownReasonPending == Breakdown::controlFailure) + // Oscillate parameters for a power cut effect when breaking down + if (ride.flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) { - if (!(getGameState().currentTicks & 7)) - if (ride.breakdownSoundModifier != 255) - ride.breakdownSoundModifier++; - } - else - { - if (ride.flags.has(RideFlag::brokenDown) || ride.breakdownReasonPending == Breakdown::brakesFailure - || ride.breakdownReasonPending == Breakdown::controlFailure) + if (ride.breakdownReasonPending == Breakdown::controlFailure) { - if (ride.breakdownSoundModifier != 255) - ride.breakdownSoundModifier++; + if (!(getGameState().currentTicks & 7)) + if (ride.breakdownSoundModifier != 255) + ride.breakdownSoundModifier++; } - - if (ride.breakdownSoundModifier == 255) + else { - ride.musicTuneId = kTuneIDNull; - return true; + if (ride.flags.has(RideFlag::brokenDown) || ride.breakdownReasonPending == Breakdown::brakesFailure + || ride.breakdownReasonPending == Breakdown::controlFailure) + { + if (ride.breakdownSoundModifier != 255) + ride.breakdownSoundModifier++; + } + + if (ride.breakdownSoundModifier == 255) + { + ride.musicTuneId = kTuneIDNull; + return true; + } } } - } - return false; -} - -/** - * - * Circus music is a sound effect, rather than music. Needs separate processing. - */ -void CircusMusicUpdate(Ride& ride) -{ - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[0]); - if (vehicle == nullptr || vehicle->status != Vehicle::Status::doingCircusShow) - { - ride.musicPosition = 0; - ride.musicTuneId = kTuneIDNull; - return; + return false; } - if (RideMusicBreakdownEffect(ride)) + /** + * + * Circus music is a sound effect, rather than music. Needs separate processing. + */ + void CircusMusicUpdate(Ride& ride) { - return; - } - - CoordsXYZ rideCoords = ride.getStation().GetStart().ToTileCentre(); - - const auto sampleRate = RideMusicSampleRate(ride); - - RideAudio::UpdateMusicInstance(ride, rideCoords, sampleRate); -} - -/** - * - * rct2: 0x006ABE85 - */ -void DefaultMusicUpdate(Ride& ride) -{ - if (ride.status != RideStatus::open || !ride.flags.has(RideFlag::music)) - { - ride.musicTuneId = kTuneIDNull; - return; - } - - if (RideMusicBreakdownEffect(ride)) - { - return; - } - - // Select random tune from available tunes for a music style (of course only merry-go-rounds have more than one tune) - if (ride.musicTuneId == kTuneIDNull) - { - auto& objManager = GetContext()->GetObjectManager(); - auto musicObj = objManager.GetLoadedObject(ride.music); - if (musicObj != nullptr) + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[0]); + if (vehicle == nullptr || vehicle->status != Vehicle::Status::doingCircusShow) { - auto numTracks = musicObj->GetTrackCount(); - ride.musicTuneId = static_cast(UtilRand() % numTracks); ride.musicPosition = 0; + ride.musicTuneId = kTuneIDNull; + return; } - return; + + if (RideMusicBreakdownEffect(ride)) + { + return; + } + + CoordsXYZ rideCoords = ride.getStation().GetStart().ToTileCentre(); + + const auto sampleRate = RideMusicSampleRate(ride); + + RideAudio::UpdateMusicInstance(ride, rideCoords, sampleRate); } - CoordsXYZ rideCoords = ride.getStation().GetStart().ToTileCentre(); + /** + * + * rct2: 0x006ABE85 + */ + void DefaultMusicUpdate(Ride& ride) + { + if (ride.status != RideStatus::open || !ride.flags.has(RideFlag::music)) + { + ride.musicTuneId = kTuneIDNull; + return; + } - int32_t sampleRate = RideMusicSampleRate(ride); + if (RideMusicBreakdownEffect(ride)) + { + return; + } - RideAudio::UpdateMusicInstance(ride, rideCoords, sampleRate); -} + // Select random tune from available tunes for a music style (of course only merry-go-rounds have more than one tune) + if (ride.musicTuneId == kTuneIDNull) + { + auto& objManager = GetContext()->GetObjectManager(); + auto musicObj = objManager.GetLoadedObject(ride.music); + if (musicObj != nullptr) + { + auto numTracks = musicObj->GetTrackCount(); + ride.musicTuneId = static_cast(UtilRand() % numTracks); + ride.musicPosition = 0; + } + return; + } -static void RideMusicUpdate(Ride& ride) -{ - const auto& rtd = ride.getRideTypeDescriptor(); + CoordsXYZ rideCoords = ride.getStation().GetStart().ToTileCentre(); - if (!rtd.flags.hasAny(RtdFlag::hasMusicByDefault, RtdFlag::allowMusic)) - return; - rtd.MusicUpdateFunction(ride); -} + int32_t sampleRate = RideMusicSampleRate(ride); + + RideAudio::UpdateMusicInstance(ride, rideCoords, sampleRate); + } + + static void RideMusicUpdate(Ride& ride) + { + const auto& rtd = ride.getRideTypeDescriptor(); + + if (!rtd.flags.hasAny(RtdFlag::hasMusicByDefault, RtdFlag::allowMusic)) + return; + rtd.MusicUpdateFunction(ride); + } #pragma endregion #pragma region Measurement functions -/** - * - * rct2: 0x006B64F2 - */ -static void RideMeasurementUpdate(Ride& ride, RideMeasurement& measurement) -{ - if (measurement.vehicle_index >= std::size(ride.vehicles)) - return; - - auto vehicle = getGameState().entities.GetEntity(ride.vehicles[measurement.vehicle_index]); - if (vehicle == nullptr) - return; - - if (measurement.flags.has(RideMeasurementFlag::unloading)) + /** + * + * rct2: 0x006B64F2 + */ + static void RideMeasurementUpdate(Ride& ride, RideMeasurement& measurement) { - if (vehicle->status != Vehicle::Status::departing && vehicle->status != Vehicle::Status::travellingCableLift) + if (measurement.vehicle_index >= std::size(ride.vehicles)) return; - measurement.flags.unset(RideMeasurementFlag::unloading); - if (measurement.current_station == vehicle->current_station) - measurement.current_item = 0; - } - - if (vehicle->status == Vehicle::Status::unloadingPassengers) - { - measurement.flags.set(RideMeasurementFlag::unloading); - return; - } - - auto trackType = vehicle->GetTrackType(); - if (trackType == TrackElemType::blockBrakes || trackType == TrackElemType::cableLiftHill - || trackType == TrackElemType::up25ToFlat || trackType == TrackElemType::up60ToFlat - || trackType == TrackElemType::diagUp25ToFlat || trackType == TrackElemType::diagUp60ToFlat - || trackType == TrackElemType::diagBlockBrakes) - if (vehicle->velocity == 0) + auto vehicle = getGameState().entities.GetEntity(ride.vehicles[measurement.vehicle_index]); + if (vehicle == nullptr) return; - if (measurement.current_item >= RideMeasurement::kMaxItems) - return; + if (measurement.flags.has(RideMeasurementFlag::unloading)) + { + if (vehicle->status != Vehicle::Status::departing && vehicle->status != Vehicle::Status::travellingCableLift) + return; - const auto currentTicks = getGameState().currentTicks; + measurement.flags.unset(RideMeasurementFlag::unloading); + if (measurement.current_station == vehicle->current_station) + measurement.current_item = 0; + } - if (measurement.flags.has(RideMeasurementFlag::gForces)) - { - auto gForces = vehicle->GetGForces(); - gForces.verticalG = std::clamp(gForces.verticalG / 8, -127, 127); - gForces.lateralG = std::clamp(gForces.lateralG / 8, -127, 127); + if (vehicle->status == Vehicle::Status::unloadingPassengers) + { + measurement.flags.set(RideMeasurementFlag::unloading); + return; + } + + auto trackType = vehicle->GetTrackType(); + if (trackType == TrackElemType::blockBrakes || trackType == TrackElemType::cableLiftHill + || trackType == TrackElemType::up25ToFlat || trackType == TrackElemType::up60ToFlat + || trackType == TrackElemType::diagUp25ToFlat || trackType == TrackElemType::diagUp60ToFlat + || trackType == TrackElemType::diagBlockBrakes) + if (vehicle->velocity == 0) + return; + + if (measurement.current_item >= RideMeasurement::kMaxItems) + return; + + const auto currentTicks = getGameState().currentTicks; + + if (measurement.flags.has(RideMeasurementFlag::gForces)) + { + auto gForces = vehicle->GetGForces(); + gForces.verticalG = std::clamp(gForces.verticalG / 8, -127, 127); + gForces.lateralG = std::clamp(gForces.lateralG / 8, -127, 127); + + if (currentTicks & 1) + { + gForces.verticalG = (gForces.verticalG + measurement.vertical[measurement.current_item]) / 2; + gForces.lateralG = (gForces.lateralG + measurement.lateral[measurement.current_item]) / 2; + } + + measurement.vertical[measurement.current_item] = gForces.verticalG & 0xFF; + measurement.lateral[measurement.current_item] = gForces.lateralG & 0xFF; + } + + auto velocity = std::min(std::abs((vehicle->velocity * 5) >> 16), 255); + auto altitude = std::min(vehicle->z / 8, 255); if (currentTicks & 1) { - gForces.verticalG = (gForces.verticalG + measurement.vertical[measurement.current_item]) / 2; - gForces.lateralG = (gForces.lateralG + measurement.lateral[measurement.current_item]) / 2; + velocity = (velocity + measurement.velocity[measurement.current_item]) / 2; + altitude = (altitude + measurement.altitude[measurement.current_item]) / 2; } - measurement.vertical[measurement.current_item] = gForces.verticalG & 0xFF; - measurement.lateral[measurement.current_item] = gForces.lateralG & 0xFF; - } + measurement.velocity[measurement.current_item] = velocity & 0xFF; + measurement.altitude[measurement.current_item] = altitude & 0xFF; - auto velocity = std::min(std::abs((vehicle->velocity * 5) >> 16), 255); - auto altitude = std::min(vehicle->z / 8, 255); - - if (currentTicks & 1) - { - velocity = (velocity + measurement.velocity[measurement.current_item]) / 2; - altitude = (altitude + measurement.altitude[measurement.current_item]) / 2; - } - - measurement.velocity[measurement.current_item] = velocity & 0xFF; - measurement.altitude[measurement.current_item] = altitude & 0xFF; - - if (currentTicks & 1) - { - measurement.current_item++; - measurement.num_items = std::max(measurement.num_items, measurement.current_item); - } -} - -/** - * - * rct2: 0x006B6456 - */ -void RideMeasurementsUpdate() -{ - PROFILED_FUNCTION(); - - if (gLegacyScene == LegacyScene::scenarioEditor) - return; - - auto& gameState = getGameState(); - - // For each ride measurement - for (auto& ride : RideManager(gameState)) - { - auto measurement = ride.measurement.get(); - if (measurement != nullptr && ride.flags.has(RideFlag::onTrack) && ride.status != RideStatus::simulating) + if (currentTicks & 1) { - if (measurement->flags.has(RideMeasurementFlag::running)) + measurement.current_item++; + measurement.num_items = std::max(measurement.num_items, measurement.current_item); + } + } + + /** + * + * rct2: 0x006B6456 + */ + void RideMeasurementsUpdate() + { + PROFILED_FUNCTION(); + + if (gLegacyScene == LegacyScene::scenarioEditor) + return; + + auto& gameState = getGameState(); + + // For each ride measurement + for (auto& ride : RideManager(gameState)) + { + auto measurement = ride.measurement.get(); + if (measurement != nullptr && ride.flags.has(RideFlag::onTrack) && ride.status != RideStatus::simulating) { - RideMeasurementUpdate(ride, *measurement); - } - else - { - // For each vehicle - for (int32_t j = 0; j < ride.numTrains; j++) + if (measurement->flags.has(RideMeasurementFlag::running)) { - auto vehicleSpriteIdx = ride.vehicles[j]; - auto vehicle = gameState.entities.GetEntity(vehicleSpriteIdx); - if (vehicle != nullptr) + RideMeasurementUpdate(ride, *measurement); + } + else + { + // For each vehicle + for (int32_t j = 0; j < ride.numTrains; j++) { - if (vehicle->status == Vehicle::Status::departing - || vehicle->status == Vehicle::Status::travellingCableLift) + auto vehicleSpriteIdx = ride.vehicles[j]; + auto vehicle = gameState.entities.GetEntity(vehicleSpriteIdx); + if (vehicle != nullptr) { - measurement->vehicle_index = j; - measurement->current_station = vehicle->current_station; - measurement->flags.set(RideMeasurementFlag::running); - measurement->flags.unset(RideMeasurementFlag::unloading); - RideMeasurementUpdate(ride, *measurement); - break; + if (vehicle->status == Vehicle::Status::departing + || vehicle->status == Vehicle::Status::travellingCableLift) + { + measurement->vehicle_index = j; + measurement->current_station = vehicle->current_station; + measurement->flags.set(RideMeasurementFlag::running); + measurement->flags.unset(RideMeasurementFlag::unloading); + RideMeasurementUpdate(ride, *measurement); + break; + } } } } } } } -} -/** - * If there are more than the threshold of allowed ride measurements, free the non-LRU one. - */ -static void RideFreeOldMeasurements() -{ - size_t numRideMeasurements; - do + /** + * If there are more than the threshold of allowed ride measurements, free the non-LRU one. + */ + static void RideFreeOldMeasurements() { - Ride* lruRide{}; - numRideMeasurements = 0; - - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) + size_t numRideMeasurements; + do { - if (ride.measurement != nullptr) + Ride* lruRide{}; + numRideMeasurements = 0; + + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) { - if (lruRide == nullptr || ride.measurement->last_use_tick > lruRide->measurement->last_use_tick) + if (ride.measurement != nullptr) { - lruRide = &ride; + if (lruRide == nullptr || ride.measurement->last_use_tick > lruRide->measurement->last_use_tick) + { + lruRide = &ride; + } + numRideMeasurements++; } - numRideMeasurements++; } - } - if (numRideMeasurements > kMaxRideMeasurements && lruRide != nullptr) + if (numRideMeasurements > kMaxRideMeasurements && lruRide != nullptr) + { + lruRide->measurement = {}; + numRideMeasurements--; + } + } while (numRideMeasurements > kMaxRideMeasurements); + } + + std::pair Ride::getMeasurement() + { + const auto& rtd = getRideTypeDescriptor(); + + // Check if ride type supports data logging + if (!rtd.flags.has(RtdFlag::hasDataLogging)) { - lruRide->measurement = {}; - numRideMeasurements--; + return { nullptr, { STR_DATA_LOGGING_NOT_AVAILABLE_FOR_THIS_TYPE_OF_RIDE, {} } }; } - } while (numRideMeasurements > kMaxRideMeasurements); -} -std::pair Ride::getMeasurement() -{ - const auto& rtd = getRideTypeDescriptor(); - - // Check if ride type supports data logging - if (!rtd.flags.has(RtdFlag::hasDataLogging)) - { - return { nullptr, { STR_DATA_LOGGING_NOT_AVAILABLE_FOR_THIS_TYPE_OF_RIDE, {} } }; - } - - // Check if a measurement already exists for this ride - if (measurement == nullptr) - { - measurement = std::make_unique(); - if (rtd.flags.has(RtdFlag::hasGForces)) + // Check if a measurement already exists for this ride + if (measurement == nullptr) { - measurement->flags.set(RideMeasurementFlag::gForces); + measurement = std::make_unique(); + if (rtd.flags.has(RtdFlag::hasGForces)) + { + measurement->flags.set(RideMeasurementFlag::gForces); + } + RideFreeOldMeasurements(); + assert(measurement != nullptr); } - RideFreeOldMeasurements(); - assert(measurement != nullptr); - } - measurement->last_use_tick = getGameState().currentTicks; - if (measurement->flags.has(RideMeasurementFlag::running)) - { - return { measurement.get(), { kStringIdEmpty, {} } }; - } + measurement->last_use_tick = getGameState().currentTicks; + if (measurement->flags.has(RideMeasurementFlag::running)) + { + return { measurement.get(), { kStringIdEmpty, {} } }; + } - auto ft = Formatter(); - ft.Add(GetRideComponentName(rtd.NameConvention.vehicle).singular); - ft.Add(GetRideComponentName(rtd.NameConvention.station).singular); - return { nullptr, { STR_DATA_LOGGING_WILL_START_WHEN_NEXT_LEAVES, ft } }; -} + auto ft = Formatter(); + ft.Add(GetRideComponentName(rtd.NameConvention.vehicle).singular); + ft.Add(GetRideComponentName(rtd.NameConvention.station).singular); + return { nullptr, { STR_DATA_LOGGING_WILL_START_WHEN_NEXT_LEAVES, ft } }; + } #pragma endregion #pragma region Colour functions -VehicleColour RideGetVehicleColour(const Ride& ride, int32_t vehicleIndex) -{ - // Prevent indexing array out of bounds - vehicleIndex = std::clamp(vehicleIndex, 0, std::size(ride.vehicleColours) - 1); - return ride.vehicleColours[vehicleIndex]; -} - -static bool RideTypeVehicleColourExists(ObjectEntryIndex subType, const VehicleColour& vehicleColour) -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) + VehicleColour RideGetVehicleColour(const Ride& ride, int32_t vehicleIndex) { - if (ride.subtype != subType) - continue; - if (ride.vehicleColours[0].Body != vehicleColour.Body) - continue; - return true; + // Prevent indexing array out of bounds + vehicleIndex = std::clamp(vehicleIndex, 0, std::size(ride.vehicleColours) - 1); + return ride.vehicleColours[vehicleIndex]; } - return false; -} -int32_t RideGetUnusedPresetVehicleColour(ObjectEntryIndex subType, uint32_t randomValue) -{ - const auto* rideEntry = GetRideEntryByIndex(subType); - if (rideEntry == nullptr) - return 0; - - const auto* colourPresets = rideEntry->vehicle_preset_list; - if (colourPresets == nullptr || colourPresets->count == 0) - return 0; - if (colourPresets->count == 255) - return 255; - - // Find all the presets that haven't yet been used in the park for this ride type - std::vector unused; - unused.reserve(colourPresets->count); - for (uint8_t i = 0; i < colourPresets->count; i++) + static bool RideTypeVehicleColourExists(ObjectEntryIndex subType, const VehicleColour& vehicleColour) { - const auto& preset = colourPresets->list[i]; - if (!RideTypeVehicleColourExists(subType, preset)) + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) { - unused.push_back(i); + if (ride.subtype != subType) + continue; + if (ride.vehicleColours[0].Body != vehicleColour.Body) + continue; + return true; + } + return false; + } + + int32_t RideGetUnusedPresetVehicleColour(ObjectEntryIndex subType, uint32_t randomValue) + { + const auto* rideEntry = GetRideEntryByIndex(subType); + if (rideEntry == nullptr) + return 0; + + const auto* colourPresets = rideEntry->vehicle_preset_list; + if (colourPresets == nullptr || colourPresets->count == 0) + return 0; + if (colourPresets->count == 255) + return 255; + + // Find all the presets that haven't yet been used in the park for this ride type + std::vector unused; + unused.reserve(colourPresets->count); + for (uint8_t i = 0; i < colourPresets->count; i++) + { + const auto& preset = colourPresets->list[i]; + if (!RideTypeVehicleColourExists(subType, preset)) + { + unused.push_back(i); + } + } + + // If all presets have been used, just go with a random preset + if (unused.empty()) + return randomValue % colourPresets->count; + + // Choose a random preset from the list of unused presets + auto unusedIndex = randomValue % unused.size(); + return unused[unusedIndex]; + } + + /** + * + * rct2: 0x006DE52C + */ + void RideSetVehicleColoursToRandomPreset(Ride& ride, uint8_t preset_index) + { + const auto* rideEntry = GetRideEntryByIndex(ride.subtype); + const auto* presetList = rideEntry->vehicle_preset_list; + + if (presetList->count != 0 && presetList->count != 255) + { + assert(preset_index < presetList->count); + + ride.vehicleColourSettings = VehicleColourSettings::same; + ride.vehicleColours[0] = presetList->list[preset_index]; + } + else + { + ride.vehicleColourSettings = VehicleColourSettings::perTrain; + for (uint32_t i = 0; i < presetList->count; i++) + { + const auto index = i % 32u; + ride.vehicleColours[i] = presetList->list[index]; + } } } - // If all presets have been used, just go with a random preset - if (unused.empty()) - return randomValue % colourPresets->count; - - // Choose a random preset from the list of unused presets - auto unusedIndex = randomValue % unused.size(); - return unused[unusedIndex]; -} - -/** - * - * rct2: 0x006DE52C - */ -void RideSetVehicleColoursToRandomPreset(Ride& ride, uint8_t preset_index) -{ - const auto* rideEntry = GetRideEntryByIndex(ride.subtype); - const auto* presetList = rideEntry->vehicle_preset_list; - - if (presetList->count != 0 && presetList->count != 255) - { - assert(preset_index < presetList->count); - - ride.vehicleColourSettings = VehicleColourSettings::same; - ride.vehicleColours[0] = presetList->list[preset_index]; - } - else - { - ride.vehicleColourSettings = VehicleColourSettings::perTrain; - for (uint32_t i = 0; i < presetList->count; i++) - { - const auto index = i % 32u; - ride.vehicleColours[i] = presetList->list[index]; - } - } -} - #pragma endregion #pragma region Reachability -/** - * - * rct2: 0x006B7A5E - */ -void RideCheckAllReachable() -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) + /** + * + * rct2: 0x006B7A5E + */ + void RideCheckAllReachable() { - if (ride.connectedMessageThrottle != 0) - ride.connectedMessageThrottle--; - - if (ride.status != RideStatus::open || ride.connectedMessageThrottle != 0) - continue; - - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) - RideShopConnected(ride); - else - RideEntranceExitConnected(ride); - } -} - -/** - * - * rct2: 0x006B7C59 - * @return true if the coordinate is reachable or has no entrance, false otherwise - */ -static bool RideEntranceExitIsReachable(const TileCoordsXYZD& coordinates) -{ - if (coordinates.IsNull()) - return true; - - TileCoordsXYZ loc{ coordinates.x, coordinates.y, coordinates.z }; - loc -= TileDirectionDelta[coordinates.direction]; - - return MapCoordIsConnected(loc, coordinates.direction); -} - -static void RideEntranceExitConnected(Ride& ride) -{ - for (auto& station : ride.getStations()) - { - auto station_start = station.Start; - auto entrance = station.Entrance; - auto exit = station.Exit; - - if (station_start.IsNull()) - continue; - - if (!entrance.IsNull() && !RideEntranceExitIsReachable(entrance)) + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) { - // name of ride is parameter of the format string - Formatter ft; - ride.formatNameTo(ft); - if (Config::Get().notifications.rideWarnings) - { - News::AddItemToQueue(News::ItemType::ride, STR_ENTRANCE_NOT_CONNECTED, ride.id.ToUnderlying(), ft); - } - ride.connectedMessageThrottle = 3; - } + if (ride.connectedMessageThrottle != 0) + ride.connectedMessageThrottle--; - if (!exit.IsNull() && !RideEntranceExitIsReachable(exit)) - { - // name of ride is parameter of the format string - Formatter ft; - ride.formatNameTo(ft); - if (Config::Get().notifications.rideWarnings) - { - News::AddItemToQueue(News::ItemType::ride, STR_EXIT_NOT_CONNECTED, ride.id.ToUnderlying(), ft); - } - ride.connectedMessageThrottle = 3; + if (ride.status != RideStatus::open || ride.connectedMessageThrottle != 0) + continue; + + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + RideShopConnected(ride); + else + RideEntranceExitConnected(ride); } } -} -static void RideShopConnected(const Ride& ride) -{ - auto shopLoc = TileCoordsXY(ride.getStation().Start); - if (shopLoc.IsNull()) - return; - - TrackElement* trackElement = nullptr; - TileElement* tileElement = MapGetFirstElementAt(shopLoc); - do + /** + * + * rct2: 0x006B7C59 + * @return true if the coordinate is reachable or has no entrance, false otherwise + */ + static bool RideEntranceExitIsReachable(const TileCoordsXYZD& coordinates) { - if (tileElement == nullptr) - break; - if (tileElement->getType() == TileElementType::track && tileElement->asTrack()->GetRideIndex() == ride.id) - { - trackElement = tileElement->asTrack(); - break; - } - } while (!(tileElement++)->isLastForTile()); + if (coordinates.IsNull()) + return true; - if (trackElement == nullptr) - return; + TileCoordsXYZ loc{ coordinates.x, coordinates.y, coordinates.z }; + loc -= TileDirectionDelta[coordinates.direction]; - auto track_type = trackElement->GetTrackType(); - auto ride2 = GetRide(trackElement->GetRideIndex()); - if (ride2 == nullptr) - return; + return MapCoordIsConnected(loc, coordinates.direction); + } - const auto& ted = GetTrackElementDescriptor(track_type); - uint8_t connectionSides = ted.sequenceData.sequences[0].getEntranceConnectionSides(); - uint8_t tile_direction = trackElement->getDirection(); - connectionSides = Numerics::rol4(connectionSides, tile_direction); - - // Now each bit in connectionSides stands for an entrance direction to check - if (connectionSides == 0) - return; - - for (auto count = 0; connectionSides != 0; count++) + static void RideEntranceExitConnected(Ride& ride) { - if (!(connectionSides & 1)) + for (auto& station : ride.getStations()) { - connectionSides >>= 1; - continue; + auto station_start = station.Start; + auto entrance = station.Entrance; + auto exit = station.Exit; + + if (station_start.IsNull()) + continue; + + if (!entrance.IsNull() && !RideEntranceExitIsReachable(entrance)) + { + // name of ride is parameter of the format string + Formatter ft; + ride.formatNameTo(ft); + if (Config::Get().notifications.rideWarnings) + { + News::AddItemToQueue(News::ItemType::ride, STR_ENTRANCE_NOT_CONNECTED, ride.id.ToUnderlying(), ft); + } + ride.connectedMessageThrottle = 3; + } + + if (!exit.IsNull() && !RideEntranceExitIsReachable(exit)) + { + // name of ride is parameter of the format string + Formatter ft; + ride.formatNameTo(ft); + if (Config::Get().notifications.rideWarnings) + { + News::AddItemToQueue(News::ItemType::ride, STR_EXIT_NOT_CONNECTED, ride.id.ToUnderlying(), ft); + } + ride.connectedMessageThrottle = 3; + } } - connectionSides >>= 1; + } - // Flip direction north<->south, east<->west - uint8_t face_direction = DirectionReverse(count); - - int32_t y2 = shopLoc.y - TileDirectionDelta[face_direction].y; - int32_t x2 = shopLoc.x - TileDirectionDelta[face_direction].x; - - if (MapCoordIsConnected({ x2, y2, tileElement->baseHeight }, face_direction)) + static void RideShopConnected(const Ride& ride) + { + auto shopLoc = TileCoordsXY(ride.getStation().Start); + if (shopLoc.IsNull()) return; - } - // Name of ride is parameter of the format string - if (Config::Get().notifications.rideWarnings) - { - Formatter ft; - ride2->formatNameTo(ft); - News::AddItemToQueue(News::ItemType::ride, STR_ENTRANCE_NOT_CONNECTED, ride2->id.ToUnderlying(), ft); - } + TrackElement* trackElement = nullptr; + TileElement* tileElement = MapGetFirstElementAt(shopLoc); + do + { + if (tileElement == nullptr) + break; + if (tileElement->getType() == TileElementType::track && tileElement->asTrack()->GetRideIndex() == ride.id) + { + trackElement = tileElement->asTrack(); + break; + } + } while (!(tileElement++)->isLastForTile()); - ride2->connectedMessageThrottle = 3; -} + if (trackElement == nullptr) + return; + + auto track_type = trackElement->GetTrackType(); + auto ride2 = GetRide(trackElement->GetRideIndex()); + if (ride2 == nullptr) + return; + + const auto& ted = GetTrackElementDescriptor(track_type); + uint8_t connectionSides = ted.sequenceData.sequences[0].getEntranceConnectionSides(); + uint8_t tile_direction = trackElement->getDirection(); + connectionSides = Numerics::rol4(connectionSides, tile_direction); + + // Now each bit in connectionSides stands for an entrance direction to check + if (connectionSides == 0) + return; + + for (auto count = 0; connectionSides != 0; count++) + { + if (!(connectionSides & 1)) + { + connectionSides >>= 1; + continue; + } + connectionSides >>= 1; + + // Flip direction north<->south, east<->west + uint8_t face_direction = DirectionReverse(count); + + int32_t y2 = shopLoc.y - TileDirectionDelta[face_direction].y; + int32_t x2 = shopLoc.x - TileDirectionDelta[face_direction].x; + + if (MapCoordIsConnected({ x2, y2, tileElement->baseHeight }, face_direction)) + return; + } + + // Name of ride is parameter of the format string + if (Config::Get().notifications.rideWarnings) + { + Formatter ft; + ride2->formatNameTo(ft); + News::AddItemToQueue(News::ItemType::ride, STR_ENTRANCE_NOT_CONNECTED, ride2->id.ToUnderlying(), ft); + } + + ride2->connectedMessageThrottle = 3; + } #pragma endregion #pragma region Interface -static void RideTrackSetMapTooltip(const TrackElement& trackElement) -{ - auto rideIndex = trackElement.GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride != nullptr) + static void RideTrackSetMapTooltip(const TrackElement& trackElement) { + auto rideIndex = trackElement.GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride != nullptr) + { + auto ft = Formatter(); + ft.Add(STR_RIDE_MAP_TIP); + ride->formatNameTo(ft); + ride->formatStatusTo(ft); + auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); + intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); + ContextBroadcastIntent(&intent); + } + } + + static void RideQueueBannerSetMapTooltip(const PathElement& pathElement) + { + auto rideIndex = pathElement.GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return; + auto ft = Formatter(); ft.Add(STR_RIDE_MAP_TIP); ride->formatNameTo(ft); @@ -2162,3592 +2182,3579 @@ static void RideTrackSetMapTooltip(const TrackElement& trackElement) intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); ContextBroadcastIntent(&intent); } -} -static void RideQueueBannerSetMapTooltip(const PathElement& pathElement) -{ - auto rideIndex = pathElement.GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return; - - auto ft = Formatter(); - ft.Add(STR_RIDE_MAP_TIP); - ride->formatNameTo(ft); - ride->formatStatusTo(ft); - auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); - intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); - ContextBroadcastIntent(&intent); -} - -static void RideStationSetMapTooltip(const TrackElement& trackElement) -{ - auto rideIndex = trackElement.GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return; - - const auto stationIndex = trackElement.GetStationIndex(); - const auto stationNumber = ride->getStationNumber(stationIndex); - - auto ft = Formatter(); - ft.Add(STR_RIDE_MAP_TIP); - ft.Add(ride->numStations <= 1 ? STR_RIDE_STATION : STR_RIDE_STATION_X); - ride->formatNameTo(ft); - ft.Add(GetRideComponentName(ride->getRideTypeDescriptor().NameConvention.station).capitalised); - ft.Add(stationNumber); - ride->formatStatusTo(ft); - auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); - intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); - ContextBroadcastIntent(&intent); -} - -static void RideEntranceSetMapTooltip(const EntranceElement& entranceElement) -{ - auto rideIndex = entranceElement.GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return; - - if (entranceElement.GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE) + static void RideStationSetMapTooltip(const TrackElement& trackElement) { - // Get the queue length - int32_t queueLength = 0; - const auto stationIndex = entranceElement.GetStationIndex(); - if (!ride->getStation(stationIndex).Entrance.IsNull()) - { - queueLength = ride->getStation(stationIndex).QueueLength; - } + auto rideIndex = trackElement.GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return; + + const auto stationIndex = trackElement.GetStationIndex(); + const auto stationNumber = ride->getStationNumber(stationIndex); auto ft = Formatter(); ft.Add(STR_RIDE_MAP_TIP); - ft.Add(ride->numStations <= 1 ? STR_RIDE_ENTRANCE : STR_RIDE_STATION_X_ENTRANCE); + ft.Add(ride->numStations <= 1 ? STR_RIDE_STATION : STR_RIDE_STATION_X); ride->formatNameTo(ft); - - // String IDs have an extra pop16 for some reason - ft.Increment(sizeof(uint16_t)); - - const auto stationNumber = ride->getStationNumber(stationIndex); + ft.Add(GetRideComponentName(ride->getRideTypeDescriptor().NameConvention.station).capitalised); ft.Add(stationNumber); - - switch (queueLength) - { - case 0: - ft.Add(STR_QUEUE_EMPTY); - break; - case 1: - ft.Add(STR_QUEUE_ONE_PERSON); - break; - default: - ft.Add(STR_QUEUE_PEOPLE); - break; - } - ft.Add(queueLength); - + ride->formatStatusTo(ft); auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); ContextBroadcastIntent(&intent); } - else - { - auto ft = Formatter(); - ft.Add(ride->numStations <= 1 ? STR_RIDE_EXIT : STR_RIDE_STATION_X_EXIT); - ride->formatNameTo(ft); - // String IDs have an extra pop16 for some reason - ft.Increment(sizeof(uint16_t)); - - const auto stationIndex = entranceElement.GetStationIndex(); - const auto stationNumber = ride->getStationNumber(stationIndex); - ft.Add(stationNumber); - auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); - intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); - ContextBroadcastIntent(&intent); - } -} - -void RideSetMapTooltip(const TileElement& tileElement) -{ - if (tileElement.getType() == TileElementType::entrance) + static void RideEntranceSetMapTooltip(const EntranceElement& entranceElement) { - RideEntranceSetMapTooltip(*tileElement.asEntrance()); - } - else if (tileElement.getType() == TileElementType::track) - { - const auto* trackElement = tileElement.asTrack(); - if (trackElement->IsStation()) + auto rideIndex = entranceElement.GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return; + + if (entranceElement.GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE) { - RideStationSetMapTooltip(*trackElement); + // Get the queue length + int32_t queueLength = 0; + const auto stationIndex = entranceElement.GetStationIndex(); + if (!ride->getStation(stationIndex).Entrance.IsNull()) + { + queueLength = ride->getStation(stationIndex).QueueLength; + } + + auto ft = Formatter(); + ft.Add(STR_RIDE_MAP_TIP); + ft.Add(ride->numStations <= 1 ? STR_RIDE_ENTRANCE : STR_RIDE_STATION_X_ENTRANCE); + ride->formatNameTo(ft); + + // String IDs have an extra pop16 for some reason + ft.Increment(sizeof(uint16_t)); + + const auto stationNumber = ride->getStationNumber(stationIndex); + ft.Add(stationNumber); + + switch (queueLength) + { + case 0: + ft.Add(STR_QUEUE_EMPTY); + break; + case 1: + ft.Add(STR_QUEUE_ONE_PERSON); + break; + default: + ft.Add(STR_QUEUE_PEOPLE); + break; + } + ft.Add(queueLength); + + auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); + intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); + ContextBroadcastIntent(&intent); } else { - RideTrackSetMapTooltip(*trackElement); + auto ft = Formatter(); + ft.Add(ride->numStations <= 1 ? STR_RIDE_EXIT : STR_RIDE_STATION_X_EXIT); + ride->formatNameTo(ft); + + // String IDs have an extra pop16 for some reason + ft.Increment(sizeof(uint16_t)); + + const auto stationIndex = entranceElement.GetStationIndex(); + const auto stationNumber = ride->getStationNumber(stationIndex); + ft.Add(stationNumber); + auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); + intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); + ContextBroadcastIntent(&intent); } } - else if (tileElement.getType() == TileElementType::path) + + void RideSetMapTooltip(const TileElement& tileElement) { - RideQueueBannerSetMapTooltip(*tileElement.asPath()); + if (tileElement.getType() == TileElementType::entrance) + { + RideEntranceSetMapTooltip(*tileElement.asEntrance()); + } + else if (tileElement.getType() == TileElementType::track) + { + const auto* trackElement = tileElement.asTrack(); + if (trackElement->IsStation()) + { + RideStationSetMapTooltip(*trackElement); + } + else + { + RideTrackSetMapTooltip(*trackElement); + } + } + else if (tileElement.getType() == TileElementType::path) + { + RideQueueBannerSetMapTooltip(*tileElement.asPath()); + } } -} #pragma endregion -/** - * - * rct2: 0x006B4CC1 - */ -static ResultWithMessage RideModeCheckValidStationNumbers(const Ride& ride) -{ - uint16_t numStations = 0; - for (const auto& station : ride.getStations()) + /** + * + * rct2: 0x006B4CC1 + */ + static ResultWithMessage RideModeCheckValidStationNumbers(const Ride& ride) { - if (!station.Start.IsNull()) + uint16_t numStations = 0; + for (const auto& station : ride.getStations()) { - numStations++; + if (!station.Start.IsNull()) + { + numStations++; + } } - } - switch (ride.mode) - { - case RideMode::reverseInclineLaunchedShuttle: - case RideMode::poweredLaunchPassthrough: - case RideMode::poweredLaunch: - case RideMode::limPoweredLaunch: - if (numStations <= 1) - return { true }; - return { false, STR_UNABLE_TO_OPERATE_WITH_MORE_THAN_ONE_STATION_IN_THIS_MODE }; - case RideMode::shuttle: - if (numStations >= 2) - return { true }; - return { false, STR_UNABLE_TO_OPERATE_WITH_LESS_THAN_TWO_STATIONS_IN_THIS_MODE }; - default: + switch (ride.mode) { - // This is workaround for multiple compilation errors of type "enumeration value ‘RIDE_MODE_*' not handled - // in switch [-Werror=switch]" + case RideMode::reverseInclineLaunchedShuttle: + case RideMode::poweredLaunchPassthrough: + case RideMode::poweredLaunch: + case RideMode::limPoweredLaunch: + if (numStations <= 1) + return { true }; + return { false, STR_UNABLE_TO_OPERATE_WITH_MORE_THAN_ONE_STATION_IN_THIS_MODE }; + case RideMode::shuttle: + if (numStations >= 2) + return { true }; + return { false, STR_UNABLE_TO_OPERATE_WITH_LESS_THAN_TWO_STATIONS_IN_THIS_MODE }; + default: + { + // This is workaround for multiple compilation errors of type "enumeration value ‘RIDE_MODE_*' not handled + // in switch [-Werror=switch]" + } } - } - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.flags.has(RtdFlag::hasOneStation) && numStations > 1) - return { false, STR_UNABLE_TO_OPERATE_WITH_MORE_THAN_ONE_STATION_IN_THIS_MODE }; - - return { true }; -} - -/** - * returns stationIndex of first station on success - * STATION_INDEX_NULL on failure. - */ -static StationIndexWithMessage RideModeCheckStationPresent(const Ride& ride) -{ - auto stationIndex = RideGetFirstValidStationStart(ride); - - if (stationIndex.IsNull()) - { const auto& rtd = ride.getRideTypeDescriptor(); - if (!rtd.flags.has(RtdFlag::hasTrack)) - return { StationIndex::GetNull(), STR_NOT_YET_CONSTRUCTED }; + if (rtd.flags.has(RtdFlag::hasOneStation) && numStations > 1) + return { false, STR_UNABLE_TO_OPERATE_WITH_MORE_THAN_ONE_STATION_IN_THIS_MODE }; - if (rtd.specialType == RtdSpecialType::maze) - return { StationIndex::GetNull(), STR_NOT_YET_CONSTRUCTED }; - - return { StationIndex::GetNull(), STR_REQUIRES_A_STATION_PLATFORM }; - } - - return { stationIndex }; -} - -/** - * - * rct2: 0x006B5872 - */ -static ResultWithMessage RideCheckForEntranceExit(RideId rideIndex) -{ - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return { false }; - - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) - return { true }; - - uint8_t entrance = 0; - uint8_t exit = 0; - for (const auto& station : ride->getStations()) - { - if (station.Start.IsNull()) - continue; - - if (!station.Entrance.IsNull()) - { - entrance = 1; - } - - if (!station.Exit.IsNull()) - { - exit = 1; - } - - // If station start and no entrance/exit - // Sets same error message as no entrance - if (station.Exit.IsNull() && station.Entrance.IsNull()) - { - entrance = 0; - break; - } - } - - if (entrance == 0) - { - return { false, STR_ENTRANCE_NOT_YET_BUILT }; - } - - if (exit == 0) - { - return { false, STR_EXIT_NOT_YET_BUILT }; - } - - return { true }; -} - -/** - * Calls FootpathChainRideQueue for all entrances of the ride - * rct2: 0x006B5952 - */ -void Ride::chainQueues() const -{ - for (const auto& station : stations) - { - if (station.Entrance.IsNull()) - continue; - - auto mapLocation = station.Entrance.ToCoordsXYZ(); - - // This will fire for every entrance on this x, y and z, regardless whether that actually belongs to - // the ride or not. - TileElement* tileElement = MapGetFirstElementAt(station.Entrance); - if (tileElement != nullptr) - { - do - { - if (tileElement->getType() != TileElementType::entrance) - continue; - if (tileElement->getBaseZ() != mapLocation.z) - continue; - - int32_t direction = tileElement->getDirection(); - FootpathChainRideQueue(id, getStationIndex(&station), mapLocation, tileElement, DirectionReverse(direction)); - } while (!(tileElement++)->isLastForTile()); - } - } -} - -/** - * - * rct2: 0x006D3319 - */ -static ResultWithMessage RideCheckBlockBrakes(const CoordsXYE& input, CoordsXYE* output, bool shouldCheckCompleteCircuit) -{ - if (input.element == nullptr || input.element->getType() != TileElementType::track) - return { false }; - - RideId rideIndex = input.element->asTrack()->GetRideIndex(); - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && _currentRideIndex == rideIndex) - RideConstructionInvalidateCurrentTrack(); - - TrackCircuitIterator it; - trackCircuitIteratorBegin(&it, input); - while (trackCircuitIteratorNext(&it)) - { - if (trackTypeIsBlockBrakes(it.current.element->asTrack()->GetTrackType())) - { - auto type = it.last.element->asTrack()->GetTrackType(); - if (type == TrackElemType::endStation) - { - *output = it.current; - return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_STATION }; - } - if (trackTypeIsBlockBrakes(type)) - { - *output = it.current; - return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_EACH_OTHER }; - } - if (it.last.element->asTrack()->HasChain() && type != TrackElemType::leftCurvedLiftHill - && type != TrackElemType::rightCurvedLiftHill) - { - *output = it.current; - return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_THE_TOP_OF_THIS_LIFT_HILL }; - } - } - } - if (!it.looped && shouldCheckCompleteCircuit) - { - // Not sure why this is the case... - *output = it.last; - return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_STATION }; - } - - return { true }; -} - -/** - * Iterates along the track until an inversion (loop, corkscrew, barrel roll etc.) track piece is reached. - * @param input The start track element and position. - * @param output The first track element and position which is classified as an inversion. - * @returns true if an inversion track piece is found, otherwise false. - * rct2: 0x006CB149 - */ -static bool RideCheckTrackContainsInversions(const CoordsXYE& input, CoordsXYE* output) -{ - if (input.element == nullptr) - return false; - - const auto* trackElement = input.element->asTrack(); - if (trackElement == nullptr) - return false; - - RideId rideIndex = trackElement->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride != nullptr) - { - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - return true; - } - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) - { - RideConstructionInvalidateCurrentTrack(); - } - - bool moveSlowIt = true; - TrackCircuitIterator it, slowIt; - trackCircuitIteratorBegin(&it, input); - slowIt = it; - - while (trackCircuitIteratorNext(&it)) - { - auto trackType = it.current.element->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - if (ted.flags.has(TrackElementFlag::inversionToNormal)) - { - *output = it.current; - return true; - } - - // Prevents infinite loops - moveSlowIt = !moveSlowIt; - if (moveSlowIt) - { - trackCircuitIteratorNext(&slowIt); - if (trackCircuitIteratorsMatch(&it, &slowIt)) - { - return false; - } - } - } - return false; -} - -/** - * Iterates along the track until a banked track piece is reached. - * @param input The start track element and position. - * @param output The first track element and position which is banked. - * @returns true if a banked track piece is found, otherwise false. - * rct2: 0x006CB1D3 - */ -static bool RideCheckTrackContainsBanked(const CoordsXYE& input, CoordsXYE* output) -{ - if (input.element == nullptr) - return false; - - const auto* trackElement = input.element->asTrack(); - if (trackElement == nullptr) - return false; - - auto rideIndex = trackElement->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return false; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - return true; - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) - { - RideConstructionInvalidateCurrentTrack(); - } - - bool moveSlowIt = true; - TrackCircuitIterator it, slowIt; - trackCircuitIteratorBegin(&it, input); - slowIt = it; - - while (trackCircuitIteratorNext(&it)) - { - auto trackType = it.current.element->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - if (ted.flags.has(TrackElementFlag::banked)) - { - *output = it.current; - return true; - } - - // Prevents infinite loops - moveSlowIt = !moveSlowIt; - if (moveSlowIt) - { - trackCircuitIteratorNext(&slowIt); - if (trackCircuitIteratorsMatch(&it, &slowIt)) - { - return false; - } - } - } - return false; -} - -/** - * - * rct2: 0x006CB25D - */ -static int32_t RideCheckStationLength(const CoordsXYE& input, CoordsXYE* output) -{ - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 - && _currentRideIndex == input.element->asTrack()->GetRideIndex()) - { - RideConstructionInvalidateCurrentTrack(); - } - - output->x = input.x; - output->y = input.y; - output->element = input.element; - TrackBeginEnd trackBeginEnd; - while (trackBlockGetPrevious(*output, &trackBeginEnd)) - { - output->x = trackBeginEnd.begin_x; - output->y = trackBeginEnd.begin_y; - output->element = trackBeginEnd.begin_element; - } - - int32_t num_station_elements = 0; - CoordsXYE last_good_station = *output; - - do - { - const auto& ted = GetTrackElementDescriptor(output->element->asTrack()->GetTrackType()); - if (ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - { - num_station_elements++; - last_good_station = *output; - } - else - { - if (num_station_elements == 0) - continue; - if (num_station_elements == 1) - { - return 0; - } - num_station_elements = 0; - } - } while (trackBlockGetNext(output, output, nullptr, nullptr)); - - // Prevent returning a pointer to a map element with no track. - *output = last_good_station; - if (num_station_elements == 1) - return 0; - - return 1; -} - -/** - * - * rct2: 0x006CB2DA - */ -static bool RideCheckStartAndEndIsStation(const CoordsXYE& input) -{ - CoordsXYE trackBack, trackFront; - - RideId rideIndex = input.element->asTrack()->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return false; - - auto* windowMgr = Ui::GetWindowManager(); - auto w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) - { - RideConstructionInvalidateCurrentTrack(); - } - - // Check back of the track - trackGetBack(input, &trackBack); - auto trackType = trackBack.element->asTrack()->GetTrackType(); - const auto& tedBack = GetTrackElementDescriptor(trackType); - if (!tedBack.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - { - return false; - } - ride->chairliftBullwheelLocation[0] = TileCoordsXYZ{ CoordsXYZ{ trackBack.x, trackBack.y, trackBack.element->getBaseZ() } }; - - // Check front of the track - trackGetFront(input, &trackFront); - trackType = trackFront.element->asTrack()->GetTrackType(); - const auto& tedFront = GetTrackElementDescriptor(trackType); - if (!tedFront.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - { - return false; - } - ride->chairliftBullwheelLocation[1] = TileCoordsXYZ{ CoordsXYZ{ trackFront.x, trackFront.y, - trackFront.element->getBaseZ() } }; - return true; -} - -/** - * Sets the position and direction of the returning point on the track of a boat hire ride. This will either be the end of the - * station or the last track piece from the end of the direction. - * rct2: 0x006B4D39 - */ -static void RideSetBoatHireReturnPoint(Ride& ride, const CoordsXYE& startElement) -{ - auto trackType = TrackElemType::none; - auto returnPos = startElement; - int32_t startX = returnPos.x; - int32_t startY = returnPos.y; - TrackBeginEnd trackBeginEnd; - while (trackBlockGetPrevious(returnPos, &trackBeginEnd)) - { - // If previous track is back to the starting x, y, then break loop (otherwise possible infinite loop) - if (trackType != TrackElemType::none && startX == trackBeginEnd.begin_x && startY == trackBeginEnd.begin_y) - break; - - auto trackCoords = CoordsXYZ{ trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }; - int32_t direction = trackBeginEnd.begin_direction; - trackType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); - auto newCoords = GetTrackElementOriginAndApplyChanges( - { trackCoords, static_cast(direction) }, trackType, 0, &returnPos.element, {}); - returnPos = newCoords.has_value() ? CoordsXYE{ newCoords.value(), returnPos.element } - : CoordsXYE{ trackCoords, returnPos.element }; - }; - - trackType = returnPos.element->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - int32_t elementReturnDirection = ted.coordinates.rotationBegin; - ride.boatHireReturnDirection = returnPos.element->getDirectionWithOffset(elementReturnDirection); - ride.boatHireReturnPosition = TileCoordsXY{ returnPos }; -} - -/** - * - * rct2: 0x006B4D39 - */ -static void RideSetMazeEntranceExitPoints(Ride& ride) -{ - // Needs room for an entrance and an exit per station, plus one position for the list terminator. - TileCoordsXYZD positions[(Limits::kMaxStationsPerRide * 2) + 1]; - - // Create a list of all the entrance and exit positions - TileCoordsXYZD* position = positions; - for (const auto& station : ride.getStations()) - { - if (!station.Entrance.IsNull()) - { - *position++ = station.Entrance; - } - if (!station.Exit.IsNull()) - { - *position++ = station.Exit; - } - } - position->SetNull(); - - // Enumerate entrance and exit positions - for (position = positions; !position->IsNull(); position++) - { - auto entranceExitMapPos = position->ToCoordsXYZ(); - - TileElement* tileElement = MapGetFirstElementAt(*position); - do - { - if (tileElement == nullptr) - break; - if (tileElement->getType() != TileElementType::entrance) - continue; - if (tileElement->asEntrance()->GetEntranceType() != ENTRANCE_TYPE_RIDE_ENTRANCE - && tileElement->asEntrance()->GetEntranceType() != ENTRANCE_TYPE_RIDE_EXIT) - { - continue; - } - if (tileElement->getBaseZ() != entranceExitMapPos.z) - continue; - - MazeEntranceHedgeRemoval({ entranceExitMapPos, tileElement }); - } while (!(tileElement++)->isLastForTile()); - } -} - -void SetBrakeClosedMultiTile(TrackElement& trackElement, const CoordsXY& trackLocation, bool isClosed) -{ - switch (trackElement.GetTrackType()) - { - case TrackElemType::diagUp25ToFlat: - case TrackElemType::diagUp60ToFlat: - case TrackElemType::cableLiftHill: - case TrackElemType::diagBrakes: - case TrackElemType::diagBlockBrakes: - GetTrackElementOriginAndApplyChanges( - { trackLocation, trackElement.getBaseZ(), trackElement.getDirection() }, trackElement.GetTrackType(), isClosed, - nullptr, { TrackElementSetFlag::brakeClosed }); - break; - default: - trackElement.SetBrakeClosed(isClosed); - } -} - -/** - * Opens all block brakes of a ride. - * rct2: 0x006B4E6B - */ -static void RideOpenBlockBrakes(const CoordsXYE& startElement) -{ - CoordsXYE currentElement = startElement; - do - { - auto trackType = currentElement.element->asTrack()->GetTrackType(); - switch (trackType) - { - case TrackElemType::blockBrakes: - case TrackElemType::diagBlockBrakes: - BlockBrakeSetLinkedBrakesClosed( - CoordsXYZ(currentElement.x, currentElement.y, currentElement.element->getBaseZ()), - *currentElement.element->asTrack(), false); - [[fallthrough]]; - case TrackElemType::diagUp25ToFlat: - case TrackElemType::diagUp60ToFlat: - case TrackElemType::cableLiftHill: - case TrackElemType::endStation: - case TrackElemType::up25ToFlat: - case TrackElemType::up60ToFlat: - SetBrakeClosedMultiTile(*currentElement.element->asTrack(), { currentElement.x, currentElement.y }, false); - break; - default: - break; - } - } while (trackBlockGetNext(¤tElement, ¤tElement, nullptr, nullptr) - && currentElement.element != startElement.element); -} - -/** - * Set the open status of brakes adjacent to the block brake - */ -void BlockBrakeSetLinkedBrakesClosed(const CoordsXYZ& vehicleTrackLocation, TrackElement& trackElement, bool isClosed) -{ - uint8_t brakeSpeed = trackElement.GetBrakeBoosterSpeed(); - - auto tileElement = reinterpret_cast(&trackElement); - auto location = vehicleTrackLocation; - TrackBeginEnd trackBeginEnd, slowTrackBeginEnd; - TileElement slowTileElement = *tileElement; - bool counter = true; - CoordsXY slowLocation = location; - do - { - if (!trackBlockGetPrevious({ location, tileElement }, &trackBeginEnd)) - { - return; - } - if (trackBeginEnd.begin_x == vehicleTrackLocation.x && trackBeginEnd.begin_y == vehicleTrackLocation.y - && tileElement == trackBeginEnd.begin_element) - { - return; - } - - location.x = trackBeginEnd.end_x; - location.y = trackBeginEnd.end_y; - location.z = trackBeginEnd.begin_z; - tileElement = trackBeginEnd.begin_element; - - if (trackTypeIsBrakes(tileElement->asTrack()->GetTrackType())) - { - SetBrakeClosedMultiTile( - *tileElement->asTrack(), { trackBeginEnd.begin_x, trackBeginEnd.begin_y }, - (tileElement->asTrack()->GetBrakeBoosterSpeed() >= brakeSpeed) || isClosed); - } - - // prevent infinite loop - counter = !counter; - if (counter) - { - trackBlockGetPrevious({ slowLocation, &slowTileElement }, &slowTrackBeginEnd); - slowLocation.x = slowTrackBeginEnd.end_x; - slowLocation.y = slowTrackBeginEnd.end_y; - slowTileElement = *(slowTrackBeginEnd.begin_element); - if (slowLocation == location && slowTileElement.getBaseZ() == tileElement->getBaseZ() - && slowTileElement.getType() == tileElement->getType() - && slowTileElement.getDirection() == tileElement->getDirection()) - { - return; - } - } - } while (trackTypeIsBrakes(trackBeginEnd.begin_element->asTrack()->GetTrackType())); -} - -/** - * - * rct2: 0x006B4D26 - */ -static void RideSetStartFinishPoints(RideId rideIndex, const CoordsXYE& startElement) -{ - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return; - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - RideSetMazeEntranceExitPoints(*ride); - else if (rtd.specialType == RtdSpecialType::boatHire) - RideSetBoatHireReturnPoint(*ride, startElement); - - if (ride->isBlockSectioned() && !ride->flags.has(RideFlag::onTrack)) - { - RideOpenBlockBrakes(startElement); - } -} - -/** - * - * rct2: 0x0069ED9E - */ -static int32_t count_free_misc_sprite_slots() -{ - auto& gameState = getGameState(); - int32_t miscSpriteCount = gameState.entities.GetMiscEntityCount(); - int32_t remainingSpriteCount = gameState.entities.GetNumFreeEntities(); - return std::max(0, miscSpriteCount + remainingSpriteCount - 300); -} - -static constexpr CoordsXY word_9A3AB4[4] = { - { 0, 0 }, - { 0, -96 }, - { -96, -96 }, - { -96, 0 }, -}; - -// clang-format off -static constexpr CoordsXY word_9A2A60[] = { - { 0, 16 }, - { 16, 31 }, - { 31, 16 }, - { 16, 0 }, - { 16, 16 }, - { 64, 64 }, - { 64, -32 }, - { -32, -32 }, - { -32, 64 }, -}; -// clang-format on - -/** - * - * rct2: 0x006DD90D - */ -static Vehicle* VehicleCreateCar( - Ride& ride, int32_t carEntryIndex, int32_t carIndex, int32_t vehicleIndex, const CoordsXYZ& carPosition, - int32_t* remainingDistance, TrackElement* trackElement) -{ - if (trackElement == nullptr) - return nullptr; - - auto rideEntry = ride.getRideEntry(); - if (rideEntry == nullptr) - return nullptr; - - auto& carEntry = rideEntry->Cars[carEntryIndex]; - - auto* vehicle = getGameState().entities.CreateEntity(); - if (vehicle == nullptr) - return nullptr; - - vehicle->ride = ride.id; - vehicle->ride_subtype = ride.subtype; - - vehicle->vehicle_type = carEntryIndex; - vehicle->SubType = carIndex == 0 ? Vehicle::Type::head : Vehicle::Type::tail; - vehicle->var_44 = Numerics::ror32(carEntry.spacing, 10) & 0xFFFF; - - const auto halfSpacing = carEntry.spacing >> 1; - *remainingDistance -= halfSpacing; - vehicle->remaining_distance = *remainingDistance; - - if (!carEntry.flags.has(CarEntryFlag::isGoKart)) - { - *remainingDistance -= halfSpacing; - } - - // Loc6DD9A5: - vehicle->spriteData.width = carEntry.spriteWidth; - vehicle->spriteData.heightMin = carEntry.spriteHeightNegative; - vehicle->spriteData.heightMax = carEntry.spriteHeightPositive; - vehicle->mass = carEntry.car_mass; - vehicle->num_seats = carEntry.num_seats; - vehicle->speed = carEntry.powered_max_speed; - vehicle->powered_acceleration = carEntry.powered_acceleration; - vehicle->velocity = 0; - vehicle->acceleration = 0; - vehicle->SwingSprite = 0; - vehicle->SwingPosition = 0; - vehicle->SwingSpeed = 0; - vehicle->restraints_position = 0; - vehicle->spin_sprite = 0; - vehicle->spin_speed = 0; - vehicle->sound2_flags = 0; - vehicle->sound1_id = Audio::SoundId::null; - vehicle->sound2_id = Audio::SoundId::null; - vehicle->next_vehicle_on_train = EntityId::GetNull(); - vehicle->CollisionDetectionTimer = 0; - vehicle->animation_frame = 0; - vehicle->animationState = 0; - vehicle->scream_sound_id = Audio::SoundId::null; - vehicle->pitch = VehiclePitch::flat; - vehicle->roll = VehicleRoll::unbanked; - vehicle->target_seat_rotation = 4; - vehicle->seat_rotation = 4; - for (size_t i = 0; i < std::size(vehicle->peep); i++) - { - vehicle->peep[i] = EntityId::GetNull(); - } - - const auto& rtd = ride.getRideTypeDescriptor(); - if (carEntry.flags.has(CarEntryFlag::useDodgemCarPlacement)) - { - // Loc6DDCA4: - vehicle->TrackSubposition = VehicleTrackSubposition::standard; - int32_t direction = trackElement->getDirection(); - auto dodgemPos = carPosition + CoordsXYZ{ word_9A3AB4[direction], 0 }; - vehicle->TrackLocation = dodgemPos; - vehicle->current_station = trackElement->GetStationIndex(); - - dodgemPos.z += rtd.Heights.VehicleZOffset; - - vehicle->SetTrackDirection(0); - vehicle->SetTrackType(trackElement->GetTrackType()); - vehicle->track_progress = 0; - vehicle->SetState(Vehicle::Status::movingToEndOfStation); - vehicle->flags.clearAll(); - - CoordsXY chosenLoc; - auto numAttempts = 0; - // Loc6DDD26: - do - { - numAttempts++; - // This can happen when trying to spawn dozens of cars in a tiny area. - if (numAttempts > 10000) - return nullptr; - - vehicle->orientation = ScenarioRand() & 0x1E; - chosenLoc.y = dodgemPos.y + (ScenarioRand() & 0xFF); - chosenLoc.x = dodgemPos.x + (ScenarioRand() & 0xFF); - } while (vehicle->DodgemsCarWouldCollideAt(chosenLoc).has_value()); - - vehicle->moveToAndUpdateSpatialIndex({ chosenLoc, dodgemPos.z }); - } - else - { - VehicleTrackSubposition subposition = VehicleTrackSubposition::standard; - if (carEntry.flags.has(CarEntryFlag::isChairlift)) - { - subposition = VehicleTrackSubposition::chairliftGoingOut; - } - - if (carEntry.flags.has(CarEntryFlag::isGoKart)) - { - // Choose which lane Go Kart should start in - subposition = VehicleTrackSubposition::goKartsLeftLane; - if (vehicleIndex & 1) - { - subposition = VehicleTrackSubposition::goKartsRightLane; - } - } - if (carEntry.flags.has(CarEntryFlag::isMiniGolf)) - { - subposition = VehicleTrackSubposition::miniGolfStart9; - vehicle->var_D3 = 0; - vehicle->mini_golf_current_animation = MiniGolfAnimation::walk; - vehicle->miniGolfFlags.clearAll(); - } - if (carEntry.flags.has(CarEntryFlag::isReverserCoasterBogie)) - { - if (vehicle->IsHead()) - { - subposition = VehicleTrackSubposition::reverserRCFrontBogie; - } - } - if (carEntry.flags.has(CarEntryFlag::isReverserCoasterPassengerCar)) - { - subposition = VehicleTrackSubposition::reverserRCRearBogie; - } - vehicle->TrackSubposition = subposition; - - auto chosenLoc = carPosition; - vehicle->TrackLocation = chosenLoc; - - int32_t direction = trackElement->getDirection(); - vehicle->orientation = direction << 3; - - if (ride.getRideTypeDescriptor().specialType == RtdSpecialType::spaceRings) - { - direction = 4; - } - else - { - if (rtd.flags.has(RtdFlag::vehicleIsIntegral)) - { - if (rtd.StartTrackPiece != TrackElemType::flatTrack1x4B) - { - if (rtd.StartTrackPiece != TrackElemType::flatTrack1x4A) - { - if (ride.getRideTypeDescriptor().specialType == RtdSpecialType::enterprise) - { - direction += 5; - } - else - { - direction = 4; - } - } - } - } - } - - chosenLoc += CoordsXYZ{ word_9A2A60[direction], rtd.Heights.VehicleZOffset }; - - vehicle->current_station = trackElement->GetStationIndex(); - - vehicle->moveTo(chosenLoc); - vehicle->SetTrackType(trackElement->GetTrackType()); - vehicle->SetTrackDirection(vehicle->orientation >> 3); - vehicle->track_progress = 31; - if (carEntry.flags.has(CarEntryFlag::isMiniGolf)) - { - vehicle->track_progress = 15; - } - vehicle->flags = { VehicleFlag::collisionDisabled }; - if (carEntry.flags.has(CarEntryFlag::hasInvertedSpriteSet)) - { - if (trackElement->IsInverted()) - { - vehicle->flags.set(VehicleFlag::carIsInverted); - } - } - vehicle->SetState(Vehicle::Status::movingToEndOfStation); - - if (ride.flags.has(RideFlag::reversedTrains)) - { - vehicle->SubType = carIndex == (ride.numCarsPerTrain - 1) ? Vehicle::Type::head : Vehicle::Type::tail; - vehicle->flags.set(VehicleFlag::carIsReversed); - } - } - - // Loc6DDD5E: - vehicle->num_peeps = 0; - vehicle->next_free_seat = 0; - vehicle->BoatLocation.SetNull(); - return vehicle; -} - -/** - * - * rct2: 0x006DD84C - */ -static TrainReference VehicleCreateTrain( - Ride& ride, const CoordsXYZ& trainPos, int32_t vehicleIndex, int32_t* remainingDistance, TrackElement* trackElement) -{ - TrainReference train = { nullptr, nullptr }; - bool isReversed = ride.flags.has(RideFlag::reversedTrains); - - for (int32_t carIndex = 0; carIndex < ride.numCarsPerTrain; carIndex++) - { - auto carSpawnIndex = (isReversed) ? (ride.numCarsPerTrain - 1) - carIndex : carIndex; - - auto vehicle = RideEntryGetVehicleAtPosition(ride.subtype, ride.numCarsPerTrain, carSpawnIndex); - auto car = VehicleCreateCar(ride, vehicle, carSpawnIndex, vehicleIndex, trainPos, remainingDistance, trackElement); - if (car == nullptr) - break; - - if (carIndex == 0) - { - train.head = car; - } - else - { - // Link the previous car with this car - train.tail->next_vehicle_on_train = car->id; - train.tail->next_vehicle_on_ride = car->id; - car->prev_vehicle_on_ride = train.tail->id; - } - train.tail = car; - } - - return train; -} - -static bool VehicleCreateTrains(Ride& ride, const CoordsXYZ& trainsPos, TrackElement* trackElement, int16_t numberOfTrains) -{ - TrainReference firstTrain = {}; - TrainReference lastTrain = {}; - int32_t remainingDistance = 0; - bool allTrainsCreated = true; - - for (int32_t vehicleIndex = 0; vehicleIndex < numberOfTrains; vehicleIndex++) - { - if (ride.isBlockSectioned()) - { - remainingDistance = 0; - } - TrainReference train = VehicleCreateTrain(ride, trainsPos, vehicleIndex, &remainingDistance, trackElement); - if (train.head == nullptr || train.tail == nullptr) - { - allTrainsCreated = false; - continue; - } - - if (vehicleIndex == 0) - { - firstTrain = train; - } - else - { - // Link the end of the previous train with the front of this train - lastTrain.tail->next_vehicle_on_ride = train.head->id; - train.head->prev_vehicle_on_ride = lastTrain.tail->id; - } - lastTrain = train; - - for (int32_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) - { - if (ride.vehicles[i].IsNull()) - { - ride.vehicles[i] = train.head->id; - break; - } - } - } - - // Link the first train and last train together. Nullptr checks are there to keep Clang happy. - if (lastTrain.tail != nullptr) - firstTrain.head->prev_vehicle_on_ride = lastTrain.tail->id; - if (firstTrain.head != nullptr) - lastTrain.tail->next_vehicle_on_ride = firstTrain.head->id; - - return allTrainsCreated; -} - -/** - * - * rct2: 0x006DDE9E - */ -static void RidecreateVehiclesFindFirstBlock(const Ride& ride, CoordsXYE* outXYElement) -{ - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[0]); - if (vehicle == nullptr) - return; - - auto curTrackPos = vehicle->TrackLocation; - auto curTrackElement = MapGetTrackElementAt(curTrackPos); - - assert(curTrackElement != nullptr); - - CoordsXY trackPos = curTrackPos; - auto trackElement = curTrackElement; - TrackBeginEnd trackBeginEnd; - while (trackBlockGetPrevious({ trackPos, reinterpret_cast(trackElement) }, &trackBeginEnd)) - { - trackPos = { trackBeginEnd.end_x, trackBeginEnd.end_y }; - trackElement = trackBeginEnd.begin_element->asTrack(); - if (trackPos == curTrackPos && trackElement == curTrackElement) - { - break; - } - - auto trackType = trackElement->GetTrackType(); - switch (trackType) - { - case TrackElemType::diagUp25ToFlat: - case TrackElemType::diagUp60ToFlat: - if (!trackElement->HasChain()) - { - break; - } - [[fallthrough]]; - case TrackElemType::diagBlockBrakes: - { - TileElement* tileElement = MapGetTrackElementAtOfTypeSeq( - { trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }, trackType, 0); - - if (tileElement != nullptr) - { - outXYElement->x = trackBeginEnd.begin_x; - outXYElement->y = trackBeginEnd.begin_y; - outXYElement->element = tileElement; - return; - } - break; - } - case TrackElemType::up25ToFlat: - case TrackElemType::up60ToFlat: - if (!trackElement->HasChain()) - { - break; - } - [[fallthrough]]; - case TrackElemType::endStation: - case TrackElemType::blockBrakes: - *outXYElement = { trackPos, reinterpret_cast(trackElement) }; - return; - default: - break; - } - } - - outXYElement->x = curTrackPos.x; - outXYElement->y = curTrackPos.y; - outXYElement->element = reinterpret_cast(curTrackElement); -} - -/** - * Create and place the rides vehicles - * rct2: 0x006DD84C - */ -ResultWithMessage Ride::createVehicles(const CoordsXYE& element, bool isApplying, bool isSimulating) -{ - updateMaxVehicles(); - if (subtype == kObjectEntryIndexNull) - { return { true }; } - // Check if there are enough free sprite slots for all the vehicles - int32_t numberOfTrains = numTrains; - if (isBlockSectioned() && isSimulating) + /** + * returns stationIndex of first station on success + * STATION_INDEX_NULL on failure. + */ + static StationIndexWithMessage RideModeCheckStationPresent(const Ride& ride) { - numberOfTrains = 1; - } - int32_t totalCars = numberOfTrains * numCarsPerTrain; - if (totalCars > count_free_misc_sprite_slots()) - { - return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; + auto stationIndex = RideGetFirstValidStationStart(ride); + + if (stationIndex.IsNull()) + { + const auto& rtd = ride.getRideTypeDescriptor(); + if (!rtd.flags.has(RtdFlag::hasTrack)) + return { StationIndex::GetNull(), STR_NOT_YET_CONSTRUCTED }; + + if (rtd.specialType == RtdSpecialType::maze) + return { StationIndex::GetNull(), STR_NOT_YET_CONSTRUCTED }; + + return { StationIndex::GetNull(), STR_REQUIRES_A_STATION_PLATFORM }; + } + + return { stationIndex }; } - if (!isApplying) + /** + * + * rct2: 0x006B5872 + */ + static ResultWithMessage RideCheckForEntranceExit(RideId rideIndex) { + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return { false }; + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + return { true }; + + uint8_t entrance = 0; + uint8_t exit = 0; + for (const auto& station : ride->getStations()) + { + if (station.Start.IsNull()) + continue; + + if (!station.Entrance.IsNull()) + { + entrance = 1; + } + + if (!station.Exit.IsNull()) + { + exit = 1; + } + + // If station start and no entrance/exit + // Sets same error message as no entrance + if (station.Exit.IsNull() && station.Entrance.IsNull()) + { + entrance = 0; + break; + } + } + + if (entrance == 0) + { + return { false, STR_ENTRANCE_NOT_YET_BUILT }; + } + + if (exit == 0) + { + return { false, STR_EXIT_NOT_YET_BUILT }; + } + return { true }; } - auto* trackElement = element.element->asTrack(); - auto vehiclePos = CoordsXYZ{ element, element.element->getBaseZ() }; - int32_t direction = trackElement->getDirection(); - - // - if (mode == RideMode::stationToStation) + /** + * Calls FootpathChainRideQueue for all entrances of the ride + * rct2: 0x006B5952 + */ + void Ride::chainQueues() const { - vehiclePos -= CoordsXYZ{ CoordsDirectionDelta[direction], 0 }; - - trackElement = MapGetTrackElementAt(vehiclePos); - - vehiclePos.z = trackElement->getBaseZ(); - } - - if (!VehicleCreateTrains(*this, vehiclePos, trackElement, numberOfTrains)) - { - // This flag is needed for Ride::removeVehicles() - flags.set(RideFlag::onTrack); - removeVehicles(); - return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; - } - // return true; - - // Initialise station departs - // 006DDDD0: - flags.set(RideFlag::onTrack); - for (int32_t i = 0; i < Limits::kMaxStationsPerRide; i++) - { - stations[i].Depart = (stations[i].Depart & kStationDepartFlag) | 1; - } - - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::spaceRings && !rtd.flags.has(RtdFlag::vehicleIsIntegral)) - { - if (isBlockSectioned() && !isSimulating) + for (const auto& station : stations) { - CoordsXYE firstBlock{}; - RidecreateVehiclesFindFirstBlock(*this, &firstBlock); - moveTrainsToBlockBrakes( - { firstBlock.x, firstBlock.y, firstBlock.element->getBaseZ() }, *firstBlock.element->asTrack()); - } - else - { - for (int32_t i = 0; i < numTrains; i++) + if (station.Entrance.IsNull()) + continue; + + auto mapLocation = station.Entrance.ToCoordsXYZ(); + + // This will fire for every entrance on this x, y and z, regardless whether that actually belongs to + // the ride or not. + TileElement* tileElement = MapGetFirstElementAt(station.Entrance); + if (tileElement != nullptr) { - Vehicle* vehicle = getGameState().entities.GetEntity(vehicles[i]); - if (vehicle == nullptr) + do { - continue; - } + if (tileElement->getType() != TileElementType::entrance) + continue; + if (tileElement->getBaseZ() != mapLocation.z) + continue; - auto carEntry = vehicle->Entry(); - - if (!carEntry->flags.has(CarEntryFlag::useDodgemCarPlacement)) - { - vehicle->UpdateTrackMotion(nullptr); - } - - vehicle->EnableCollisionsForTrain(); - } - } - } - RideUpdateVehicleColours(*this); - return { true }; -} - -/** - * Move all the trains so each one will be placed at the block brake of a different block. - * The first vehicle will placed into the first block and all other vehicles in the blocks - * preceding that block. - * rct2: 0x006DDF9C - */ -void Ride::moveTrainsToBlockBrakes(const CoordsXYZ& firstBlockPosition, TrackElement& firstBlock) -{ - // If the ride has a cable lift, we don't want to fetch the cable lift element and the block preceding it - TrackElement* cableLiftTileElement = nullptr; - TrackElement* cableLiftPreviousBlock = nullptr; - if (flags.has(RideFlag::cableLiftHillComponentUsed)) - { - cableLiftTileElement = MapGetTrackElementAt(cableLiftLoc); - if (cableLiftTileElement != nullptr) - { - CoordsXYZ location = cableLiftLoc; - cableLiftPreviousBlock = trackGetPreviousBlock(location, reinterpret_cast(cableLiftTileElement)); - } - } - - for (int32_t i = 0; i < numTrains; i++) - { - auto train = getGameState().entities.GetEntity(vehicles[i]); - if (train == nullptr) - continue; - - // At this point, all vehicles have state of MovingToEndOfStation, which slowly moves forward at a constant speed - // regardless of incline. The first vehicle stops at the station immediately, while all other vehicles seek forward - // until they reach a closed block brake. The block brake directly before the station is set to closed every frame - // because the trains will open the block brake when the tail leaves the station. Brakes have no effect at this time, so - // do not set linked brakes when closing the first block. - train->UpdateTrackMotion(nullptr); - - if (i == 0) - { - train->EnableCollisionsForTrain(); - continue; - } - - size_t numIterations = 0; - do - { - // Fixes both freezing issues in #15503. - // TODO: refactor the code so a tortoise-and-hare algorithm can be used. - if (numIterations++ > 1000000) - { - break; - } - - // Setting the first block before the cable lift to the same state as the cable lift ensures that any train which - // would be placed on the cable lift will instead stop on the block before it. As there can only be one cable lift - // per ride and there must always be at least one block left free, there will be enough blocks remaining. This fixes - // the bug in #1122. - if (cableLiftTileElement != nullptr && cableLiftPreviousBlock != nullptr) - { - cableLiftPreviousBlock->SetBrakeClosed(cableLiftTileElement->IsBrakeClosed()); - } - firstBlock.SetBrakeClosed(true); - for (Vehicle* car = train; car != nullptr; - car = getGameState().entities.GetEntity(car->next_vehicle_on_train)) - { - car->velocity = 0; - car->acceleration = 0; - car->SwingSprite = 0; - car->remaining_distance += 13962; - } - } while (!(train->UpdateTrackMotion(nullptr) & VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE)); - - // All vehicles are in position, set the block brake directly before the station one last time and make sure the brakes - // are set appropriately - SetBrakeClosedMultiTile(firstBlock, firstBlockPosition, true); - if (trackTypeIsBlockBrakes(firstBlock.GetTrackType())) - { - BlockBrakeSetLinkedBrakesClosed(firstBlockPosition, firstBlock, true); - } - for (Vehicle* car = train; car != nullptr; car = getGameState().entities.GetEntity(car->next_vehicle_on_train)) - { - car->flags.unset(VehicleFlag::collisionDisabled); - car->SetState(Vehicle::Status::travelling, car->sub_state); - if ((car->GetTrackType()) == TrackElemType::endStation) - { - car->SetState(Vehicle::Status::movingToEndOfStation, car->sub_state); + int32_t direction = tileElement->getDirection(); + FootpathChainRideQueue( + id, getStationIndex(&station), mapLocation, tileElement, DirectionReverse(direction)); + } while (!(tileElement++)->isLastForTile()); } } } - // After all trains are in position, set the block preceding the cable lift to open. - if (cableLiftPreviousBlock != nullptr) + /** + * + * rct2: 0x006D3319 + */ + static ResultWithMessage RideCheckBlockBrakes(const CoordsXYE& input, CoordsXYE* output, bool shouldCheckCompleteCircuit) { - cableLiftPreviousBlock->SetBrakeClosed(false); - } -} + if (input.element == nullptr || input.element->getType() != TileElementType::track) + return { false }; -static bool RideGetStationTile(const Ride& ride, CoordsXYE* output) -{ - for (const auto& station : ride.getStations()) - { - CoordsXYZ trackStart = station.GetStart(); - if (trackStart.IsNull()) - continue; + RideId rideIndex = input.element->asTrack()->GetRideIndex(); - TileElement* tileElement = MapGetTrackElementAtOfType(trackStart, TrackElemType::endStation); - if (tileElement == nullptr) - continue; - - *output = { trackStart.x, trackStart.y, tileElement }; - return true; - } - return false; -} - -/** - * Checks and initialises the cable lift track returns false if unable to find - * appropriate track. - * rct2: 0x006D31A6 - */ -static ResultWithMessage RideInitialiseCableLiftTrack(const Ride& ride, bool isApplying) -{ - // Despawn existing cable lift tiles - CoordsXYE stationTile; - if (!RideGetStationTile(ride, &stationTile)) - return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; - - if (isApplying) - { - // In case circuit is incomplete, find the start of the track in order to ensure all tiles connected - // to the station are cleared - RideGetStartOfTrack(&stationTile); + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && _currentRideIndex == rideIndex) + RideConstructionInvalidateCurrentTrack(); TrackCircuitIterator it; - trackCircuitIteratorBegin(&it, stationTile); + trackCircuitIteratorBegin(&it, input); while (trackCircuitIteratorNext(&it)) { - TileElement* tileElement = it.current.element; - GetTrackElementOriginAndApplyChanges( - { { it.current, tileElement->getBaseZ() }, tileElement->getDirection() }, - tileElement->asTrack()->GetTrackType(), 0, &tileElement, { TrackElementSetFlag::cableLiftOff }); - } - } - - // Spawn new cable lift tiles - auto cableLiftTileElement = MapGetTrackElementAt(ride.cableLiftLoc); - CoordsXYE cableLiftCoords = { ride.cableLiftLoc, reinterpret_cast(cableLiftTileElement) }; - if (cableLiftTileElement == nullptr) - return { false }; - - TrackCircuitIterator it; - trackCircuitIteratorBegin(&it, cableLiftCoords); - while (trackCircuitIteratorPrevious(&it)) - { - TileElement* tileElement = it.current.element; - auto trackType = tileElement->asTrack()->GetTrackType(); - switch (trackType) - { - case TrackElemType::up25: - case TrackElemType::up60: - case TrackElemType::flatToUp25: - case TrackElemType::up25ToFlat: - case TrackElemType::up25ToUp60: - case TrackElemType::up60ToUp25: - case TrackElemType::flatToUp60LongBase: - case TrackElemType::flat: - if (isApplying) + if (trackTypeIsBlockBrakes(it.current.element->asTrack()->GetTrackType())) + { + auto type = it.last.element->asTrack()->GetTrackType(); + if (type == TrackElemType::endStation) { - GetTrackElementOriginAndApplyChanges( - { { it.current, tileElement->getBaseZ() }, tileElement->getDirection() }, trackType, 0, &tileElement, - { TrackElementSetFlag::cableLiftOn }); + *output = it.current; + return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_STATION }; } - break; - case TrackElemType::endStation: - case TrackElemType::blockBrakes: - return { true }; - default: - return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; + if (trackTypeIsBlockBrakes(type)) + { + *output = it.current; + return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_EACH_OTHER }; + } + if (it.last.element->asTrack()->HasChain() && type != TrackElemType::leftCurvedLiftHill + && type != TrackElemType::rightCurvedLiftHill) + { + *output = it.current; + return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_THE_TOP_OF_THIS_LIFT_HILL }; + } + } + } + if (!it.looped && shouldCheckCompleteCircuit) + { + // Not sure why this is the case... + *output = it.last; + return { false, STR_BLOCK_BRAKES_CANNOT_BE_USED_DIRECTLY_AFTER_STATION }; } - } - return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; -} -/** - * - * rct2: 0x006DF4D4 - */ -static ResultWithMessage RideCreateCableLift(RideId rideIndex, bool isApplying) -{ - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return { false }; - - if (ride->mode != RideMode::continuousCircuitBlockSectioned && ride->mode != RideMode::continuousCircuit) - { - return { false, STR_CABLE_LIFT_UNABLE_TO_WORK_IN_THIS_OPERATING_MODE }; - } - - if (ride->numCircuits > 1) - { - return { false, STR_MULTICIRCUIT_NOT_POSSIBLE_WITH_CABLE_LIFT_HILL }; - } - - if (count_free_misc_sprite_slots() <= 5) - { - return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; - } - - auto cableLiftInitialiseResult = RideInitialiseCableLiftTrack(*ride, isApplying); - if (!cableLiftInitialiseResult.Successful) - { - return { false, cableLiftInitialiseResult.Message }; - } - - if (!isApplying) - { return { true }; } - auto cableLiftLoc = ride->cableLiftLoc; - auto tileElement = MapGetTrackElementAt(cableLiftLoc); - int32_t direction = tileElement->getDirection(); - - Vehicle* head = nullptr; - Vehicle* tail = nullptr; - uint32_t ebx = 0; - for (int32_t i = 0; i < 5; i++) + /** + * Iterates along the track until an inversion (loop, corkscrew, barrel roll etc.) track piece is reached. + * @param input The start track element and position. + * @param output The first track element and position which is classified as an inversion. + * @returns true if an inversion track piece is found, otherwise false. + * rct2: 0x006CB149 + */ + static bool RideCheckTrackContainsInversions(const CoordsXYE& input, CoordsXYE* output) { - uint32_t edx = Numerics::ror32(0x15478, 10); - uint16_t var_44 = edx & 0xFFFF; - edx = Numerics::rol32(edx, 10) >> 1; - ebx -= edx; - int32_t remaining_distance = ebx; - ebx -= edx; + if (input.element == nullptr) + return false; - Vehicle* current = CableLiftSegmentCreate( - *ride, cableLiftLoc.x, cableLiftLoc.y, cableLiftLoc.z / 8, direction, var_44, remaining_distance, i == 0); - current->next_vehicle_on_train = EntityId::GetNull(); - if (i == 0) + const auto* trackElement = input.element->asTrack(); + if (trackElement == nullptr) + return false; + + RideId rideIndex = trackElement->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride != nullptr) { - head = current; - } - else - { - tail->next_vehicle_on_train = current->id; - tail->next_vehicle_on_ride = current->id; - current->prev_vehicle_on_ride = tail->id; - } - tail = current; - } - head->prev_vehicle_on_ride = tail->id; - tail->next_vehicle_on_ride = head->id; - - ride->flags.set(RideFlag::cableLift); - head->CableLiftUpdateTrackMotion(); - return { true }; -} - -/** - * Opens the construction window prompting to construct a missing entrance or exit. - * This will also move the screen to the first station missing the entrance or exit. - * rct2: 0x006B51C0 - */ -void Ride::constructMissingEntranceOrExit() const -{ - auto* w = WindowGetMain(); - if (w == nullptr) - return; - - int8_t entranceOrExit = -1; - const RideStation* incompleteStation = nullptr; - for (const auto& station : stations) - { - if (station.Start.IsNull()) - continue; - - if (station.Entrance.IsNull()) - { - entranceOrExit = WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE; - incompleteStation = &station; - break; - } - - if (station.Exit.IsNull()) - { - entranceOrExit = WC_RIDE_CONSTRUCTION__WIDX_EXIT; - incompleteStation = &station; - break; - } - } - - if (incompleteStation == nullptr) - { // No station with a missing entrance or exit was found - return; - } - - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::maze) - { - auto location = incompleteStation->GetStart(); - WindowScrollToLocation(*w, location); - - CoordsXYE trackElement; - RideTryGetOriginElement(*this, &trackElement); - findTrackGap(*this, trackElement, &trackElement); - int32_t ok = RideModify(trackElement); - if (ok == 0) - { - return; + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + return true; } auto* windowMgr = Ui::GetWindowManager(); - w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr) - w->onMouseUp(entranceOrExit); - } -} + WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) + { + RideConstructionInvalidateCurrentTrack(); + } -/** - * - * rct2: 0x006B528A - */ -static void RideScrollToTrackError(const CoordsXYE& trackElement) -{ - if (trackElement.element == nullptr) - return; - - auto* w = WindowGetMain(); - if (w != nullptr) - { - WindowScrollToLocation(*w, { trackElement, trackElement.element->getBaseZ() }); - RideModify(trackElement); - } -} - -/** - * - * rct2: 0x006B4F6B - */ -TrackElement* Ride::getOriginElement(StationIndex stationIndex) const -{ - auto stationLoc = getStation(stationIndex).Start; - TileElement* tileElement = MapGetFirstElementAt(stationLoc); - if (tileElement == nullptr) - return nullptr; - do - { - if (tileElement->getType() != TileElementType::track) - continue; - - auto* trackElement = tileElement->asTrack(); - const auto& ted = GetTrackElementDescriptor(trackElement->GetTrackType()); - if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - continue; - - if (trackElement->GetRideIndex() == id) - return trackElement; - } while (!(tileElement++)->isLastForTile()); - - return nullptr; -} - -ResultWithMessage Ride::test(bool isApplying) -{ - if (type == kRideTypeNull) - { - LOG_WARNING("Invalid ride type for ride %u", id.ToUnderlying()); - return { false }; - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByNumber(WindowClass::rideConstruction, id.ToUnderlying()); - - StationIndex stationIndex = {}; - auto message = changeStatusDoStationChecks(stationIndex); - if (!message.Successful) - { - return message; - } - - auto entranceExitCheck = RideCheckForEntranceExit(id); - if (!entranceExitCheck.Successful) - { - constructMissingEntranceOrExit(); - return { false, entranceExitCheck.Message }; - } - - CoordsXYE trackElement = {}; - message = changeStatusGetStartElement(stationIndex, trackElement); - if (!message.Successful) - { - return message; - } - - message = changeStatusCheckCompleteCircuit(trackElement); - if (!message.Successful) - { - return message; - } - - message = changeStatusCheckTrackValidity(trackElement, false); - if (!message.Successful) - { - return message; - } - - return changeStatusCreateVehicles(isApplying, trackElement, false); -} - -ResultWithMessage Ride::simulate(bool isApplying) -{ - CoordsXYE trackElement = {}; - if (type == kRideTypeNull) - { - LOG_WARNING("Invalid ride type for ride %u", id.ToUnderlying()); - return { false }; - } - - StationIndex stationIndex = {}; - auto message = changeStatusDoStationChecks(stationIndex); - if (!message.Successful) - { - return message; - } - - message = changeStatusGetStartElement(stationIndex, trackElement); - if (!message.Successful) - { - return message; - } - - message = changeStatusCheckTrackValidity(trackElement, true); - if (!message.Successful) - { - return message; - } - - return changeStatusCreateVehicles(isApplying, trackElement, true); -} - -/** - * - * rct2: 0x006B4EEA - */ -ResultWithMessage Ride::open(bool isApplying) -{ - // Check to see if construction tool is in use. If it is close the construction window - // to set the track to its final state and clean up ghosts. - // We can't just call close as it would cause a stack overflow during shop creation - // with auto open on. - if (isToolActive(WindowClass::rideConstruction, static_cast(id.ToUnderlying()))) - { - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->CloseByNumber(WindowClass::rideConstruction, id.ToUnderlying()); - } - - StationIndex stationIndex = {}; - auto message = changeStatusDoStationChecks(stationIndex); - if (!message.Successful) - { - return message; - } - - auto entranceExitCheck = RideCheckForEntranceExit(id); - if (!entranceExitCheck.Successful) - { - constructMissingEntranceOrExit(); - return { false, entranceExitCheck.Message }; - } - - if (isApplying) - { - chainQueues(); - flags.set(RideFlag::everBeenOpened); - } - - CoordsXYE trackElement = {}; - message = changeStatusGetStartElement(stationIndex, trackElement); - if (!message.Successful) - { - return message; - } - - message = changeStatusCheckCompleteCircuit(trackElement); - if (!message.Successful) - { - return message; - } - - message = changeStatusCheckTrackValidity(trackElement, false); - if (!message.Successful) - { - return message; - } - - return changeStatusCreateVehicles(isApplying, trackElement, false); -} - -/** - * Given a track element of the ride, find the start of the track. - * It has to do this as a backwards loop in case this is an incomplete track. - */ -void RideGetStartOfTrack(CoordsXYE* output) -{ - TrackBeginEnd trackBeginEnd; - CoordsXYE trackElement = *output; - if (trackBlockGetPrevious(trackElement, &trackBeginEnd)) - { - TileElement* initial_map = trackElement.element; - TrackBeginEnd slowIt = trackBeginEnd; bool moveSlowIt = true; - do - { - // Because we are working backwards, begin_element is the section at the end of a piece of track, whereas - // begin_x and begin_y are the coordinates at the start of a piece of track, so we need to pass end_x and - // end_y - CoordsXYE lastGood = { - /* .x = */ trackBeginEnd.end_x, - /* .y = */ trackBeginEnd.end_y, - /* .element = */ trackBeginEnd.begin_element, - }; + TrackCircuitIterator it, slowIt; + trackCircuitIteratorBegin(&it, input); + slowIt = it; - if (!trackBlockGetPrevious( - { trackBeginEnd.end_x, trackBeginEnd.end_y, trackBeginEnd.begin_element }, &trackBeginEnd)) + while (trackCircuitIteratorNext(&it)) + { + auto trackType = it.current.element->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + if (ted.flags.has(TrackElementFlag::inversionToNormal)) { - trackElement = lastGood; - break; + *output = it.current; + return true; } + // Prevents infinite loops moveSlowIt = !moveSlowIt; if (moveSlowIt) { - if (!trackBlockGetPrevious({ slowIt.end_x, slowIt.end_y, slowIt.begin_element }, &slowIt) - || slowIt.begin_element == trackBeginEnd.begin_element) + trackCircuitIteratorNext(&slowIt); + if (trackCircuitIteratorsMatch(&it, &slowIt)) { - break; + return false; } } - } while (initial_map != trackBeginEnd.begin_element); - } - *output = trackElement; -} - -/** - * - * rct2: 0x00696707 - */ -void Ride::stopGuestsQueuing() -{ - for (auto peep : EntityList()) - { - if (peep->State != PeepState::queuing) - continue; - if (peep->CurrentRide != id) - continue; - - peep->removeFromQueue(); - peep->SetState(PeepState::falling); - } -} - -RideMode Ride::getDefaultMode() const -{ - return getRideTypeDescriptor().DefaultMode; -} - -static bool RideTypeWithTrackColoursExists(ride_type_t rideType, const TrackColour& colours) -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - if (ride.type != rideType) - continue; - if (ride.trackColours[0].main != colours.main) - continue; - if (ride.trackColours[0].additional != colours.additional) - continue; - if (ride.trackColours[0].supports != colours.supports) - continue; - - return true; - } - return false; -} - -bool Ride::nameExists(std::string_view name, RideId excludeRideId) -{ - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) - { - if (ride.id != excludeRideId) - { - Formatter ft; - ride.formatNameTo(ft); - - char buffer[256]{}; - FormatStringLegacy(buffer, 256, STR_STRINGID, ft.Data()); - if (name == buffer && RideHasAnyTrackElements(ride)) - { - return true; - } } - } - return false; -} - -int32_t RideGetRandomColourPresetIndex(ride_type_t rideType) -{ - if (rideType >= std::size(kRideTypeDescriptors)) - { - return 0; + return false; } - // Find all the presets that haven't yet been used in the park for this ride type - const auto& colourPresets = GetRideTypeDescriptor(rideType).ColourPresets; - std::vector unused; - unused.reserve(colourPresets.count); - for (uint8_t i = 0; i < colourPresets.count; i++) + /** + * Iterates along the track until a banked track piece is reached. + * @param input The start track element and position. + * @param output The first track element and position which is banked. + * @returns true if a banked track piece is found, otherwise false. + * rct2: 0x006CB1D3 + */ + static bool RideCheckTrackContainsBanked(const CoordsXYE& input, CoordsXYE* output) { - const auto& colours = colourPresets.list[i]; - if (!RideTypeWithTrackColoursExists(rideType, colours)) - { - unused.push_back(static_cast(i)); - } - } + if (input.element == nullptr) + return false; - // If all presets have been used, just go with a random preset - if (unused.empty()) - return UtilRand() % colourPresets.count; + const auto* trackElement = input.element->asTrack(); + if (trackElement == nullptr) + return false; - // Choose a random preset from the list of unused presets - auto unusedIndex = UtilRand() % unused.size(); - return unused[unusedIndex]; -} + auto rideIndex = trackElement->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return false; -/** - * - * Based on rct2: 0x006B4776 - */ -void Ride::setColourPreset(uint8_t trackColourPreset, uint8_t vehicleColourPreset) -{ - const TrackColourPresetList* colourPresets = &getRideTypeDescriptor().ColourPresets; - TrackColour colours = { OpenRCT2::Drawing::Colour::black, OpenRCT2::Drawing::Colour::black, - OpenRCT2::Drawing::Colour::black }; - // Stalls save their default colour in the vehicle settings (since they share a common ride type) - if (!isRide()) - { - const auto* rideEntry = GetRideEntryByIndex(subtype); - if (rideEntry != nullptr && rideEntry->vehicle_preset_list->count > 0) - { - if (vehicleColourPreset < rideEntry->vehicle_preset_list->count) - { - auto list = rideEntry->vehicle_preset_list->list[vehicleColourPreset]; - colours = { list.Body, list.Trim, list.Tertiary }; - } - } - } - else if (trackColourPreset < colourPresets->count) - { - colours = colourPresets->list[trackColourPreset]; - } - for (size_t i = 0; i < std::size(trackColours); i++) - { - trackColours[i].main = colours.main; - trackColours[i].additional = colours.additional; - trackColours[i].supports = colours.supports; - } - vehicleColourSettings = VehicleColourSettings::same; -} - -money64 RideGetCommonPrice(const Ride& forRide) -{ - auto& gameState = getGameState(); - for (const auto& ride : RideManager(gameState)) - { - if (ride.type == forRide.type && ride.id != forRide.id) - { - return ride.price[0]; - } - } - - return kMoney64Undefined; -} - -void Ride::setNameToDefault() -{ - char rideNameBuffer[256]{}; - - // Increment default name number until we find a unique name - customName = {}; - defaultNameNumber = 0; - do - { - defaultNameNumber++; - Formatter ft; - formatNameTo(ft); - FormatStringLegacy(rideNameBuffer, 256, STR_STRINGID, ft.Data()); - } while (nameExists(rideNameBuffer, id)); -} - -/** - * This will return the name of the ride, as seen in the New Ride window. - */ -RideNaming GetRideNaming(const ride_type_t rideType, const RideObjectEntry* rideEntry) -{ - const auto& rtd = GetRideTypeDescriptor(rideType); - if (rtd.flags.has(RtdFlag::listVehiclesSeparately) && rideEntry != nullptr) - { - return rideEntry->naming; - } - - return rtd.Naming; -} - -/* - * The next eight functions are helpers to access ride data at the offset 10E & - * 110. Known as the turn counts. There are 3 different types (default, banked, sloped) - * and there are 4 counts as follows: - * - * 1 element turns: low 5 bits - * 2 element turns: bits 6-8 - * 3 element turns: bits 9-11 - * 4 element or more turns: bits 12-15 - * - * 4 plus elements only possible on sloped type. Falls back to 3 element - * if by some miracle you manage 4 element none sloped. - */ - -void IncrementTurnCount1Element(Ride& ride, uint8_t type) -{ - uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return; - } - uint16_t value = (*turn_count & kTurnMask1Element) + 1; - *turn_count &= ~kTurnMask1Element; - - if (value > kTurnMask1Element) - value = kTurnMask1Element; - *turn_count |= value; -} - -void IncrementTurnCount2Elements(Ride& ride, uint8_t type) -{ - uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return; - } - uint16_t value = (*turn_count & kTurnMask2Elements) + 0x20; - *turn_count &= ~kTurnMask2Elements; - - if (value > kTurnMask2Elements) - value = kTurnMask2Elements; - *turn_count |= value; -} - -void IncrementTurnCount3Elements(Ride& ride, uint8_t type) -{ - uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return; - } - uint16_t value = (*turn_count & kTurnMask3Elements) + 0x100; - *turn_count &= ~kTurnMask3Elements; - - if (value > kTurnMask3Elements) - value = kTurnMask3Elements; - *turn_count |= value; -} - -void IncrementTurnCount4PlusElements(Ride& ride, uint8_t type) -{ - uint16_t* turn_count; - switch (type) - { - case 0: - case 1: - // Just in case fallback to 3 element turn - IncrementTurnCount3Elements(ride, type); - return; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return; - } - uint16_t value = (*turn_count & kTurnMask4PlusElements) + 0x800; - *turn_count &= ~kTurnMask4PlusElements; - - if (value > kTurnMask4PlusElements) - value = kTurnMask4PlusElements; - *turn_count |= value; -} - -int32_t GetTurnCount1Element(const Ride& ride, uint8_t type) -{ - const uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return 0; - } - - return (*turn_count) & kTurnMask1Element; -} - -int32_t GetTurnCount2Elements(const Ride& ride, uint8_t type) -{ - const uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return 0; - } - - return ((*turn_count) & kTurnMask2Elements) >> 5; -} - -int32_t GetTurnCount3Elements(const Ride& ride, uint8_t type) -{ - const uint16_t* turn_count; - switch (type) - { - case 0: - turn_count = &ride.turnCountDefault; - break; - case 1: - turn_count = &ride.turnCountBanked; - break; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return 0; - } - - return ((*turn_count) & kTurnMask3Elements) >> 8; -} - -int32_t GetTurnCount4PlusElements(const Ride& ride, uint8_t type) -{ - const uint16_t* turn_count; - switch (type) - { - case 0: - case 1: - return 0; - case 2: - turn_count = &ride.turnCountSloped; - break; - default: - return 0; - } - - return ((*turn_count) & kTurnMask4PlusElements) >> 11; -} - -bool Ride::hasSpinningTunnel() const -{ - return specialTrackElements.has(SpecialElement::spinningTunnel); -} - -bool Ride::hasWaterSplash() const -{ - return specialTrackElements.has(SpecialElement::splash); -} - -bool Ride::hasRapids() const -{ - return specialTrackElements.has(SpecialElement::rapids); -} - -bool Ride::hasLogReverser() const -{ - return specialTrackElements.has(SpecialElement::reverser); -} - -bool Ride::hasWaterfall() const -{ - return specialTrackElements.has(SpecialElement::waterfall); -} - -bool Ride::hasWhirlpool() const -{ - return specialTrackElements.has(SpecialElement::whirlpool); -} - -bool Ride::isPoweredLaunched() const -{ - return mode == RideMode::poweredLaunchPassthrough || mode == RideMode::poweredLaunch - || mode == RideMode::poweredLaunchBlockSectioned; -} - -bool Ride::isBlockSectioned() const -{ - return mode == RideMode::continuousCircuitBlockSectioned || mode == RideMode::poweredLaunchBlockSectioned; -} - -bool RideHasAnyTrackElements(const Ride& ride) -{ - TileElementIterator it; - - TileElementIteratorBegin(&it); - while (TileElementIteratorNext(&it)) - { - if (it.element->getType() != TileElementType::track) - continue; - if (it.element->asTrack()->GetRideIndex() != ride.id) - continue; - if (it.element->isGhost()) - continue; - - return true; - } - - return false; -} - -/** - * - * rct2: 0x006B59C6 - */ -void InvalidateTestResults(Ride& ride) -{ - ride.measurement = {}; - ride.ratings.setNull(); - ride.flags.unset(RideFlag::tested, RideFlag::testInProgress); - if (ride.flags.has(RideFlag::onTrack)) - { - for (int32_t i = 0; i < ride.numTrains; i++) - { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle != nullptr) - { - vehicle->flags.unset(VehicleFlag::testing); - } - } - } - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); -} - -/** - * - * rct2: 0x006B7481 - * - * @param rideIndex (dl) - * @param reliabilityIncreaseFactor (ax) - */ -void RideFixBreakdown(Ride& ride, int32_t reliabilityIncreaseFactor) -{ - ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection); - ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); - - if (ride.flags.has(RideFlag::onTrack)) - { - for (int32_t i = 0; i < ride.numTrains; i++) - { - for (Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - vehicle->flags.unset(VehicleFlag::stoppedBySafetyCutout, VehicleFlag::carIsBroken, VehicleFlag::trainIsBroken); - } - } - } - - uint8_t unreliability = 100 - ride.reliabilityPercentage; - ride.reliability += reliabilityIncreaseFactor * (unreliability / 2); -} - -/** - * - * rct2: 0x006DE102 - */ -void RideUpdateVehicleColours(const Ride& ride) -{ - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::spaceRings || rtd.flags.has(RtdFlag::vehicleIsIntegral)) - { - GfxInvalidateScreen(); - } - - auto& entities = getGameState().entities; - for (int32_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) - { - int32_t carIndex = 0; - for (Vehicle* vehicle = entities.GetEntity(ride.vehicles[i]); vehicle != nullptr; - vehicle = entities.GetEntity(vehicle->next_vehicle_on_train)) - { - VehicleColour colours = {}; - switch (ride.vehicleColourSettings) - { - case VehicleColourSettings::same: - colours = ride.vehicleColours[0]; - break; - case VehicleColourSettings::perTrain: - colours = ride.vehicleColours[i]; - break; - case VehicleColourSettings::perCar: - { - const bool isReversed = vehicle->flags.has(VehicleFlag::carIsReversed); - const auto colourIndex = isReversed ? (ride.numCarsPerTrain - 1) - carIndex : carIndex; - colours = ride.vehicleColours[std::min(colourIndex, Limits::kMaxCarsPerTrain - 1)]; - break; - } - } - - vehicle->colours = colours; - vehicle->invalidate(); - carIndex++; - } - } -} - -uint8_t RideEntryGetVehicleAtPosition(int32_t rideEntryIndex, int32_t numCarsPerTrain, int32_t position) -{ - const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); - if (position == 0 && rideEntry->FrontCar != 255) - { - return rideEntry->FrontCar; - } - if (position == 1 && rideEntry->SecondCar != 255) - { - return rideEntry->SecondCar; - } - if (position == 2 && rideEntry->ThirdCar != 255) - { - return rideEntry->ThirdCar; - } - if (position == numCarsPerTrain - 1 && rideEntry->RearCar != 255) - { - return rideEntry->RearCar; - } - - return rideEntry->DefaultCar; -} - -using namespace OpenRCT2::Entity::Yaw; - -struct NecessarySpriteGroup -{ - SpriteGroupType VehicleSpriteGroup; - SpritePrecision MinPrecision; -}; - -// Finds track pieces that a given ride entry has sprites for -BitSet RideEntryGetSupportedTrackPieces(const RideObjectEntry& rideEntry) -{ - // TODO: Use a std::span when C++20 available as 6 is due to jagged array - static const std::array trackPieceRequiredSprites[] = { - { SpriteGroupType::slopeFlat, SpritePrecision::none }, // TrackGroup::flat - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::straight - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::stationEnd - { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::liftHill - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, - SpritePrecision::sprites4 }, // TrackGroup::liftHillSteep - { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::liftHillCurve - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, - SpritePrecision::sprites16 }, // TrackGroup::flatRollBanking - { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::verticalLoop - { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::slope - { SpriteGroupType::slopes60, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepDown - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, - SpritePrecision::sprites4 }, // TrackGroup::flatToSteepSlope - { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::slopeCurve - { SpriteGroupType::slopes60, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveSteep - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::sBend - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveVerySmall - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveSmall - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curve - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveLarge - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, SpritePrecision::sprites4, - SpriteGroupType::flatBanked67, SpritePrecision::sprites4, SpriteGroupType::flatBanked90, SpritePrecision::sprites4, - SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::twist - { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoop - { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::corkscrew - { SpriteGroupType::slopeFlat, SpritePrecision::none }, // TrackGroup::tower - { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixUpBankedHalf - { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixDownBankedHalf - { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixUpBankedQuarter - { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixDownBankedQuarter - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::helixUpUnbankedQuarter - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::helixDownUnbankedQuarter - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::brakes - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::onridePhoto - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes12, - SpritePrecision::sprites4 }, // TrackGroup::waterSplash - { SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::slopeVertical - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, SpritePrecision::sprites4, - SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::barrelRoll - { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::poweredLift - { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoopLarge - { SpriteGroupType::slopes12Banked22, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveBanked - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::logFlumeReverser - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, SpritePrecision::sprites4, - SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::heartlineRoll - { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::reverser - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes25, SpritePrecision::sprites4, - SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4 }, // TrackGroup::reverseFreefall - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes25, SpritePrecision::sprites4, - SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4 }, // TrackGroup::slopeToFlat - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::blockBrakes - { SpriteGroupType::slopes25Banked22, SpritePrecision::sprites4 }, // TrackGroup::slopeRollBanking - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, - SpritePrecision::sprites4 }, // TrackGroup::slopeSteepLong - { SpriteGroupType::slopes90, SpritePrecision::sprites16 }, // TrackGroup::curveVertical - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, - SpritePrecision::sprites4 }, // TrackGroup::liftHillCable - { SpriteGroupType::curvedLiftHillUp, SpritePrecision::sprites16 }, // TrackGroup::liftHillCurved - { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoop - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::spinningTunnel - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::booster - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, SpritePrecision::sprites4, - SpriteGroupType::flatBanked67, SpritePrecision::sprites4, SpriteGroupType::flatBanked90, SpritePrecision::sprites4, - SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::inlineTwistUninverted - { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, SpritePrecision::sprites4, - SpriteGroupType::flatBanked67, SpritePrecision::sprites4, SpriteGroupType::flatBanked90, SpritePrecision::sprites4, - SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::inlineTwistInverted - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::quarterLoopUninvertedUp - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::quarterLoopUninvertedDown - { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoopInvertedUp - { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoopInvertedDown - { SpriteGroupType::slopes12, SpritePrecision::sprites4 }, // TrackGroup::rapids - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopUninvertedUp - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, - SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopInvertedDown - {}, // TrackGroup::flatRideBase - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::waterfall - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::whirlpool - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, - SpritePrecision::sprites4 }, // TrackGroup::brakeForDrop - { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::corkscrewUninverted - { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::corkscrewInverted - { SpriteGroupType::slopes12, SpritePrecision::sprites4, SpriteGroupType::slopes25, - SpritePrecision::sprites4 }, // TrackGroup::heartlineTransfer - {}, // TrackGroup::miniGolfHole - { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::rotationControlToggle - { SpriteGroupType::slopes60, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepUp - { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::corkscrewLarge - { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, - SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, - SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoopMedium - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes12Banked22, SpritePrecision::sprites4, - SpriteGroupType::slopes25Banked22, SpritePrecision::sprites4, SpriteGroupType::slopes25Banked45, - SpritePrecision::sprites4, SpriteGroupType::inlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::zeroGRoll - { SpriteGroupType::slopes42Banked22, SpritePrecision::sprites4, SpriteGroupType::slopes42Banked45, - SpritePrecision::sprites4, SpriteGroupType::slopes42Banked67, SpritePrecision::sprites4, - SpriteGroupType::slopes42Banked90, SpritePrecision::sprites4, SpriteGroupType::slopes60Banked22, - SpritePrecision::sprites4 }, // TrackGroup::zeroGRollLarge - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopUninvertedUp - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, - SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopInvertedDown - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, - SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopUninvertedDown - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopInvertedUp - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopInvertedUp - { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, - SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, - SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopUninvertedDown - { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveLarge - { SpriteGroupType::slopes25Banked45, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveLargeBanked - { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBrakes - { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBlockBrakes - { SpriteGroupType::slopes25, SpritePrecision::sprites8 }, // TrackGroup::inclinedBrakes - { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBooster - { SpriteGroupType::slopes8, SpritePrecision::sprites4, SpriteGroupType::slopes16, SpritePrecision::sprites4, - SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, - SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepLong - { SpriteGroupType::slopes50, SpritePrecision::sprites4, SpriteGroupType::slopes60Banked22, SpritePrecision::sprites8, - SpriteGroupType::slopes50Banked45, SpritePrecision::sprites8, SpriteGroupType::slopes50Banked67, - SpritePrecision::sprites8, SpriteGroupType::slopes50Banked90, SpritePrecision::sprites8, SpriteGroupType::corkscrews, - SpritePrecision::sprites4, SpriteGroupType::slopes25InlineTwists, SpritePrecision::sprites4, - SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, - SpritePrecision::sprites4 }, // TrackGroup::diveLoop - { SpriteGroupType::slopes8, SpritePrecision::sprites4, SpriteGroupType::slopes16, - SpritePrecision::sprites4 }, // TrackGroup::diagSlope - { SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, - SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::diagSlopeSteepUp - { SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, - SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::diagSlopeSteepDown - }; - - static_assert(std::size(trackPieceRequiredSprites) == EnumValue(TrackGroup::count)); - - // Only check default vehicle; it's assumed the others will have correct sprites if this one does (I've yet to find an - // exception, at least) - auto supportedPieces = OpenRCT2::BitSet(); - supportedPieces.flip(); - auto defaultVehicle = rideEntry.GetDefaultCar(); - if (defaultVehicle != nullptr) - { - for (size_t i = 0; i < std::size(trackPieceRequiredSprites); i++) - { - for (auto& group : trackPieceRequiredSprites[i]) - { - auto precision = defaultVehicle->SpriteGroups[EnumValue(group.VehicleSpriteGroup)].spritePrecision; - if (precision < group.MinPrecision) - supportedPieces.set(i, false); - } - } - } - return supportedPieces; -} - -static std::optional RideGetSmallestStationLength(const Ride& ride) -{ - std::optional result; - for (const auto& station : ride.getStations()) - { - if (!station.Start.IsNull()) - { - if (!result.has_value() || station.Length < result.value()) - { - result = station.Length; - } - } - } - return result; -} - -/** - * - * rct2: 0x006CB3AA - */ -static int32_t RideGetTrackLength(const Ride& ride) -{ - TileElement* tileElement = nullptr; - TrackElemType trackType; - CoordsXYZ trackStart; - bool foundTrack = false; - - for (const auto& station : ride.getStations()) - { - trackStart = station.GetStart(); - if (trackStart.IsNull()) - continue; - - tileElement = MapGetFirstElementAt(trackStart); - if (tileElement == nullptr) - continue; - do - { - if (tileElement->getType() != TileElementType::track) - continue; - - trackType = tileElement->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - continue; - - if (tileElement->getBaseZ() != trackStart.z) - continue; - - foundTrack = true; - } while (!foundTrack && !(tileElement++)->isLastForTile()); - - if (foundTrack) - break; - } - - if (!foundTrack) - return 0; - - RideId rideIndex = tileElement->asTrack()->GetRideIndex(); - - auto* windowMgr = Ui::GetWindowManager(); - WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); - if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && _currentRideIndex == rideIndex) - { - RideConstructionInvalidateCurrentTrack(); - } - - bool moveSlowIt = true; - int32_t result = 0; - - TrackCircuitIterator it; - trackCircuitIteratorBegin(&it, { trackStart.x, trackStart.y, tileElement }); - - TrackCircuitIterator slowIt = it; - while (trackCircuitIteratorNext(&it)) - { - trackType = it.current.element->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - result += ted.pieceLength; - - moveSlowIt = !moveSlowIt; - if (moveSlowIt) - { - trackCircuitIteratorNext(&slowIt); - if (trackCircuitIteratorsMatch(&it, &slowIt)) - { - return 0; - } - } - } - return result; -} - -/** - * - * rct2: 0x006DD57D - */ -void Ride::updateMaxVehicles() -{ - if (subtype == kObjectEntryIndexNull) - return; - - const auto* rideEntry = GetRideEntryByIndex(subtype); - if (rideEntry == nullptr) - { - return; - } - - uint8_t newNumCarsPerTrain; - int32_t maxNumTrains; - - const auto& rtd = getRideTypeDescriptor(); - if (rideEntry->cars_per_flat_ride == kNoFlatRideCars) - { - newNumCarsPerTrain = std::max(rideEntry->min_cars_in_train, numCarsPerTrain); - minCarsPerTrain = rideEntry->min_cars_in_train; - maxCarsPerTrain = rideEntry->max_cars_in_train; - - // Calculate maximum train length based on smallest station length - auto stationNumTiles = RideGetSmallestStationLength(*this); - if (!stationNumTiles.has_value()) - return; - - auto stationLength = (stationNumTiles.value() * 0x44180) - 0x16B2A; - int32_t maxMass = rtd.MaxMass << 8; - int32_t newMaxCarsPerTrain = 1; - for (int32_t numCars = rideEntry->max_cars_in_train; numCars > 0; numCars--) - { - int32_t trainLength = 0; - int32_t totalMass = 0; - for (int32_t i = 0; i < numCars; i++) - { - const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, numCars, i)]; - trainLength += carEntry.spacing; - totalMass += carEntry.car_mass; - } - - if (trainLength <= stationLength && totalMass <= maxMass) - { - newMaxCarsPerTrain = numCars; - break; - } - } - int32_t newCarsPerTrain = std::max(proposedNumCarsPerTrain, rideEntry->min_cars_in_train); - newMaxCarsPerTrain = std::max(newMaxCarsPerTrain, static_cast(rideEntry->min_cars_in_train)); - if (!getGameState().cheats.disableTrainLengthLimit) - { - newCarsPerTrain = std::min(newMaxCarsPerTrain, newCarsPerTrain); - } - maxCarsPerTrain = newMaxCarsPerTrain; - minCarsPerTrain = rideEntry->min_cars_in_train; - - switch (mode) - { - case RideMode::continuousCircuitBlockSectioned: - case RideMode::poweredLaunchBlockSectioned: - maxNumTrains = std::clamp(numStations + numBlockBrakes - 1, 1, Limits::kMaxTrainsPerRide); - break; - case RideMode::reverseInclineLaunchedShuttle: - case RideMode::poweredLaunchPassthrough: - case RideMode::shuttle: - case RideMode::limPoweredLaunch: - case RideMode::poweredLaunch: - maxNumTrains = 1; - break; - default: - // Calculate maximum number of trains - int32_t trainLength = 0; - for (int32_t i = 0; i < newCarsPerTrain; i++) - { - const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, i)]; - trainLength += carEntry.spacing; - } - - int32_t totalLength = trainLength / 2; - if (newCarsPerTrain != 1) - totalLength /= 2; - - maxNumTrains = 0; - do - { - maxNumTrains++; - totalLength += trainLength; - } while (totalLength <= stationLength); - - if ((mode != RideMode::stationToStation && mode != RideMode::continuousCircuit) - || !rtd.flags.has(RtdFlag::allowMoreVehiclesThanStationFits)) - { - maxNumTrains = std::min(maxNumTrains, int32_t(Limits::kMaxTrainsPerRide)); - } - else - { - const auto& firstCarEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, 0)]; - int32_t poweredMaxSpeed = firstCarEntry.powered_max_speed; - - int32_t totalSpacing = 0; - for (int32_t i = 0; i < newCarsPerTrain; i++) - { - const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, i)]; - totalSpacing += carEntry.spacing; - } - - totalSpacing >>= 13; - int32_t trackLength = RideGetTrackLength(*this) / 4; - if (poweredMaxSpeed > 10) - trackLength = (trackLength * 3) / 4; - if (poweredMaxSpeed > 25) - trackLength = (trackLength * 3) / 4; - if (poweredMaxSpeed > 40) - trackLength = (trackLength * 3) / 4; - - maxNumTrains = 0; - int32_t length = 0; - do - { - maxNumTrains++; - length += totalSpacing; - } while (maxNumTrains < Limits::kMaxTrainsPerRide && length < trackLength); - } - break; - } - maxTrains = maxNumTrains; - - newNumCarsPerTrain = std::min(proposedNumCarsPerTrain, static_cast(newCarsPerTrain)); - } - else - { - maxTrains = rideEntry->cars_per_flat_ride; - minCarsPerTrain = rideEntry->min_cars_in_train; - maxCarsPerTrain = rideEntry->max_cars_in_train; - newNumCarsPerTrain = rideEntry->max_cars_in_train; - maxNumTrains = rideEntry->cars_per_flat_ride; - } - - if (getGameState().cheats.disableTrainLengthLimit) - { - maxNumTrains = Limits::kMaxTrainsPerRide; - } - auto newNumTrains = std::min(proposedNumTrains, static_cast(maxNumTrains)); - - // Refresh new current num vehicles / num cars per vehicle - if (newNumTrains != numTrains || newNumCarsPerTrain != numCarsPerTrain) - { - numCarsPerTrain = newNumCarsPerTrain; - numTrains = newNumTrains; + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + return true; auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, id.ToUnderlying()); - } -} - -void Ride::updateNumberOfCircuits() -{ - if (!canHaveMultipleCircuits()) - { - numCircuits = 1; - } -} - -void Ride::setRideEntry(ObjectEntryIndex entryIndex) -{ - auto colour = RideGetUnusedPresetVehicleColour(entryIndex, UtilRand()); - auto rideSetVehicleAction = GameActions::RideSetVehicleAction( - id, GameActions::RideSetVehicleType::rideEntry, entryIndex, colour); - GameActions::Execute(&rideSetVehicleAction, getGameState()); -} - -void Ride::setNumTrains(int32_t newNumTrains) -{ - auto rideSetVehicleAction = GameActions::RideSetVehicleAction(id, GameActions::RideSetVehicleType::numTrains, newNumTrains); - GameActions::Execute(&rideSetVehicleAction, getGameState()); -} - -void Ride::setNumCarsPerTrain(int32_t numCarsPerVehicle) -{ - auto rideSetVehicleAction = GameActions::RideSetVehicleAction( - id, GameActions::RideSetVehicleType::numCarsPerTrain, numCarsPerVehicle); - GameActions::Execute(&rideSetVehicleAction, getGameState()); -} - -void Ride::setReversedTrains(bool reverseTrains) -{ - auto rideSetVehicleAction = GameActions::RideSetVehicleAction( - id, GameActions::RideSetVehicleType::trainsReversed, reverseTrains); - GameActions::Execute(&rideSetVehicleAction, getGameState()); -} - -/** - * - * rct2: 0x006B752C - */ -void Ride::crash(uint8_t vehicleIndex) -{ - Vehicle* vehicle = getGameState().entities.GetEntity(vehicles[vehicleIndex]); - - if (gLegacyScene != LegacyScene::titleSequence && vehicle != nullptr) - { - // Open ride window for crashed vehicle - auto intent = Intent(WindowDetail::vehicle); - intent.PutExtra(INTENT_EXTRA_VEHICLE, vehicle); - WindowBase* w = ContextOpenIntent(&intent); - - Viewport* viewport = WindowGetViewport(w); - if (w != nullptr && viewport != nullptr) + WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) { - viewport->flags |= VIEWPORT_FLAG_SOUND_ON; + RideConstructionInvalidateCurrentTrack(); } - } - if (Config::Get().notifications.rideCrashed) - { - Formatter ft; - formatNameTo(ft); - News::AddItemToQueue(News::ItemType::ride, STR_RIDE_HAS_CRASHED, id.ToUnderlying(), ft); - } -} + bool moveSlowIt = true; + TrackCircuitIterator it, slowIt; + trackCircuitIteratorBegin(&it, input); + slowIt = it; -// Gets the approximate value of customers per hour for this ride. Multiplies ride_customers_in_last_5_minutes() by 12. -uint32_t RideCustomersPerHour(const Ride& ride) -{ - return RideCustomersInLast5Minutes(ride) * 12; -} - -// Calculates the number of customers for this ride in the last 5 minutes (or more correctly 9600 game ticks) -uint32_t RideCustomersInLast5Minutes(const Ride& ride) -{ - uint32_t sum = 0; - - for (int32_t i = 0; i < Limits::kCustomerHistorySize; i++) - { - sum += ride.numCustomers[i]; - } - - return sum; -} - -Vehicle* RideGetBrokenVehicle(const Ride& ride) -{ - auto vehicleIndex = ride.vehicles[ride.brokenTrain]; - Vehicle* vehicle = getGameState().entities.GetEntity(vehicleIndex); - if (vehicle != nullptr) - { - return vehicle->GetCar(ride.brokenCar); - } - return nullptr; -} - -/** - * - * rct2: 0x006D235B - */ -void Ride::remove() -{ - RideDelete(id); -} - -void Ride::renew() -{ - // Set build date to current date (so the ride is brand new) - buildDate = GetDate().GetMonthsElapsed(); - reliability = kRideInitialReliability; - std::fill(std::begin(downtimeHistory), std::end(downtimeHistory), 0); - downtime = 0; -} - -RideClassification Ride::getClassification() const -{ - const auto& rtd = getRideTypeDescriptor(); - return rtd.Classification; -} - -bool Ride::isRide() const -{ - return getClassification() == RideClassification::ride; -} - -money64 RideGetPrice(const Ride& ride) -{ - auto& park = getGameState().park; - if (park.flags & PARK_FLAGS_NO_MONEY) - return 0; - if (ride.isRide()) - { - if (!Park::RidePricesUnlocked(park)) + while (trackCircuitIteratorNext(&it)) { - return 0; - } - } - return ride.price[0]; -} + auto trackType = it.current.element->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + if (ted.flags.has(TrackElementFlag::banked)) + { + *output = it.current; + return true; + } -/** - * Return the tile_element of an adjacent station at x,y,z(+-2). - * Returns nullptr if no suitable tile_element is found. - */ -TileElement* GetStationPlatform(const CoordsXYRangedZ& coords) -{ - bool foundTileElement = false; - TileElement* tileElement = MapGetFirstElementAt(coords); - if (tileElement != nullptr) + // Prevents infinite loops + moveSlowIt = !moveSlowIt; + if (moveSlowIt) + { + trackCircuitIteratorNext(&slowIt); + if (trackCircuitIteratorsMatch(&it, &slowIt)) + { + return false; + } + } + } + return false; + } + + /** + * + * rct2: 0x006CB25D + */ + static int32_t RideCheckStationLength(const CoordsXYE& input, CoordsXYE* output) { + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 + && _currentRideIndex == input.element->asTrack()->GetRideIndex()) + { + RideConstructionInvalidateCurrentTrack(); + } + + output->x = input.x; + output->y = input.y; + output->element = input.element; + TrackBeginEnd trackBeginEnd; + while (trackBlockGetPrevious(*output, &trackBeginEnd)) + { + output->x = trackBeginEnd.begin_x; + output->y = trackBeginEnd.begin_y; + output->element = trackBeginEnd.begin_element; + } + + int32_t num_station_elements = 0; + CoordsXYE last_good_station = *output; + do { - if (tileElement->getType() != TileElementType::track) - continue; - /* Check if tileElement is a station platform. */ - if (!tileElement->asTrack()->IsStation()) - continue; - - if (coords.baseZ > tileElement->getBaseZ() || coords.clearanceZ < tileElement->getBaseZ()) + const auto& ted = GetTrackElementDescriptor(output->element->asTrack()->GetTrackType()); + if (ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) { - /* The base height of tileElement is not within - * the z tolerance. */ - continue; + num_station_elements++; + last_good_station = *output; } - - foundTileElement = true; - break; - } while (!(tileElement++)->isLastForTile()); - } - if (!foundTileElement) - { - return nullptr; - } - - return tileElement; -} - -/** - * Check for an adjacent station to x,y,z in direction. - */ -static bool CheckForAdjacentStation(const CoordsXYZ& stationCoords, uint8_t direction) -{ - bool found = false; - int32_t adjX = stationCoords.x; - int32_t adjY = stationCoords.y; - for (uint32_t i = 0; i <= kRideAdjacencyCheckDistance; i++) - { - adjX += CoordsDirectionDelta[direction].x; - adjY += CoordsDirectionDelta[direction].y; - TileElement* stationElement = GetStationPlatform( - { { adjX, adjY, stationCoords.z - 2 * kCoordsZStep }, stationCoords.z + 2 * kCoordsZStep }); - if (stationElement != nullptr) - { - auto rideIndex = stationElement->asTrack()->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride != nullptr && (ride->departFlags & RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS)) + else { - found = true; - } - } - } - return found; -} - -/** - * Return whether ride has at least one adjacent station to it. - */ -bool RideHasAdjacentStation(const Ride& ride) -{ - bool found = false; - - /* Loop through all of the ride stations, checking for an - * adjacent station on either side. */ - for (const auto& station : ride.getStations()) - { - auto stationStart = station.GetStart(); - if (!stationStart.IsNull()) - { - /* Get the map element for the station start. */ - TileElement* stationElement = GetStationPlatform({ stationStart, stationStart.z + 0 }); - if (stationElement == nullptr) - { - continue; - } - /* Check the first side of the station */ - int32_t direction = stationElement->getDirectionWithOffset(1); - found = CheckForAdjacentStation(stationStart, direction); - if (found) - break; - /* Check the other side of the station */ - direction = DirectionReverse(direction); - found = CheckForAdjacentStation(stationStart, direction); - if (found) - break; - } - } - return found; -} - -bool RideHasStationShelter(const Ride& ride) -{ - const auto* stationObj = ride.getStationObject(); - return stationObj != nullptr && (stationObj->Flags & StationObjectFlags::hasShelter); -} - -bool RideHasRatings(const Ride& ride) -{ - return !ride.ratings.isNull(); -} - -int32_t GetUnifiedBoosterSpeed(ride_type_t rideType, int32_t relativeSpeed) -{ - return GetRideTypeDescriptor(rideType).GetUnifiedBoosterSpeed(relativeSpeed); -} - -void FixInvalidVehicleSpriteSizes() -{ - auto& gameState = getGameState(); - for (const auto& ride : RideManager(gameState)) - { - for (auto entityIndex : ride.vehicles) - { - for (Vehicle* vehicle = getGameState().entities.TryGetEntity(entityIndex); vehicle != nullptr; - vehicle = getGameState().entities.TryGetEntity(vehicle->next_vehicle_on_train)) - { - auto carEntry = vehicle->Entry(); - if (carEntry == nullptr) + if (num_station_elements == 0) + continue; + if (num_station_elements == 1) { + return 0; + } + num_station_elements = 0; + } + } while (trackBlockGetNext(output, output, nullptr, nullptr)); + + // Prevent returning a pointer to a map element with no track. + *output = last_good_station; + if (num_station_elements == 1) + return 0; + + return 1; + } + + /** + * + * rct2: 0x006CB2DA + */ + static bool RideCheckStartAndEndIsStation(const CoordsXYE& input) + { + CoordsXYE trackBack, trackFront; + + RideId rideIndex = input.element->asTrack()->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return false; + + auto* windowMgr = Ui::GetWindowManager(); + auto w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && rideIndex == _currentRideIndex) + { + RideConstructionInvalidateCurrentTrack(); + } + + // Check back of the track + trackGetBack(input, &trackBack); + auto trackType = trackBack.element->asTrack()->GetTrackType(); + const auto& tedBack = GetTrackElementDescriptor(trackType); + if (!tedBack.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + { + return false; + } + ride->chairliftBullwheelLocation[0] = TileCoordsXYZ{ CoordsXYZ{ trackBack.x, trackBack.y, + trackBack.element->getBaseZ() } }; + + // Check front of the track + trackGetFront(input, &trackFront); + trackType = trackFront.element->asTrack()->GetTrackType(); + const auto& tedFront = GetTrackElementDescriptor(trackType); + if (!tedFront.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + { + return false; + } + ride->chairliftBullwheelLocation[1] = TileCoordsXYZ{ CoordsXYZ{ trackFront.x, trackFront.y, + trackFront.element->getBaseZ() } }; + return true; + } + + /** + * Sets the position and direction of the returning point on the track of a boat hire ride. This will either be the end of + * the station or the last track piece from the end of the direction. rct2: 0x006B4D39 + */ + static void RideSetBoatHireReturnPoint(Ride& ride, const CoordsXYE& startElement) + { + auto trackType = TrackElemType::none; + auto returnPos = startElement; + int32_t startX = returnPos.x; + int32_t startY = returnPos.y; + TrackBeginEnd trackBeginEnd; + while (trackBlockGetPrevious(returnPos, &trackBeginEnd)) + { + // If previous track is back to the starting x, y, then break loop (otherwise possible infinite loop) + if (trackType != TrackElemType::none && startX == trackBeginEnd.begin_x && startY == trackBeginEnd.begin_y) + break; + + auto trackCoords = CoordsXYZ{ trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }; + int32_t direction = trackBeginEnd.begin_direction; + trackType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); + auto newCoords = GetTrackElementOriginAndApplyChanges( + { trackCoords, static_cast(direction) }, trackType, 0, &returnPos.element, {}); + returnPos = newCoords.has_value() ? CoordsXYE{ newCoords.value(), returnPos.element } + : CoordsXYE{ trackCoords, returnPos.element }; + }; + + trackType = returnPos.element->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + int32_t elementReturnDirection = ted.coordinates.rotationBegin; + ride.boatHireReturnDirection = returnPos.element->getDirectionWithOffset(elementReturnDirection); + ride.boatHireReturnPosition = TileCoordsXY{ returnPos }; + } + + /** + * + * rct2: 0x006B4D39 + */ + static void RideSetMazeEntranceExitPoints(Ride& ride) + { + // Needs room for an entrance and an exit per station, plus one position for the list terminator. + TileCoordsXYZD positions[(Limits::kMaxStationsPerRide * 2) + 1]; + + // Create a list of all the entrance and exit positions + TileCoordsXYZD* position = positions; + for (const auto& station : ride.getStations()) + { + if (!station.Entrance.IsNull()) + { + *position++ = station.Entrance; + } + if (!station.Exit.IsNull()) + { + *position++ = station.Exit; + } + } + position->SetNull(); + + // Enumerate entrance and exit positions + for (position = positions; !position->IsNull(); position++) + { + auto entranceExitMapPos = position->ToCoordsXYZ(); + + TileElement* tileElement = MapGetFirstElementAt(*position); + do + { + if (tileElement == nullptr) break; - } - - if (vehicle->spriteData.width == 0) - { - vehicle->spriteData.width = carEntry->spriteWidth; - } - if (vehicle->spriteData.heightMin == 0) - { - vehicle->spriteData.heightMin = carEntry->spriteHeightNegative; - } - if (vehicle->spriteData.heightMax == 0) - { - vehicle->spriteData.heightMax = carEntry->spriteHeightPositive; - } - } - } - } -} - -bool RideEntryHasCategory(const RideObjectEntry& rideEntry, RideCategory category) -{ - auto rideType = rideEntry.GetFirstNonNullRideType(); - return GetRideTypeDescriptor(rideType).Category == category; -} - -ObjectEntryIndex RideGetEntryIndex(ride_type_t rideType, ObjectEntryIndex rideSubType) -{ - auto subType = rideSubType; - - if (subType == kObjectEntryIndexNull) - { - auto& objManager = GetContext()->GetObjectManager(); - auto& rideEntries = objManager.GetAllRideEntries(rideType); - if (!rideEntries.empty()) - { - subType = rideEntries[0]; - for (auto rideEntryIndex : rideEntries) - { - const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); - if (rideEntry == nullptr) - { - return kObjectEntryIndexNull; - } - - // Can happen in select-by-track-type mode - if (!RideEntryIsInvented(rideEntryIndex) && !getGameState().cheats.ignoreResearchStatus) + if (tileElement->getType() != TileElementType::entrance) + continue; + if (tileElement->asEntrance()->GetEntranceType() != ENTRANCE_TYPE_RIDE_ENTRANCE + && tileElement->asEntrance()->GetEntranceType() != ENTRANCE_TYPE_RIDE_EXIT) { continue; } + if (tileElement->getBaseZ() != entranceExitMapPos.z) + continue; - if (!GetRideTypeDescriptor(rideType).flags.has(RtdFlag::listVehiclesSeparately)) + MazeEntranceHedgeRemoval({ entranceExitMapPos, tileElement }); + } while (!(tileElement++)->isLastForTile()); + } + } + + void SetBrakeClosedMultiTile(TrackElement& trackElement, const CoordsXY& trackLocation, bool isClosed) + { + switch (trackElement.GetTrackType()) + { + case TrackElemType::diagUp25ToFlat: + case TrackElemType::diagUp60ToFlat: + case TrackElemType::cableLiftHill: + case TrackElemType::diagBrakes: + case TrackElemType::diagBlockBrakes: + GetTrackElementOriginAndApplyChanges( + { trackLocation, trackElement.getBaseZ(), trackElement.getDirection() }, trackElement.GetTrackType(), + isClosed, nullptr, { TrackElementSetFlag::brakeClosed }); + break; + default: + trackElement.SetBrakeClosed(isClosed); + } + } + + /** + * Opens all block brakes of a ride. + * rct2: 0x006B4E6B + */ + static void RideOpenBlockBrakes(const CoordsXYE& startElement) + { + CoordsXYE currentElement = startElement; + do + { + auto trackType = currentElement.element->asTrack()->GetTrackType(); + switch (trackType) + { + case TrackElemType::blockBrakes: + case TrackElemType::diagBlockBrakes: + BlockBrakeSetLinkedBrakesClosed( + CoordsXYZ(currentElement.x, currentElement.y, currentElement.element->getBaseZ()), + *currentElement.element->asTrack(), false); + [[fallthrough]]; + case TrackElemType::diagUp25ToFlat: + case TrackElemType::diagUp60ToFlat: + case TrackElemType::cableLiftHill: + case TrackElemType::endStation: + case TrackElemType::up25ToFlat: + case TrackElemType::up60ToFlat: + SetBrakeClosedMultiTile(*currentElement.element->asTrack(), { currentElement.x, currentElement.y }, false); + break; + default: + break; + } + } while (trackBlockGetNext(¤tElement, ¤tElement, nullptr, nullptr) + && currentElement.element != startElement.element); + } + + /** + * Set the open status of brakes adjacent to the block brake + */ + void BlockBrakeSetLinkedBrakesClosed(const CoordsXYZ& vehicleTrackLocation, TrackElement& trackElement, bool isClosed) + { + uint8_t brakeSpeed = trackElement.GetBrakeBoosterSpeed(); + + auto tileElement = reinterpret_cast(&trackElement); + auto location = vehicleTrackLocation; + TrackBeginEnd trackBeginEnd, slowTrackBeginEnd; + TileElement slowTileElement = *tileElement; + bool counter = true; + CoordsXY slowLocation = location; + do + { + if (!trackBlockGetPrevious({ location, tileElement }, &trackBeginEnd)) + { + return; + } + if (trackBeginEnd.begin_x == vehicleTrackLocation.x && trackBeginEnd.begin_y == vehicleTrackLocation.y + && tileElement == trackBeginEnd.begin_element) + { + return; + } + + location.x = trackBeginEnd.end_x; + location.y = trackBeginEnd.end_y; + location.z = trackBeginEnd.begin_z; + tileElement = trackBeginEnd.begin_element; + + if (trackTypeIsBrakes(tileElement->asTrack()->GetTrackType())) + { + SetBrakeClosedMultiTile( + *tileElement->asTrack(), { trackBeginEnd.begin_x, trackBeginEnd.begin_y }, + (tileElement->asTrack()->GetBrakeBoosterSpeed() >= brakeSpeed) || isClosed); + } + + // prevent infinite loop + counter = !counter; + if (counter) + { + trackBlockGetPrevious({ slowLocation, &slowTileElement }, &slowTrackBeginEnd); + slowLocation.x = slowTrackBeginEnd.end_x; + slowLocation.y = slowTrackBeginEnd.end_y; + slowTileElement = *(slowTrackBeginEnd.begin_element); + if (slowLocation == location && slowTileElement.getBaseZ() == tileElement->getBaseZ() + && slowTileElement.getType() == tileElement->getType() + && slowTileElement.getDirection() == tileElement->getDirection()) { - subType = rideEntryIndex; + return; + } + } + } while (trackTypeIsBrakes(trackBeginEnd.begin_element->asTrack()->GetTrackType())); + } + + /** + * + * rct2: 0x006B4D26 + */ + static void RideSetStartFinishPoints(RideId rideIndex, const CoordsXYE& startElement) + { + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return; + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + RideSetMazeEntranceExitPoints(*ride); + else if (rtd.specialType == RtdSpecialType::boatHire) + RideSetBoatHireReturnPoint(*ride, startElement); + + if (ride->isBlockSectioned() && !ride->flags.has(RideFlag::onTrack)) + { + RideOpenBlockBrakes(startElement); + } + } + + /** + * + * rct2: 0x0069ED9E + */ + static int32_t count_free_misc_sprite_slots() + { + auto& gameState = getGameState(); + int32_t miscSpriteCount = gameState.entities.GetMiscEntityCount(); + int32_t remainingSpriteCount = gameState.entities.GetNumFreeEntities(); + return std::max(0, miscSpriteCount + remainingSpriteCount - 300); + } + + static constexpr CoordsXY word_9A3AB4[4] = { + { 0, 0 }, + { 0, -96 }, + { -96, -96 }, + { -96, 0 }, + }; + + // clang-format off + static constexpr CoordsXY word_9A2A60[] = { + { 0, 16 }, + { 16, 31 }, + { 31, 16 }, + { 16, 0 }, + { 16, 16 }, + { 64, 64 }, + { 64, -32 }, + { -32, -32 }, + { -32, 64 }, + }; + // clang-format on + + /** + * + * rct2: 0x006DD90D + */ + static Vehicle* VehicleCreateCar( + Ride& ride, int32_t carEntryIndex, int32_t carIndex, int32_t vehicleIndex, const CoordsXYZ& carPosition, + int32_t* remainingDistance, TrackElement* trackElement) + { + if (trackElement == nullptr) + return nullptr; + + auto rideEntry = ride.getRideEntry(); + if (rideEntry == nullptr) + return nullptr; + + auto& carEntry = rideEntry->Cars[carEntryIndex]; + + auto* vehicle = getGameState().entities.CreateEntity(); + if (vehicle == nullptr) + return nullptr; + + vehicle->ride = ride.id; + vehicle->ride_subtype = ride.subtype; + + vehicle->vehicle_type = carEntryIndex; + vehicle->SubType = carIndex == 0 ? Vehicle::Type::head : Vehicle::Type::tail; + vehicle->var_44 = Numerics::ror32(carEntry.spacing, 10) & 0xFFFF; + + const auto halfSpacing = carEntry.spacing >> 1; + *remainingDistance -= halfSpacing; + vehicle->remaining_distance = *remainingDistance; + + if (!carEntry.flags.has(CarEntryFlag::isGoKart)) + { + *remainingDistance -= halfSpacing; + } + + // Loc6DD9A5: + vehicle->spriteData.width = carEntry.spriteWidth; + vehicle->spriteData.heightMin = carEntry.spriteHeightNegative; + vehicle->spriteData.heightMax = carEntry.spriteHeightPositive; + vehicle->mass = carEntry.car_mass; + vehicle->num_seats = carEntry.num_seats; + vehicle->speed = carEntry.powered_max_speed; + vehicle->powered_acceleration = carEntry.powered_acceleration; + vehicle->velocity = 0; + vehicle->acceleration = 0; + vehicle->SwingSprite = 0; + vehicle->SwingPosition = 0; + vehicle->SwingSpeed = 0; + vehicle->restraints_position = 0; + vehicle->spin_sprite = 0; + vehicle->spin_speed = 0; + vehicle->sound2_flags = 0; + vehicle->sound1_id = Audio::SoundId::null; + vehicle->sound2_id = Audio::SoundId::null; + vehicle->next_vehicle_on_train = EntityId::GetNull(); + vehicle->CollisionDetectionTimer = 0; + vehicle->animation_frame = 0; + vehicle->animationState = 0; + vehicle->scream_sound_id = Audio::SoundId::null; + vehicle->pitch = VehiclePitch::flat; + vehicle->roll = VehicleRoll::unbanked; + vehicle->target_seat_rotation = 4; + vehicle->seat_rotation = 4; + for (size_t i = 0; i < std::size(vehicle->peep); i++) + { + vehicle->peep[i] = EntityId::GetNull(); + } + + const auto& rtd = ride.getRideTypeDescriptor(); + if (carEntry.flags.has(CarEntryFlag::useDodgemCarPlacement)) + { + // Loc6DDCA4: + vehicle->TrackSubposition = VehicleTrackSubposition::standard; + int32_t direction = trackElement->getDirection(); + auto dodgemPos = carPosition + CoordsXYZ{ word_9A3AB4[direction], 0 }; + vehicle->TrackLocation = dodgemPos; + vehicle->current_station = trackElement->GetStationIndex(); + + dodgemPos.z += rtd.Heights.VehicleZOffset; + + vehicle->SetTrackDirection(0); + vehicle->SetTrackType(trackElement->GetTrackType()); + vehicle->track_progress = 0; + vehicle->SetState(Vehicle::Status::movingToEndOfStation); + vehicle->flags.clearAll(); + + CoordsXY chosenLoc; + auto numAttempts = 0; + // Loc6DDD26: + do + { + numAttempts++; + // This can happen when trying to spawn dozens of cars in a tiny area. + if (numAttempts > 10000) + return nullptr; + + vehicle->orientation = ScenarioRand() & 0x1E; + chosenLoc.y = dodgemPos.y + (ScenarioRand() & 0xFF); + chosenLoc.x = dodgemPos.x + (ScenarioRand() & 0xFF); + } while (vehicle->DodgemsCarWouldCollideAt(chosenLoc).has_value()); + + vehicle->moveToAndUpdateSpatialIndex({ chosenLoc, dodgemPos.z }); + } + else + { + VehicleTrackSubposition subposition = VehicleTrackSubposition::standard; + if (carEntry.flags.has(CarEntryFlag::isChairlift)) + { + subposition = VehicleTrackSubposition::chairliftGoingOut; + } + + if (carEntry.flags.has(CarEntryFlag::isGoKart)) + { + // Choose which lane Go Kart should start in + subposition = VehicleTrackSubposition::goKartsLeftLane; + if (vehicleIndex & 1) + { + subposition = VehicleTrackSubposition::goKartsRightLane; + } + } + if (carEntry.flags.has(CarEntryFlag::isMiniGolf)) + { + subposition = VehicleTrackSubposition::miniGolfStart9; + vehicle->var_D3 = 0; + vehicle->mini_golf_current_animation = MiniGolfAnimation::walk; + vehicle->miniGolfFlags.clearAll(); + } + if (carEntry.flags.has(CarEntryFlag::isReverserCoasterBogie)) + { + if (vehicle->IsHead()) + { + subposition = VehicleTrackSubposition::reverserRCFrontBogie; + } + } + if (carEntry.flags.has(CarEntryFlag::isReverserCoasterPassengerCar)) + { + subposition = VehicleTrackSubposition::reverserRCRearBogie; + } + vehicle->TrackSubposition = subposition; + + auto chosenLoc = carPosition; + vehicle->TrackLocation = chosenLoc; + + int32_t direction = trackElement->getDirection(); + vehicle->orientation = direction << 3; + + if (ride.getRideTypeDescriptor().specialType == RtdSpecialType::spaceRings) + { + direction = 4; + } + else + { + if (rtd.flags.has(RtdFlag::vehicleIsIntegral)) + { + if (rtd.StartTrackPiece != TrackElemType::flatTrack1x4B) + { + if (rtd.StartTrackPiece != TrackElemType::flatTrack1x4A) + { + if (ride.getRideTypeDescriptor().specialType == RtdSpecialType::enterprise) + { + direction += 5; + } + else + { + direction = 4; + } + } + } + } + } + + chosenLoc += CoordsXYZ{ word_9A2A60[direction], rtd.Heights.VehicleZOffset }; + + vehicle->current_station = trackElement->GetStationIndex(); + + vehicle->moveTo(chosenLoc); + vehicle->SetTrackType(trackElement->GetTrackType()); + vehicle->SetTrackDirection(vehicle->orientation >> 3); + vehicle->track_progress = 31; + if (carEntry.flags.has(CarEntryFlag::isMiniGolf)) + { + vehicle->track_progress = 15; + } + vehicle->flags = { VehicleFlag::collisionDisabled }; + if (carEntry.flags.has(CarEntryFlag::hasInvertedSpriteSet)) + { + if (trackElement->IsInverted()) + { + vehicle->flags.set(VehicleFlag::carIsInverted); + } + } + vehicle->SetState(Vehicle::Status::movingToEndOfStation); + + if (ride.flags.has(RideFlag::reversedTrains)) + { + vehicle->SubType = carIndex == (ride.numCarsPerTrain - 1) ? Vehicle::Type::head : Vehicle::Type::tail; + vehicle->flags.set(VehicleFlag::carIsReversed); + } + } + + // Loc6DDD5E: + vehicle->num_peeps = 0; + vehicle->next_free_seat = 0; + vehicle->BoatLocation.SetNull(); + return vehicle; + } + + /** + * + * rct2: 0x006DD84C + */ + static TrainReference VehicleCreateTrain( + Ride& ride, const CoordsXYZ& trainPos, int32_t vehicleIndex, int32_t* remainingDistance, TrackElement* trackElement) + { + TrainReference train = { nullptr, nullptr }; + bool isReversed = ride.flags.has(RideFlag::reversedTrains); + + for (int32_t carIndex = 0; carIndex < ride.numCarsPerTrain; carIndex++) + { + auto carSpawnIndex = (isReversed) ? (ride.numCarsPerTrain - 1) - carIndex : carIndex; + + auto vehicle = RideEntryGetVehicleAtPosition(ride.subtype, ride.numCarsPerTrain, carSpawnIndex); + auto car = VehicleCreateCar(ride, vehicle, carSpawnIndex, vehicleIndex, trainPos, remainingDistance, trackElement); + if (car == nullptr) + break; + + if (carIndex == 0) + { + train.head = car; + } + else + { + // Link the previous car with this car + train.tail->next_vehicle_on_train = car->id; + train.tail->next_vehicle_on_ride = car->id; + car->prev_vehicle_on_ride = train.tail->id; + } + train.tail = car; + } + + return train; + } + + static bool VehicleCreateTrains(Ride& ride, const CoordsXYZ& trainsPos, TrackElement* trackElement, int16_t numberOfTrains) + { + TrainReference firstTrain = {}; + TrainReference lastTrain = {}; + int32_t remainingDistance = 0; + bool allTrainsCreated = true; + + for (int32_t vehicleIndex = 0; vehicleIndex < numberOfTrains; vehicleIndex++) + { + if (ride.isBlockSectioned()) + { + remainingDistance = 0; + } + TrainReference train = VehicleCreateTrain(ride, trainsPos, vehicleIndex, &remainingDistance, trackElement); + if (train.head == nullptr || train.tail == nullptr) + { + allTrainsCreated = false; + continue; + } + + if (vehicleIndex == 0) + { + firstTrain = train; + } + else + { + // Link the end of the previous train with the front of this train + lastTrain.tail->next_vehicle_on_ride = train.head->id; + train.head->prev_vehicle_on_ride = lastTrain.tail->id; + } + lastTrain = train; + + for (int32_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) + { + if (ride.vehicles[i].IsNull()) + { + ride.vehicles[i] = train.head->id; break; } } } + + // Link the first train and last train together. Nullptr checks are there to keep Clang happy. + if (lastTrain.tail != nullptr) + firstTrain.head->prev_vehicle_on_ride = lastTrain.tail->id; + if (firstTrain.head != nullptr) + lastTrain.tail->next_vehicle_on_ride = firstTrain.head->id; + + return allTrainsCreated; } - return subType; -} - -const StationObject* Ride::getStationObject() const -{ - auto& objManager = GetContext()->GetObjectManager(); - return objManager.GetLoadedObject(entranceStyle); -} - -const MusicObject* Ride::getMusicObject() const -{ - auto& objManager = GetContext()->GetObjectManager(); - return objManager.GetLoadedObject(music); -} - -// Normally, a station has at most one entrance and one exit, which are at the same height -// as the station. But in hacked parks, neither can be taken for granted. This code ensures -// that the ride.entrances and ride.exits arrays will point to one of them. There is -// an ever-so-slight chance two entrances/exits for the same station reside on the same tile. -// In cases like this, the one at station height will be considered the "true" one. -// If none exists at that height, newer and higher placed ones take precedence. -void DetermineRideEntranceAndExitLocations() -{ - LOG_VERBOSE("Inspecting ride entrance / exit locations"); - - auto& gameState = getGameState(); - for (auto& ride : RideManager(gameState)) + /** + * + * rct2: 0x006DDE9E + */ + static void RidecreateVehiclesFindFirstBlock(const Ride& ride, CoordsXYE* outXYElement) { - for (auto& station : ride.getStations()) + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[0]); + if (vehicle == nullptr) + return; + + auto curTrackPos = vehicle->TrackLocation; + auto curTrackElement = MapGetTrackElementAt(curTrackPos); + + assert(curTrackElement != nullptr); + + CoordsXY trackPos = curTrackPos; + auto trackElement = curTrackElement; + TrackBeginEnd trackBeginEnd; + while (trackBlockGetPrevious({ trackPos, reinterpret_cast(trackElement) }, &trackBeginEnd)) { - auto stationIndex = ride.getStationIndex(&station); - TileCoordsXYZD entranceLoc = station.Entrance; - TileCoordsXYZD exitLoc = station.Exit; - bool fixEntrance = false; - bool fixExit = false; - - // Skip if the station has no entrance - if (!entranceLoc.IsNull()) + trackPos = { trackBeginEnd.end_x, trackBeginEnd.end_y }; + trackElement = trackBeginEnd.begin_element->asTrack(); + if (trackPos == curTrackPos && trackElement == curTrackElement) { - const EntranceElement* entranceElement = MapGetRideEntranceElementAt(entranceLoc.ToCoordsXYZD(), false); - - if (entranceElement == nullptr || entranceElement->GetRideIndex() != ride.id - || entranceElement->GetStationIndex() != stationIndex) - { - fixEntrance = true; - } - else - { - station.Entrance.direction = entranceElement->getDirection(); - } + break; } - if (!exitLoc.IsNull()) + auto trackType = trackElement->GetTrackType(); + switch (trackType) { - const EntranceElement* entranceElement = MapGetRideExitElementAt(exitLoc.ToCoordsXYZD(), false); - - if (entranceElement == nullptr || entranceElement->GetRideIndex() != ride.id - || entranceElement->GetStationIndex() != stationIndex) + case TrackElemType::diagUp25ToFlat: + case TrackElemType::diagUp60ToFlat: + if (!trackElement->HasChain()) + { + break; + } + [[fallthrough]]; + case TrackElemType::diagBlockBrakes: { - fixExit = true; - } - else - { - station.Exit.direction = entranceElement->getDirection(); - } - } - - if (!fixEntrance && !fixExit) - { - continue; - } - - // At this point, we know we have a disconnected entrance or exit. - // Search the map to find it. Skip the outer ring of invisible tiles. - bool alreadyFoundEntrance = false; - bool alreadyFoundExit = false; - for (int32_t y = 1; y < gameState.mapSize.y - 1; y++) - { - for (int32_t x = 1; x < gameState.mapSize.x - 1; x++) - { - TileElement* tileElement = MapGetFirstElementAt(TileCoordsXY{ x, y }); + TileElement* tileElement = MapGetTrackElementAtOfTypeSeq( + { trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }, trackType, 0); if (tileElement != nullptr) { - do - { - if (tileElement->getType() != TileElementType::entrance) - { - continue; - } - const EntranceElement* entranceElement = tileElement->asEntrance(); - if (entranceElement->GetRideIndex() != ride.id) - { - continue; - } - if (entranceElement->GetStationIndex() != stationIndex) - { - continue; - } - - // The expected height is where entrances and exit reside in non-hacked parks. - const uint8_t expectedHeight = station.Height; - - if (fixEntrance && entranceElement->GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE) - { - if (alreadyFoundEntrance) - { - if (station.Entrance.z == expectedHeight) - continue; - if (station.Entrance.z > entranceElement->baseHeight) - continue; - } - - // Found our entrance - station.Entrance = { x, y, entranceElement->baseHeight, entranceElement->getDirection() }; - alreadyFoundEntrance = true; - - LOG_VERBOSE( - "Fixed disconnected entrance of ride %d, station %d to x = %d, y = %d and z = %d.", ride.id, - stationIndex, x, y, entranceElement->baseHeight); - } - else if (fixExit && entranceElement->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) - { - if (alreadyFoundExit) - { - if (station.Exit.z == expectedHeight) - continue; - if (station.Exit.z > entranceElement->baseHeight) - continue; - } - - // Found our exit - station.Exit = { x, y, entranceElement->baseHeight, entranceElement->getDirection() }; - alreadyFoundExit = true; - - LOG_VERBOSE( - "Fixed disconnected exit of ride %d, station %d to x = %d, y = %d and z = %d.", ride.id, - stationIndex, x, y, entranceElement->baseHeight); - } - } while (!(tileElement++)->isLastForTile()); + outXYElement->x = trackBeginEnd.begin_x; + outXYElement->y = trackBeginEnd.begin_y; + outXYElement->element = tileElement; + return; } + break; + } + case TrackElemType::up25ToFlat: + case TrackElemType::up60ToFlat: + if (!trackElement->HasChain()) + { + break; + } + [[fallthrough]]; + case TrackElemType::endStation: + case TrackElemType::blockBrakes: + *outXYElement = { trackPos, reinterpret_cast(trackElement) }; + return; + default: + break; + } + } + + outXYElement->x = curTrackPos.x; + outXYElement->y = curTrackPos.y; + outXYElement->element = reinterpret_cast(curTrackElement); + } + + /** + * Create and place the rides vehicles + * rct2: 0x006DD84C + */ + ResultWithMessage Ride::createVehicles(const CoordsXYE& element, bool isApplying, bool isSimulating) + { + updateMaxVehicles(); + if (subtype == kObjectEntryIndexNull) + { + return { true }; + } + + // Check if there are enough free sprite slots for all the vehicles + int32_t numberOfTrains = numTrains; + if (isBlockSectioned() && isSimulating) + { + numberOfTrains = 1; + } + int32_t totalCars = numberOfTrains * numCarsPerTrain; + if (totalCars > count_free_misc_sprite_slots()) + { + return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; + } + + if (!isApplying) + { + return { true }; + } + + auto* trackElement = element.element->asTrack(); + auto vehiclePos = CoordsXYZ{ element, element.element->getBaseZ() }; + int32_t direction = trackElement->getDirection(); + + // + if (mode == RideMode::stationToStation) + { + vehiclePos -= CoordsXYZ{ CoordsDirectionDelta[direction], 0 }; + + trackElement = MapGetTrackElementAt(vehiclePos); + + vehiclePos.z = trackElement->getBaseZ(); + } + + if (!VehicleCreateTrains(*this, vehiclePos, trackElement, numberOfTrains)) + { + // This flag is needed for Ride::removeVehicles() + flags.set(RideFlag::onTrack); + removeVehicles(); + return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; + } + // return true; + + // Initialise station departs + // 006DDDD0: + flags.set(RideFlag::onTrack); + for (int32_t i = 0; i < Limits::kMaxStationsPerRide; i++) + { + stations[i].Depart = (stations[i].Depart & kStationDepartFlag) | 1; + } + + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::spaceRings && !rtd.flags.has(RtdFlag::vehicleIsIntegral)) + { + if (isBlockSectioned() && !isSimulating) + { + CoordsXYE firstBlock{}; + RidecreateVehiclesFindFirstBlock(*this, &firstBlock); + moveTrainsToBlockBrakes( + { firstBlock.x, firstBlock.y, firstBlock.element->getBaseZ() }, *firstBlock.element->asTrack()); + } + else + { + for (int32_t i = 0; i < numTrains; i++) + { + Vehicle* vehicle = getGameState().entities.GetEntity(vehicles[i]); + if (vehicle == nullptr) + { + continue; + } + + auto carEntry = vehicle->Entry(); + + if (!carEntry->flags.has(CarEntryFlag::useDodgemCarPlacement)) + { + vehicle->UpdateTrackMotion(nullptr); + } + + vehicle->EnableCollisionsForTrain(); } } + } + RideUpdateVehicleColours(*this); + return { true }; + } - if (fixEntrance && !alreadyFoundEntrance) + /** + * Move all the trains so each one will be placed at the block brake of a different block. + * The first vehicle will placed into the first block and all other vehicles in the blocks + * preceding that block. + * rct2: 0x006DDF9C + */ + void Ride::moveTrainsToBlockBrakes(const CoordsXYZ& firstBlockPosition, TrackElement& firstBlock) + { + // If the ride has a cable lift, we don't want to fetch the cable lift element and the block preceding it + TrackElement* cableLiftTileElement = nullptr; + TrackElement* cableLiftPreviousBlock = nullptr; + if (flags.has(RideFlag::cableLiftHillComponentUsed)) + { + cableLiftTileElement = MapGetTrackElementAt(cableLiftLoc); + if (cableLiftTileElement != nullptr) { - station.Entrance.SetNull(); - LOG_VERBOSE("Cleared disconnected entrance of ride %d, station %d.", ride.id, stationIndex); - } - if (fixExit && !alreadyFoundExit) - { - station.Exit.SetNull(); - LOG_VERBOSE("Cleared disconnected exit of ride %d, station %d.", ride.id, stationIndex); + CoordsXYZ location = cableLiftLoc; + cableLiftPreviousBlock = trackGetPreviousBlock(location, reinterpret_cast(cableLiftTileElement)); } } - } -} -void RideClearLeftoverEntrances(const Ride& ride) -{ - auto& gameState = getGameState(); - for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) - { - for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) + for (int32_t i = 0; i < numTrains; i++) { - for (auto* entrance : TileElementsView(tilePos.ToCoordsXY())) - { - const bool isRideEntranceExit = entrance->GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE - || entrance->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT; - if (!isRideEntranceExit) - continue; - if (entrance->GetRideIndex() != ride.id) - continue; + auto train = getGameState().entities.GetEntity(vehicles[i]); + if (train == nullptr) + continue; - TileElementRemove(entrance->as()); + // At this point, all vehicles have state of MovingToEndOfStation, which slowly moves forward at a constant speed + // regardless of incline. The first vehicle stops at the station immediately, while all other vehicles seek forward + // until they reach a closed block brake. The block brake directly before the station is set to closed every frame + // because the trains will open the block brake when the tail leaves the station. Brakes have no effect at this + // time, so do not set linked brakes when closing the first block. + train->UpdateTrackMotion(nullptr); + + if (i == 0) + { + train->EnableCollisionsForTrain(); + continue; + } + + size_t numIterations = 0; + do + { + // Fixes both freezing issues in #15503. + // TODO: refactor the code so a tortoise-and-hare algorithm can be used. + if (numIterations++ > 1000000) + { + break; + } + + // Setting the first block before the cable lift to the same state as the cable lift ensures that any train + // which would be placed on the cable lift will instead stop on the block before it. As there can only be one + // cable lift per ride and there must always be at least one block left free, there will be enough blocks + // remaining. This fixes the bug in #1122. + if (cableLiftTileElement != nullptr && cableLiftPreviousBlock != nullptr) + { + cableLiftPreviousBlock->SetBrakeClosed(cableLiftTileElement->IsBrakeClosed()); + } + firstBlock.SetBrakeClosed(true); + for (Vehicle* car = train; car != nullptr; + car = getGameState().entities.GetEntity(car->next_vehicle_on_train)) + { + car->velocity = 0; + car->acceleration = 0; + car->SwingSprite = 0; + car->remaining_distance += 13962; + } + } while (!(train->UpdateTrackMotion(nullptr) & VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE)); + + // All vehicles are in position, set the block brake directly before the station one last time and make sure the + // brakes are set appropriately + SetBrakeClosedMultiTile(firstBlock, firstBlockPosition, true); + if (trackTypeIsBlockBrakes(firstBlock.GetTrackType())) + { + BlockBrakeSetLinkedBrakesClosed(firstBlockPosition, firstBlock, true); + } + for (Vehicle* car = train; car != nullptr; + car = getGameState().entities.GetEntity(car->next_vehicle_on_train)) + { + car->flags.unset(VehicleFlag::collisionDisabled); + car->SetState(Vehicle::Status::travelling, car->sub_state); + if ((car->GetTrackType()) == TrackElemType::endStation) + { + car->SetState(Vehicle::Status::movingToEndOfStation, car->sub_state); + } } } - } -} -std::string Ride::getName() const -{ - Formatter ft; - formatNameTo(ft); - return FormatStringIDLegacy(STR_STRINGID, reinterpret_cast(ft.Data())); -} - -void Ride::formatNameTo(Formatter& ft) const -{ - if (!customName.empty()) - { - auto str = customName.c_str(); - ft.Add(STR_STRING); - ft.Add(str); - } - else - { - const auto rideTypeName = getTypeNaming().Name; - ft.Add(1).Add(rideTypeName).Add(defaultNameNumber); - } -} - -uint64_t Ride::getAvailableModes() const -{ - if (getGameState().cheats.showAllOperatingModes) - return kAllRideModesAvailable; - - return getRideTypeDescriptor().RideModes; -} - -const RideTypeDescriptor& Ride::getRideTypeDescriptor() const -{ - return ::GetRideTypeDescriptor(type); -} - -RideNaming Ride::getTypeNaming() const -{ - return GetRideNaming(type, getRideEntry()); -} - -uint8_t Ride::getNumShelteredSections() const -{ - return numShelteredSections & ShelteredSectionsBits::kNumShelteredSectionsMask; -} - -void Ride::increaseNumShelteredSections() -{ - auto newNumShelteredSections = getNumShelteredSections(); - if (newNumShelteredSections != 0x1F) - newNumShelteredSections++; - numShelteredSections &= ~ShelteredSectionsBits::kNumShelteredSectionsMask; - numShelteredSections |= newNumShelteredSections; -} - -void Ride::updateRideTypeForAllPieces() -{ - auto& gameState = getGameState(); - for (int32_t y = 0; y < gameState.mapSize.y; y++) - { - for (int32_t x = 0; x < gameState.mapSize.x; x++) + // After all trains are in position, set the block preceding the cable lift to open. + if (cableLiftPreviousBlock != nullptr) { - auto* tileElement = MapGetFirstElementAt(TileCoordsXY(x, y)); + cableLiftPreviousBlock->SetBrakeClosed(false); + } + } + + static bool RideGetStationTile(const Ride& ride, CoordsXYE* output) + { + for (const auto& station : ride.getStations()) + { + CoordsXYZ trackStart = station.GetStart(); + if (trackStart.IsNull()) + continue; + + TileElement* tileElement = MapGetTrackElementAtOfType(trackStart, TrackElemType::endStation); if (tileElement == nullptr) continue; + *output = { trackStart.x, trackStart.y, tileElement }; + return true; + } + return false; + } + + /** + * Checks and initialises the cable lift track returns false if unable to find + * appropriate track. + * rct2: 0x006D31A6 + */ + static ResultWithMessage RideInitialiseCableLiftTrack(const Ride& ride, bool isApplying) + { + // Despawn existing cable lift tiles + CoordsXYE stationTile; + if (!RideGetStationTile(ride, &stationTile)) + return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; + + if (isApplying) + { + // In case circuit is incomplete, find the start of the track in order to ensure all tiles connected + // to the station are cleared + RideGetStartOfTrack(&stationTile); + + TrackCircuitIterator it; + trackCircuitIteratorBegin(&it, stationTile); + while (trackCircuitIteratorNext(&it)) + { + TileElement* tileElement = it.current.element; + GetTrackElementOriginAndApplyChanges( + { { it.current, tileElement->getBaseZ() }, tileElement->getDirection() }, + tileElement->asTrack()->GetTrackType(), 0, &tileElement, { TrackElementSetFlag::cableLiftOff }); + } + } + + // Spawn new cable lift tiles + auto cableLiftTileElement = MapGetTrackElementAt(ride.cableLiftLoc); + CoordsXYE cableLiftCoords = { ride.cableLiftLoc, reinterpret_cast(cableLiftTileElement) }; + if (cableLiftTileElement == nullptr) + return { false }; + + TrackCircuitIterator it; + trackCircuitIteratorBegin(&it, cableLiftCoords); + while (trackCircuitIteratorPrevious(&it)) + { + TileElement* tileElement = it.current.element; + auto trackType = tileElement->asTrack()->GetTrackType(); + switch (trackType) + { + case TrackElemType::up25: + case TrackElemType::up60: + case TrackElemType::flatToUp25: + case TrackElemType::up25ToFlat: + case TrackElemType::up25ToUp60: + case TrackElemType::up60ToUp25: + case TrackElemType::flatToUp60LongBase: + case TrackElemType::flat: + if (isApplying) + { + GetTrackElementOriginAndApplyChanges( + { { it.current, tileElement->getBaseZ() }, tileElement->getDirection() }, trackType, 0, + &tileElement, { TrackElementSetFlag::cableLiftOn }); + } + break; + case TrackElemType::endStation: + case TrackElemType::blockBrakes: + return { true }; + default: + return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; + } + } + return { false, STR_CABLE_LIFT_HILL_MUST_START_IMMEDIATELY_AFTER_STATION_OR_BLOCK_BRAKE }; + } + + /** + * + * rct2: 0x006DF4D4 + */ + static ResultWithMessage RideCreateCableLift(RideId rideIndex, bool isApplying) + { + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return { false }; + + if (ride->mode != RideMode::continuousCircuitBlockSectioned && ride->mode != RideMode::continuousCircuit) + { + return { false, STR_CABLE_LIFT_UNABLE_TO_WORK_IN_THIS_OPERATING_MODE }; + } + + if (ride->numCircuits > 1) + { + return { false, STR_MULTICIRCUIT_NOT_POSSIBLE_WITH_CABLE_LIFT_HILL }; + } + + if (count_free_misc_sprite_slots() <= 5) + { + return { false, STR_UNABLE_TO_CREATE_ENOUGH_VEHICLES }; + } + + auto cableLiftInitialiseResult = RideInitialiseCableLiftTrack(*ride, isApplying); + if (!cableLiftInitialiseResult.Successful) + { + return { false, cableLiftInitialiseResult.Message }; + } + + if (!isApplying) + { + return { true }; + } + + auto cableLiftLoc = ride->cableLiftLoc; + auto tileElement = MapGetTrackElementAt(cableLiftLoc); + int32_t direction = tileElement->getDirection(); + + Vehicle* head = nullptr; + Vehicle* tail = nullptr; + uint32_t ebx = 0; + for (int32_t i = 0; i < 5; i++) + { + uint32_t edx = Numerics::ror32(0x15478, 10); + uint16_t var_44 = edx & 0xFFFF; + edx = Numerics::rol32(edx, 10) >> 1; + ebx -= edx; + int32_t remaining_distance = ebx; + ebx -= edx; + + Vehicle* current = CableLiftSegmentCreate( + *ride, cableLiftLoc.x, cableLiftLoc.y, cableLiftLoc.z / 8, direction, var_44, remaining_distance, i == 0); + current->next_vehicle_on_train = EntityId::GetNull(); + if (i == 0) + { + head = current; + } + else + { + tail->next_vehicle_on_train = current->id; + tail->next_vehicle_on_ride = current->id; + current->prev_vehicle_on_ride = tail->id; + } + tail = current; + } + head->prev_vehicle_on_ride = tail->id; + tail->next_vehicle_on_ride = head->id; + + ride->flags.set(RideFlag::cableLift); + head->CableLiftUpdateTrackMotion(); + return { true }; + } + + /** + * Opens the construction window prompting to construct a missing entrance or exit. + * This will also move the screen to the first station missing the entrance or exit. + * rct2: 0x006B51C0 + */ + void Ride::constructMissingEntranceOrExit() const + { + auto* w = WindowGetMain(); + if (w == nullptr) + return; + + int8_t entranceOrExit = -1; + const RideStation* incompleteStation = nullptr; + for (const auto& station : stations) + { + if (station.Start.IsNull()) + continue; + + if (station.Entrance.IsNull()) + { + entranceOrExit = WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE; + incompleteStation = &station; + break; + } + + if (station.Exit.IsNull()) + { + entranceOrExit = WC_RIDE_CONSTRUCTION__WIDX_EXIT; + incompleteStation = &station; + break; + } + } + + if (incompleteStation == nullptr) + { // No station with a missing entrance or exit was found + return; + } + + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::maze) + { + auto location = incompleteStation->GetStart(); + WindowScrollToLocation(*w, location); + + CoordsXYE trackElement; + RideTryGetOriginElement(*this, &trackElement); + findTrackGap(*this, trackElement, &trackElement); + int32_t ok = RideModify(trackElement); + if (ok == 0) + { + return; + } + + auto* windowMgr = Ui::GetWindowManager(); + w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr) + w->onMouseUp(entranceOrExit); + } + } + + /** + * + * rct2: 0x006B528A + */ + static void RideScrollToTrackError(const CoordsXYE& trackElement) + { + if (trackElement.element == nullptr) + return; + + auto* w = WindowGetMain(); + if (w != nullptr) + { + WindowScrollToLocation(*w, { trackElement, trackElement.element->getBaseZ() }); + RideModify(trackElement); + } + } + + /** + * + * rct2: 0x006B4F6B + */ + TrackElement* Ride::getOriginElement(StationIndex stationIndex) const + { + auto stationLoc = getStation(stationIndex).Start; + TileElement* tileElement = MapGetFirstElementAt(stationLoc); + if (tileElement == nullptr) + return nullptr; + do + { + if (tileElement->getType() != TileElementType::track) + continue; + + auto* trackElement = tileElement->asTrack(); + const auto& ted = GetTrackElementDescriptor(trackElement->GetTrackType()); + if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + continue; + + if (trackElement->GetRideIndex() == id) + return trackElement; + } while (!(tileElement++)->isLastForTile()); + + return nullptr; + } + + ResultWithMessage Ride::test(bool isApplying) + { + if (type == kRideTypeNull) + { + LOG_WARNING("Invalid ride type for ride %u", id.ToUnderlying()); + return { false }; + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByNumber(WindowClass::rideConstruction, id.ToUnderlying()); + + StationIndex stationIndex = {}; + auto message = changeStatusDoStationChecks(stationIndex); + if (!message.Successful) + { + return message; + } + + auto entranceExitCheck = RideCheckForEntranceExit(id); + if (!entranceExitCheck.Successful) + { + constructMissingEntranceOrExit(); + return { false, entranceExitCheck.Message }; + } + + CoordsXYE trackElement = {}; + message = changeStatusGetStartElement(stationIndex, trackElement); + if (!message.Successful) + { + return message; + } + + message = changeStatusCheckCompleteCircuit(trackElement); + if (!message.Successful) + { + return message; + } + + message = changeStatusCheckTrackValidity(trackElement, false); + if (!message.Successful) + { + return message; + } + + return changeStatusCreateVehicles(isApplying, trackElement, false); + } + + ResultWithMessage Ride::simulate(bool isApplying) + { + CoordsXYE trackElement = {}; + if (type == kRideTypeNull) + { + LOG_WARNING("Invalid ride type for ride %u", id.ToUnderlying()); + return { false }; + } + + StationIndex stationIndex = {}; + auto message = changeStatusDoStationChecks(stationIndex); + if (!message.Successful) + { + return message; + } + + message = changeStatusGetStartElement(stationIndex, trackElement); + if (!message.Successful) + { + return message; + } + + message = changeStatusCheckTrackValidity(trackElement, true); + if (!message.Successful) + { + return message; + } + + return changeStatusCreateVehicles(isApplying, trackElement, true); + } + + /** + * + * rct2: 0x006B4EEA + */ + ResultWithMessage Ride::open(bool isApplying) + { + // Check to see if construction tool is in use. If it is close the construction window + // to set the track to its final state and clean up ghosts. + // We can't just call close as it would cause a stack overflow during shop creation + // with auto open on. + if (isToolActive(WindowClass::rideConstruction, static_cast(id.ToUnderlying()))) + { + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->CloseByNumber(WindowClass::rideConstruction, id.ToUnderlying()); + } + + StationIndex stationIndex = {}; + auto message = changeStatusDoStationChecks(stationIndex); + if (!message.Successful) + { + return message; + } + + auto entranceExitCheck = RideCheckForEntranceExit(id); + if (!entranceExitCheck.Successful) + { + constructMissingEntranceOrExit(); + return { false, entranceExitCheck.Message }; + } + + if (isApplying) + { + chainQueues(); + flags.set(RideFlag::everBeenOpened); + } + + CoordsXYE trackElement = {}; + message = changeStatusGetStartElement(stationIndex, trackElement); + if (!message.Successful) + { + return message; + } + + message = changeStatusCheckCompleteCircuit(trackElement); + if (!message.Successful) + { + return message; + } + + message = changeStatusCheckTrackValidity(trackElement, false); + if (!message.Successful) + { + return message; + } + + return changeStatusCreateVehicles(isApplying, trackElement, false); + } + + /** + * Given a track element of the ride, find the start of the track. + * It has to do this as a backwards loop in case this is an incomplete track. + */ + void RideGetStartOfTrack(CoordsXYE* output) + { + TrackBeginEnd trackBeginEnd; + CoordsXYE trackElement = *output; + if (trackBlockGetPrevious(trackElement, &trackBeginEnd)) + { + TileElement* initial_map = trackElement.element; + TrackBeginEnd slowIt = trackBeginEnd; + bool moveSlowIt = true; + do + { + // Because we are working backwards, begin_element is the section at the end of a piece of track, whereas + // begin_x and begin_y are the coordinates at the start of a piece of track, so we need to pass end_x and + // end_y + CoordsXYE lastGood = { + /* .x = */ trackBeginEnd.end_x, + /* .y = */ trackBeginEnd.end_y, + /* .element = */ trackBeginEnd.begin_element, + }; + + if (!trackBlockGetPrevious( + { trackBeginEnd.end_x, trackBeginEnd.end_y, trackBeginEnd.begin_element }, &trackBeginEnd)) + { + trackElement = lastGood; + break; + } + + moveSlowIt = !moveSlowIt; + if (moveSlowIt) + { + if (!trackBlockGetPrevious({ slowIt.end_x, slowIt.end_y, slowIt.begin_element }, &slowIt) + || slowIt.begin_element == trackBeginEnd.begin_element) + { + break; + } + } + } while (initial_map != trackBeginEnd.begin_element); + } + *output = trackElement; + } + + /** + * + * rct2: 0x00696707 + */ + void Ride::stopGuestsQueuing() + { + for (auto peep : EntityList()) + { + if (peep->State != PeepState::queuing) + continue; + if (peep->CurrentRide != id) + continue; + + peep->removeFromQueue(); + peep->SetState(PeepState::falling); + } + } + + RideMode Ride::getDefaultMode() const + { + return getRideTypeDescriptor().DefaultMode; + } + + static bool RideTypeWithTrackColoursExists(ride_type_t rideType, const TrackColour& colours) + { + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + { + if (ride.type != rideType) + continue; + if (ride.trackColours[0].main != colours.main) + continue; + if (ride.trackColours[0].additional != colours.additional) + continue; + if (ride.trackColours[0].supports != colours.supports) + continue; + + return true; + } + return false; + } + + bool Ride::nameExists(std::string_view name, RideId excludeRideId) + { + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) + { + if (ride.id != excludeRideId) + { + Formatter ft; + ride.formatNameTo(ft); + + char buffer[256]{}; + FormatStringLegacy(buffer, 256, STR_STRINGID, ft.Data()); + if (name == buffer && RideHasAnyTrackElements(ride)) + { + return true; + } + } + } + return false; + } + + int32_t RideGetRandomColourPresetIndex(ride_type_t rideType) + { + if (rideType >= std::size(kRideTypeDescriptors)) + { + return 0; + } + + // Find all the presets that haven't yet been used in the park for this ride type + const auto& colourPresets = GetRideTypeDescriptor(rideType).ColourPresets; + std::vector unused; + unused.reserve(colourPresets.count); + for (uint8_t i = 0; i < colourPresets.count; i++) + { + const auto& colours = colourPresets.list[i]; + if (!RideTypeWithTrackColoursExists(rideType, colours)) + { + unused.push_back(static_cast(i)); + } + } + + // If all presets have been used, just go with a random preset + if (unused.empty()) + return UtilRand() % colourPresets.count; + + // Choose a random preset from the list of unused presets + auto unusedIndex = UtilRand() % unused.size(); + return unused[unusedIndex]; + } + + /** + * + * Based on rct2: 0x006B4776 + */ + void Ride::setColourPreset(uint8_t trackColourPreset, uint8_t vehicleColourPreset) + { + const TrackColourPresetList* colourPresets = &getRideTypeDescriptor().ColourPresets; + TrackColour colours = { Drawing::Colour::black, Drawing::Colour::black, Drawing::Colour::black }; + // Stalls save their default colour in the vehicle settings (since they share a common ride type) + if (!isRide()) + { + const auto* rideEntry = GetRideEntryByIndex(subtype); + if (rideEntry != nullptr && rideEntry->vehicle_preset_list->count > 0) + { + if (vehicleColourPreset < rideEntry->vehicle_preset_list->count) + { + auto list = rideEntry->vehicle_preset_list->list[vehicleColourPreset]; + colours = { list.Body, list.Trim, list.Tertiary }; + } + } + } + else if (trackColourPreset < colourPresets->count) + { + colours = colourPresets->list[trackColourPreset]; + } + for (size_t i = 0; i < std::size(trackColours); i++) + { + trackColours[i].main = colours.main; + trackColours[i].additional = colours.additional; + trackColours[i].supports = colours.supports; + } + vehicleColourSettings = VehicleColourSettings::same; + } + + money64 RideGetCommonPrice(const Ride& forRide) + { + auto& gameState = getGameState(); + for (const auto& ride : RideManager(gameState)) + { + if (ride.type == forRide.type && ride.id != forRide.id) + { + return ride.price[0]; + } + } + + return kMoney64Undefined; + } + + void Ride::setNameToDefault() + { + char rideNameBuffer[256]{}; + + // Increment default name number until we find a unique name + customName = {}; + defaultNameNumber = 0; + do + { + defaultNameNumber++; + Formatter ft; + formatNameTo(ft); + FormatStringLegacy(rideNameBuffer, 256, STR_STRINGID, ft.Data()); + } while (nameExists(rideNameBuffer, id)); + } + + /** + * This will return the name of the ride, as seen in the New Ride window. + */ + RideNaming GetRideNaming(const ride_type_t rideType, const RideObjectEntry* rideEntry) + { + const auto& rtd = GetRideTypeDescriptor(rideType); + if (rtd.flags.has(RtdFlag::listVehiclesSeparately) && rideEntry != nullptr) + { + return rideEntry->naming; + } + + return rtd.Naming; + } + + /* + * The next eight functions are helpers to access ride data at the offset 10E & + * 110. Known as the turn counts. There are 3 different types (default, banked, sloped) + * and there are 4 counts as follows: + * + * 1 element turns: low 5 bits + * 2 element turns: bits 6-8 + * 3 element turns: bits 9-11 + * 4 element or more turns: bits 12-15 + * + * 4 plus elements only possible on sloped type. Falls back to 3 element + * if by some miracle you manage 4 element none sloped. + */ + + void IncrementTurnCount1Element(Ride& ride, uint8_t type) + { + uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return; + } + uint16_t value = (*turn_count & kTurnMask1Element) + 1; + *turn_count &= ~kTurnMask1Element; + + if (value > kTurnMask1Element) + value = kTurnMask1Element; + *turn_count |= value; + } + + void IncrementTurnCount2Elements(Ride& ride, uint8_t type) + { + uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return; + } + uint16_t value = (*turn_count & kTurnMask2Elements) + 0x20; + *turn_count &= ~kTurnMask2Elements; + + if (value > kTurnMask2Elements) + value = kTurnMask2Elements; + *turn_count |= value; + } + + void IncrementTurnCount3Elements(Ride& ride, uint8_t type) + { + uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return; + } + uint16_t value = (*turn_count & kTurnMask3Elements) + 0x100; + *turn_count &= ~kTurnMask3Elements; + + if (value > kTurnMask3Elements) + value = kTurnMask3Elements; + *turn_count |= value; + } + + void IncrementTurnCount4PlusElements(Ride& ride, uint8_t type) + { + uint16_t* turn_count; + switch (type) + { + case 0: + case 1: + // Just in case fallback to 3 element turn + IncrementTurnCount3Elements(ride, type); + return; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return; + } + uint16_t value = (*turn_count & kTurnMask4PlusElements) + 0x800; + *turn_count &= ~kTurnMask4PlusElements; + + if (value > kTurnMask4PlusElements) + value = kTurnMask4PlusElements; + *turn_count |= value; + } + + int32_t GetTurnCount1Element(const Ride& ride, uint8_t type) + { + const uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return 0; + } + + return (*turn_count) & kTurnMask1Element; + } + + int32_t GetTurnCount2Elements(const Ride& ride, uint8_t type) + { + const uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return 0; + } + + return ((*turn_count) & kTurnMask2Elements) >> 5; + } + + int32_t GetTurnCount3Elements(const Ride& ride, uint8_t type) + { + const uint16_t* turn_count; + switch (type) + { + case 0: + turn_count = &ride.turnCountDefault; + break; + case 1: + turn_count = &ride.turnCountBanked; + break; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return 0; + } + + return ((*turn_count) & kTurnMask3Elements) >> 8; + } + + int32_t GetTurnCount4PlusElements(const Ride& ride, uint8_t type) + { + const uint16_t* turn_count; + switch (type) + { + case 0: + case 1: + return 0; + case 2: + turn_count = &ride.turnCountSloped; + break; + default: + return 0; + } + + return ((*turn_count) & kTurnMask4PlusElements) >> 11; + } + + bool Ride::hasSpinningTunnel() const + { + return specialTrackElements.has(SpecialElement::spinningTunnel); + } + + bool Ride::hasWaterSplash() const + { + return specialTrackElements.has(SpecialElement::splash); + } + + bool Ride::hasRapids() const + { + return specialTrackElements.has(SpecialElement::rapids); + } + + bool Ride::hasLogReverser() const + { + return specialTrackElements.has(SpecialElement::reverser); + } + + bool Ride::hasWaterfall() const + { + return specialTrackElements.has(SpecialElement::waterfall); + } + + bool Ride::hasWhirlpool() const + { + return specialTrackElements.has(SpecialElement::whirlpool); + } + + bool Ride::isPoweredLaunched() const + { + return mode == RideMode::poweredLaunchPassthrough || mode == RideMode::poweredLaunch + || mode == RideMode::poweredLaunchBlockSectioned; + } + + bool Ride::isBlockSectioned() const + { + return mode == RideMode::continuousCircuitBlockSectioned || mode == RideMode::poweredLaunchBlockSectioned; + } + + bool RideHasAnyTrackElements(const Ride& ride) + { + TileElementIterator it; + + TileElementIteratorBegin(&it); + while (TileElementIteratorNext(&it)) + { + if (it.element->getType() != TileElementType::track) + continue; + if (it.element->asTrack()->GetRideIndex() != ride.id) + continue; + if (it.element->isGhost()) + continue; + + return true; + } + + return false; + } + + /** + * + * rct2: 0x006B59C6 + */ + void InvalidateTestResults(Ride& ride) + { + ride.measurement = {}; + ride.ratings.setNull(); + ride.flags.unset(RideFlag::tested, RideFlag::testInProgress); + if (ride.flags.has(RideFlag::onTrack)) + { + for (int32_t i = 0; i < ride.numTrains; i++) + { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle != nullptr) + { + vehicle->flags.unset(VehicleFlag::testing); + } + } + } + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); + } + + /** + * + * rct2: 0x006B7481 + * + * @param rideIndex (dl) + * @param reliabilityIncreaseFactor (ax) + */ + void RideFixBreakdown(Ride& ride, int32_t reliabilityIncreaseFactor) + { + ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown, RideFlag::dueInspection); + ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); + + if (ride.flags.has(RideFlag::onTrack)) + { + for (int32_t i = 0; i < ride.numTrains; i++) + { + for (Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + { + vehicle->flags.unset( + VehicleFlag::stoppedBySafetyCutout, VehicleFlag::carIsBroken, VehicleFlag::trainIsBroken); + } + } + } + + uint8_t unreliability = 100 - ride.reliabilityPercentage; + ride.reliability += reliabilityIncreaseFactor * (unreliability / 2); + } + + /** + * + * rct2: 0x006DE102 + */ + void RideUpdateVehicleColours(const Ride& ride) + { + const auto& rtd = ride.getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::spaceRings || rtd.flags.has(RtdFlag::vehicleIsIntegral)) + { + GfxInvalidateScreen(); + } + + auto& entities = getGameState().entities; + for (int32_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) + { + int32_t carIndex = 0; + for (Vehicle* vehicle = entities.GetEntity(ride.vehicles[i]); vehicle != nullptr; + vehicle = entities.GetEntity(vehicle->next_vehicle_on_train)) + { + VehicleColour colours = {}; + switch (ride.vehicleColourSettings) + { + case VehicleColourSettings::same: + colours = ride.vehicleColours[0]; + break; + case VehicleColourSettings::perTrain: + colours = ride.vehicleColours[i]; + break; + case VehicleColourSettings::perCar: + { + const bool isReversed = vehicle->flags.has(VehicleFlag::carIsReversed); + const auto colourIndex = isReversed ? (ride.numCarsPerTrain - 1) - carIndex : carIndex; + colours = ride.vehicleColours[std::min(colourIndex, Limits::kMaxCarsPerTrain - 1)]; + break; + } + } + + vehicle->colours = colours; + vehicle->invalidate(); + carIndex++; + } + } + } + + uint8_t RideEntryGetVehicleAtPosition(int32_t rideEntryIndex, int32_t numCarsPerTrain, int32_t position) + { + const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); + if (position == 0 && rideEntry->FrontCar != 255) + { + return rideEntry->FrontCar; + } + if (position == 1 && rideEntry->SecondCar != 255) + { + return rideEntry->SecondCar; + } + if (position == 2 && rideEntry->ThirdCar != 255) + { + return rideEntry->ThirdCar; + } + if (position == numCarsPerTrain - 1 && rideEntry->RearCar != 255) + { + return rideEntry->RearCar; + } + + return rideEntry->DefaultCar; + } + + struct NecessarySpriteGroup + { + SpriteGroupType VehicleSpriteGroup; + SpritePrecision MinPrecision; + }; + + // Finds track pieces that a given ride entry has sprites for + BitSet RideEntryGetSupportedTrackPieces(const RideObjectEntry& rideEntry) + { + // TODO: Use a std::span when C++20 available as 6 is due to jagged array + static const std::array trackPieceRequiredSprites[] = { + { SpriteGroupType::slopeFlat, SpritePrecision::none }, // TrackGroup::flat + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::straight + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::stationEnd + { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::liftHill + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, + SpritePrecision::sprites4 }, // TrackGroup::liftHillSteep + { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::liftHillCurve + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites16 }, // TrackGroup::flatRollBanking + { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::verticalLoop + { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::slope + { SpriteGroupType::slopes60, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepDown + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, + SpritePrecision::sprites4 }, // TrackGroup::flatToSteepSlope + { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::slopeCurve + { SpriteGroupType::slopes60, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveSteep + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::sBend + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveVerySmall + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveSmall + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curve + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::curveLarge + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites4, SpriteGroupType::flatBanked67, SpritePrecision::sprites4, + SpriteGroupType::flatBanked90, SpritePrecision::sprites4, SpriteGroupType::inlineTwists, + SpritePrecision::sprites4, SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::twist + { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoop + { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::corkscrew + { SpriteGroupType::slopeFlat, SpritePrecision::none }, // TrackGroup::tower + { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixUpBankedHalf + { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixDownBankedHalf + { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixUpBankedQuarter + { SpriteGroupType::flatBanked45, SpritePrecision::sprites16 }, // TrackGroup::helixDownBankedQuarter + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::helixUpUnbankedQuarter + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::helixDownUnbankedQuarter + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::brakes + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::onridePhoto + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes12, + SpritePrecision::sprites4 }, // TrackGroup::waterSplash + { SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::slopeVertical + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites4, SpriteGroupType::inlineTwists, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::barrelRoll + { SpriteGroupType::slopes25, SpritePrecision::sprites4 }, // TrackGroup::poweredLift + { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoopLarge + { SpriteGroupType::slopes12Banked22, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveBanked + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::logFlumeReverser + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites4, SpriteGroupType::inlineTwists, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::heartlineRoll + { SpriteGroupType::slopeFlat, SpritePrecision::sprites16 }, // TrackGroup::reverser + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes25, SpritePrecision::sprites4, + SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4 }, // TrackGroup::reverseFreefall + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4, SpriteGroupType::slopes25, SpritePrecision::sprites4, + SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4 }, // TrackGroup::slopeToFlat + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::blockBrakes + { SpriteGroupType::slopes25Banked22, SpritePrecision::sprites4 }, // TrackGroup::slopeRollBanking + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, + SpritePrecision::sprites4 }, // TrackGroup::slopeSteepLong + { SpriteGroupType::slopes90, SpritePrecision::sprites16 }, // TrackGroup::curveVertical + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, + SpritePrecision::sprites4 }, // TrackGroup::liftHillCable + { SpriteGroupType::curvedLiftHillUp, SpritePrecision::sprites16 }, // TrackGroup::liftHillCurved + { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoop + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::spinningTunnel + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::booster + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites4, SpriteGroupType::flatBanked67, SpritePrecision::sprites4, + SpriteGroupType::flatBanked90, SpritePrecision::sprites4, SpriteGroupType::inlineTwists, + SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::inlineTwistUninverted + { SpriteGroupType::flatBanked22, SpritePrecision::sprites4, SpriteGroupType::flatBanked45, + SpritePrecision::sprites4, SpriteGroupType::flatBanked67, SpritePrecision::sprites4, + SpriteGroupType::flatBanked90, SpritePrecision::sprites4, SpriteGroupType::inlineTwists, + SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::inlineTwistInverted + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::quarterLoopUninvertedUp + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::quarterLoopUninvertedDown + { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoopInvertedUp + { SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::quarterLoopInvertedDown + { SpriteGroupType::slopes12, SpritePrecision::sprites4 }, // TrackGroup::rapids + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopUninvertedUp + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, + SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopInvertedDown + {}, // TrackGroup::flatRideBase + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::waterfall + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::whirlpool + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, + SpritePrecision::sprites4 }, // TrackGroup::brakeForDrop + { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::corkscrewUninverted + { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::corkscrewInverted + { SpriteGroupType::slopes12, SpritePrecision::sprites4, SpriteGroupType::slopes25, + SpritePrecision::sprites4 }, // TrackGroup::heartlineTransfer + {}, // TrackGroup::miniGolfHole + { SpriteGroupType::slopeFlat, SpritePrecision::sprites4 }, // TrackGroup::rotationControlToggle + { SpriteGroupType::slopes60, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepUp + { SpriteGroupType::corkscrews, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::corkscrewLarge + { SpriteGroupType::slopes60, SpritePrecision::sprites4, SpriteGroupType::slopes75, SpritePrecision::sprites4, + SpriteGroupType::slopes90, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, SpritePrecision::sprites4, + SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::halfLoopMedium + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes12Banked22, + SpritePrecision::sprites4, SpriteGroupType::slopes25Banked22, SpritePrecision::sprites4, + SpriteGroupType::slopes25Banked45, SpritePrecision::sprites4, SpriteGroupType::inlineTwists, + SpritePrecision::sprites4, SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::zeroGRoll + { SpriteGroupType::slopes42Banked22, SpritePrecision::sprites4, SpriteGroupType::slopes42Banked45, + SpritePrecision::sprites4, SpriteGroupType::slopes42Banked67, SpritePrecision::sprites4, + SpriteGroupType::slopes42Banked90, SpritePrecision::sprites4, SpriteGroupType::slopes60Banked22, + SpritePrecision::sprites4 }, // TrackGroup::zeroGRollLarge + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopUninvertedUp + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, + SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopInvertedDown + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, SpritePrecision::sprites4, + SpriteGroupType::slopesLoop, SpritePrecision::sprites4, SpriteGroupType::slopeInverted, + SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopUninvertedDown + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::flyingLargeHalfLoopInvertedUp + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopInvertedUp + { SpriteGroupType::slopes25, SpritePrecision::sprites4, SpriteGroupType::slopes60, SpritePrecision::sprites4, + SpriteGroupType::slopes75, SpritePrecision::sprites4, SpriteGroupType::slopes90, + SpritePrecision::sprites4 }, // TrackGroup::flyingHalfLoopUninvertedDown + { SpriteGroupType::slopes25, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveLarge + { SpriteGroupType::slopes25Banked45, SpritePrecision::sprites16 }, // TrackGroup::slopeCurveLargeBanked + { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBrakes + { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBlockBrakes + { SpriteGroupType::slopes25, SpritePrecision::sprites8 }, // TrackGroup::inclinedBrakes + { SpriteGroupType::slopeFlat, SpritePrecision::sprites8 }, // TrackGroup::diagBooster + { SpriteGroupType::slopes8, SpritePrecision::sprites4, SpriteGroupType::slopes16, SpritePrecision::sprites4, + SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, + SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::slopeSteepLong + { SpriteGroupType::slopes50, SpritePrecision::sprites4, SpriteGroupType::slopes60Banked22, + SpritePrecision::sprites8, SpriteGroupType::slopes50Banked45, SpritePrecision::sprites8, + SpriteGroupType::slopes50Banked67, SpritePrecision::sprites8, SpriteGroupType::slopes50Banked90, + SpritePrecision::sprites8, SpriteGroupType::corkscrews, SpritePrecision::sprites4, + SpriteGroupType::slopes25InlineTwists, SpritePrecision::sprites4, SpriteGroupType::slopesLoop, + SpritePrecision::sprites4, SpriteGroupType::slopeInverted, SpritePrecision::sprites4 }, // TrackGroup::diveLoop + { SpriteGroupType::slopes8, SpritePrecision::sprites4, SpriteGroupType::slopes16, + SpritePrecision::sprites4 }, // TrackGroup::diagSlope + { SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, + SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::diagSlopeSteepUp + { SpriteGroupType::slopes25, SpritePrecision::sprites8, SpriteGroupType::slopes42, SpritePrecision::sprites8, + SpriteGroupType::slopes50, SpritePrecision::sprites4 }, // TrackGroup::diagSlopeSteepDown + }; + + static_assert(std::size(trackPieceRequiredSprites) == EnumValue(TrackGroup::count)); + + // Only check default vehicle; it's assumed the others will have correct sprites if this one does (I've yet to find an + // exception, at least) + auto supportedPieces = BitSet(); + supportedPieces.flip(); + auto defaultVehicle = rideEntry.GetDefaultCar(); + if (defaultVehicle != nullptr) + { + for (size_t i = 0; i < std::size(trackPieceRequiredSprites); i++) + { + for (auto& group : trackPieceRequiredSprites[i]) + { + auto precision = defaultVehicle->SpriteGroups[EnumValue(group.VehicleSpriteGroup)].spritePrecision; + if (precision < group.MinPrecision) + supportedPieces.set(i, false); + } + } + } + return supportedPieces; + } + + static std::optional RideGetSmallestStationLength(const Ride& ride) + { + std::optional result; + for (const auto& station : ride.getStations()) + { + if (!station.Start.IsNull()) + { + if (!result.has_value() || station.Length < result.value()) + { + result = station.Length; + } + } + } + return result; + } + + /** + * + * rct2: 0x006CB3AA + */ + static int32_t RideGetTrackLength(const Ride& ride) + { + TileElement* tileElement = nullptr; + TrackElemType trackType; + CoordsXYZ trackStart; + bool foundTrack = false; + + for (const auto& station : ride.getStations()) + { + trackStart = station.GetStart(); + if (trackStart.IsNull()) + continue; + + tileElement = MapGetFirstElementAt(trackStart); + if (tileElement == nullptr) + continue; do { if (tileElement->getType() != TileElementType::track) continue; - auto* trackElement = tileElement->asTrack(); - if (trackElement->GetRideIndex() != id) + trackType = tileElement->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) continue; - trackElement->SetRideType(type); + if (tileElement->getBaseZ() != trackStart.z) + continue; - } while (!(tileElement++)->isLastForTile()); + foundTrack = true; + } while (!foundTrack && !(tileElement++)->isLastForTile()); + + if (foundTrack) + break; } - } -} -bool Ride::hasRecolourableShopItems() const -{ - const auto rideEntry = getRideEntry(); - if (rideEntry == nullptr) - return false; + if (!foundTrack) + return 0; - for (size_t itemIndex = 0; itemIndex < std::size(rideEntry->shop_item); itemIndex++) - { - const ShopItem currentItem = rideEntry->shop_item[itemIndex]; - if (currentItem != ShopItem::none && GetShopItemDescriptor(currentItem).IsRecolourable()) + RideId rideIndex = tileElement->asTrack()->GetRideIndex(); + + auto* windowMgr = Ui::GetWindowManager(); + WindowBase* w = windowMgr->FindByClass(WindowClass::rideConstruction); + if (w != nullptr && _rideConstructionState != RideConstructionState::state0 && _currentRideIndex == rideIndex) { - return true; + RideConstructionInvalidateCurrentTrack(); } - } - return false; -} -bool Ride::hasStation() const -{ - return numStations != 0; -} + bool moveSlowIt = true; + int32_t result = 0; -std::vector GetTracklessRides() -{ - // Iterate map and build list of seen ride IDs - std::vector seen; - seen.resize(256); - TileElementIterator it; - TileElementIteratorBegin(&it); - while (TileElementIteratorNext(&it)) - { - auto trackEl = it.element->asTrack(); - if (trackEl != nullptr && !trackEl->isGhost()) + TrackCircuitIterator it; + trackCircuitIteratorBegin(&it, { trackStart.x, trackStart.y, tileElement }); + + TrackCircuitIterator slowIt = it; + while (trackCircuitIteratorNext(&it)) { - auto rideId = trackEl->GetRideIndex().ToUnderlying(); - if (rideId >= seen.size()) + trackType = it.current.element->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + result += ted.pieceLength; + + moveSlowIt = !moveSlowIt; + if (moveSlowIt) { - seen.resize(rideId + 1); + trackCircuitIteratorNext(&slowIt); + if (trackCircuitIteratorsMatch(&it, &slowIt)) + { + return 0; + } } - seen[rideId] = true; } + return result; } - // Get all rides that did not get seen during map iteration - auto& gameState = getGameState(); - const auto& rideManager = RideManager(gameState); - std::vector result; - for (const auto& ride : rideManager) + /** + * + * rct2: 0x006DD57D + */ + void Ride::updateMaxVehicles() { - const auto rideIndex = ride.id.ToUnderlying(); - if (seen.size() <= rideIndex || !seen[rideIndex]) - { - result.push_back(ride.id); - } - } - return result; -} + if (subtype == kObjectEntryIndexNull) + return; -ResultWithMessage Ride::changeStatusDoStationChecks(StationIndex& stationIndex) -{ - auto stationIndexCheck = RideModeCheckStationPresent(*this); - stationIndex = stationIndexCheck.StationIndex; - if (stationIndex.IsNull()) - return { false, stationIndexCheck.Message }; - - auto stationNumbersCheck = RideModeCheckValidStationNumbers(*this); - if (!stationNumbersCheck.Successful) - return { false, stationNumbersCheck.Message }; - - return { true }; -} - -ResultWithMessage Ride::changeStatusGetStartElement(StationIndex stationIndex, CoordsXYE& trackElement) -{ - auto startLoc = getStation(stationIndex).Start; - trackElement.x = startLoc.x; - trackElement.y = startLoc.y; - trackElement.element = reinterpret_cast(getOriginElement(stationIndex)); - if (trackElement.element == nullptr) - { - // Maze is strange, station start is 0... investigation required - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::maze) - return { false }; - } - - return { true }; -} - -ResultWithMessage Ride::changeStatusCheckCompleteCircuit(const CoordsXYE& trackElement) -{ - CoordsXYE problematicTrackElement = {}; - if (mode == RideMode::race || mode == RideMode::continuousCircuit || isBlockSectioned()) - { - if (findTrackGap(*this, trackElement, &problematicTrackElement)) - { - RideScrollToTrackError(problematicTrackElement); - return { false, STR_TRACK_IS_NOT_A_COMPLETE_CIRCUIT }; - } - } - - return { true }; -} - -ResultWithMessage Ride::changeStatusCheckTrackValidity(const CoordsXYE& trackElement, bool isSimulating) -{ - CoordsXYE problematicTrackElement = {}; - - if (isBlockSectioned()) - { - auto blockBrakeCheck = RideCheckBlockBrakes(trackElement, &problematicTrackElement, !isSimulating); - if (!blockBrakeCheck.Successful) - { - RideScrollToTrackError(problematicTrackElement); - return { false, blockBrakeCheck.Message }; - } - } - - if (subtype != kObjectEntryIndexNull && !getGameState().cheats.enableAllDrawableTrackPieces) - { const auto* rideEntry = GetRideEntryByIndex(subtype); if (rideEntry == nullptr) { - return { false, STR_UNKNOWN_RIDE }; + return; } - if (rideEntry->flags.has(RideEntryFlag::noInversions)) + + uint8_t newNumCarsPerTrain; + int32_t maxNumTrains; + + const auto& rtd = getRideTypeDescriptor(); + if (rideEntry->cars_per_flat_ride == kNoFlatRideCars) { - if (RideCheckTrackContainsInversions(trackElement, &problematicTrackElement)) + newNumCarsPerTrain = std::max(rideEntry->min_cars_in_train, numCarsPerTrain); + minCarsPerTrain = rideEntry->min_cars_in_train; + maxCarsPerTrain = rideEntry->max_cars_in_train; + + // Calculate maximum train length based on smallest station length + auto stationNumTiles = RideGetSmallestStationLength(*this); + if (!stationNumTiles.has_value()) + return; + + auto stationLength = (stationNumTiles.value() * 0x44180) - 0x16B2A; + int32_t maxMass = rtd.MaxMass << 8; + int32_t newMaxCarsPerTrain = 1; + for (int32_t numCars = rideEntry->max_cars_in_train; numCars > 0; numCars--) { - RideScrollToTrackError(problematicTrackElement); - return { false, STR_TRACK_UNSUITABLE_FOR_TYPE_OF_TRAIN }; + int32_t trainLength = 0; + int32_t totalMass = 0; + for (int32_t i = 0; i < numCars; i++) + { + const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, numCars, i)]; + trainLength += carEntry.spacing; + totalMass += carEntry.car_mass; + } + + if (trainLength <= stationLength && totalMass <= maxMass) + { + newMaxCarsPerTrain = numCars; + break; + } + } + int32_t newCarsPerTrain = std::max(proposedNumCarsPerTrain, rideEntry->min_cars_in_train); + newMaxCarsPerTrain = std::max(newMaxCarsPerTrain, static_cast(rideEntry->min_cars_in_train)); + if (!getGameState().cheats.disableTrainLengthLimit) + { + newCarsPerTrain = std::min(newMaxCarsPerTrain, newCarsPerTrain); + } + maxCarsPerTrain = newMaxCarsPerTrain; + minCarsPerTrain = rideEntry->min_cars_in_train; + + switch (mode) + { + case RideMode::continuousCircuitBlockSectioned: + case RideMode::poweredLaunchBlockSectioned: + maxNumTrains = std::clamp(numStations + numBlockBrakes - 1, 1, Limits::kMaxTrainsPerRide); + break; + case RideMode::reverseInclineLaunchedShuttle: + case RideMode::poweredLaunchPassthrough: + case RideMode::shuttle: + case RideMode::limPoweredLaunch: + case RideMode::poweredLaunch: + maxNumTrains = 1; + break; + default: + // Calculate maximum number of trains + int32_t trainLength = 0; + for (int32_t i = 0; i < newCarsPerTrain; i++) + { + const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, i)]; + trainLength += carEntry.spacing; + } + + int32_t totalLength = trainLength / 2; + if (newCarsPerTrain != 1) + totalLength /= 2; + + maxNumTrains = 0; + do + { + maxNumTrains++; + totalLength += trainLength; + } while (totalLength <= stationLength); + + if ((mode != RideMode::stationToStation && mode != RideMode::continuousCircuit) + || !rtd.flags.has(RtdFlag::allowMoreVehiclesThanStationFits)) + { + maxNumTrains = std::min(maxNumTrains, int32_t(Limits::kMaxTrainsPerRide)); + } + else + { + const auto& firstCarEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, 0)]; + int32_t poweredMaxSpeed = firstCarEntry.powered_max_speed; + + int32_t totalSpacing = 0; + for (int32_t i = 0; i < newCarsPerTrain; i++) + { + const auto& carEntry = rideEntry->Cars[RideEntryGetVehicleAtPosition(subtype, newCarsPerTrain, i)]; + totalSpacing += carEntry.spacing; + } + + totalSpacing >>= 13; + int32_t trackLength = RideGetTrackLength(*this) / 4; + if (poweredMaxSpeed > 10) + trackLength = (trackLength * 3) / 4; + if (poweredMaxSpeed > 25) + trackLength = (trackLength * 3) / 4; + if (poweredMaxSpeed > 40) + trackLength = (trackLength * 3) / 4; + + maxNumTrains = 0; + int32_t length = 0; + do + { + maxNumTrains++; + length += totalSpacing; + } while (maxNumTrains < Limits::kMaxTrainsPerRide && length < trackLength); + } + break; + } + maxTrains = maxNumTrains; + + newNumCarsPerTrain = std::min(proposedNumCarsPerTrain, static_cast(newCarsPerTrain)); + } + else + { + maxTrains = rideEntry->cars_per_flat_ride; + minCarsPerTrain = rideEntry->min_cars_in_train; + maxCarsPerTrain = rideEntry->max_cars_in_train; + newNumCarsPerTrain = rideEntry->max_cars_in_train; + maxNumTrains = rideEntry->cars_per_flat_ride; + } + + if (getGameState().cheats.disableTrainLengthLimit) + { + maxNumTrains = Limits::kMaxTrainsPerRide; + } + auto newNumTrains = std::min(proposedNumTrains, static_cast(maxNumTrains)); + + // Refresh new current num vehicles / num cars per vehicle + if (newNumTrains != numTrains || newNumCarsPerTrain != numCarsPerTrain) + { + numCarsPerTrain = newNumCarsPerTrain; + numTrains = newNumTrains; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, id.ToUnderlying()); + } + } + + void Ride::updateNumberOfCircuits() + { + if (!canHaveMultipleCircuits()) + { + numCircuits = 1; + } + } + + void Ride::setRideEntry(ObjectEntryIndex entryIndex) + { + auto colour = RideGetUnusedPresetVehicleColour(entryIndex, UtilRand()); + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::rideEntry, entryIndex, colour); + GameActions::Execute(&rideSetVehicleAction, getGameState()); + } + + void Ride::setNumTrains(int32_t newNumTrains) + { + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::numTrains, newNumTrains); + GameActions::Execute(&rideSetVehicleAction, getGameState()); + } + + void Ride::setNumCarsPerTrain(int32_t numCarsPerVehicle) + { + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::numCarsPerTrain, numCarsPerVehicle); + GameActions::Execute(&rideSetVehicleAction, getGameState()); + } + + void Ride::setReversedTrains(bool reverseTrains) + { + auto rideSetVehicleAction = GameActions::RideSetVehicleAction( + id, GameActions::RideSetVehicleType::trainsReversed, reverseTrains); + GameActions::Execute(&rideSetVehicleAction, getGameState()); + } + + /** + * + * rct2: 0x006B752C + */ + void Ride::crash(uint8_t vehicleIndex) + { + Vehicle* vehicle = getGameState().entities.GetEntity(vehicles[vehicleIndex]); + + if (gLegacyScene != LegacyScene::titleSequence && vehicle != nullptr) + { + // Open ride window for crashed vehicle + auto intent = Intent(WindowDetail::vehicle); + intent.PutExtra(INTENT_EXTRA_VEHICLE, vehicle); + WindowBase* w = ContextOpenIntent(&intent); + + Viewport* viewport = WindowGetViewport(w); + if (w != nullptr && viewport != nullptr) + { + viewport->flags |= VIEWPORT_FLAG_SOUND_ON; } } - if (rideEntry->flags.has(RideEntryFlag::noBankedTrack)) + + if (Config::Get().notifications.rideCrashed) { - if (RideCheckTrackContainsBanked(trackElement, &problematicTrackElement)) + Formatter ft; + formatNameTo(ft); + News::AddItemToQueue(News::ItemType::ride, STR_RIDE_HAS_CRASHED, id.ToUnderlying(), ft); + } + } + + // Gets the approximate value of customers per hour for this ride. Multiplies ride_customers_in_last_5_minutes() by 12. + uint32_t RideCustomersPerHour(const Ride& ride) + { + return RideCustomersInLast5Minutes(ride) * 12; + } + + // Calculates the number of customers for this ride in the last 5 minutes (or more correctly 9600 game ticks) + uint32_t RideCustomersInLast5Minutes(const Ride& ride) + { + uint32_t sum = 0; + + for (int32_t i = 0; i < Limits::kCustomerHistorySize; i++) + { + sum += ride.numCustomers[i]; + } + + return sum; + } + + Vehicle* RideGetBrokenVehicle(const Ride& ride) + { + auto vehicleIndex = ride.vehicles[ride.brokenTrain]; + Vehicle* vehicle = getGameState().entities.GetEntity(vehicleIndex); + if (vehicle != nullptr) + { + return vehicle->GetCar(ride.brokenCar); + } + return nullptr; + } + + /** + * + * rct2: 0x006D235B + */ + void Ride::remove() + { + RideDelete(id); + } + + void Ride::renew() + { + // Set build date to current date (so the ride is brand new) + buildDate = GetDate().GetMonthsElapsed(); + reliability = kRideInitialReliability; + std::fill(std::begin(downtimeHistory), std::end(downtimeHistory), 0); + downtime = 0; + } + + RideClassification Ride::getClassification() const + { + const auto& rtd = getRideTypeDescriptor(); + return rtd.Classification; + } + + bool Ride::isRide() const + { + return getClassification() == RideClassification::ride; + } + + money64 RideGetPrice(const Ride& ride) + { + auto& park = getGameState().park; + if (park.flags & PARK_FLAGS_NO_MONEY) + return 0; + if (ride.isRide()) + { + if (!Park::RidePricesUnlocked(park)) { - RideScrollToTrackError(problematicTrackElement); - return { false, STR_TRACK_UNSUITABLE_FOR_TYPE_OF_TRAIN }; + return 0; + } + } + return ride.price[0]; + } + + /** + * Return the tile_element of an adjacent station at x,y,z(+-2). + * Returns nullptr if no suitable tile_element is found. + */ + TileElement* GetStationPlatform(const CoordsXYRangedZ& coords) + { + bool foundTileElement = false; + TileElement* tileElement = MapGetFirstElementAt(coords); + if (tileElement != nullptr) + { + do + { + if (tileElement->getType() != TileElementType::track) + continue; + /* Check if tileElement is a station platform. */ + if (!tileElement->asTrack()->IsStation()) + continue; + + if (coords.baseZ > tileElement->getBaseZ() || coords.clearanceZ < tileElement->getBaseZ()) + { + /* The base height of tileElement is not within + * the z tolerance. */ + continue; + } + + foundTileElement = true; + break; + } while (!(tileElement++)->isLastForTile()); + } + if (!foundTileElement) + { + return nullptr; + } + + return tileElement; + } + + /** + * Check for an adjacent station to x,y,z in direction. + */ + static bool CheckForAdjacentStation(const CoordsXYZ& stationCoords, uint8_t direction) + { + bool found = false; + int32_t adjX = stationCoords.x; + int32_t adjY = stationCoords.y; + for (uint32_t i = 0; i <= kRideAdjacencyCheckDistance; i++) + { + adjX += CoordsDirectionDelta[direction].x; + adjY += CoordsDirectionDelta[direction].y; + TileElement* stationElement = GetStationPlatform( + { { adjX, adjY, stationCoords.z - 2 * kCoordsZStep }, stationCoords.z + 2 * kCoordsZStep }); + if (stationElement != nullptr) + { + auto rideIndex = stationElement->asTrack()->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride != nullptr && (ride->departFlags & RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS)) + { + found = true; + } + } + } + return found; + } + + /** + * Return whether ride has at least one adjacent station to it. + */ + bool RideHasAdjacentStation(const Ride& ride) + { + bool found = false; + + /* Loop through all of the ride stations, checking for an + * adjacent station on either side. */ + for (const auto& station : ride.getStations()) + { + auto stationStart = station.GetStart(); + if (!stationStart.IsNull()) + { + /* Get the map element for the station start. */ + TileElement* stationElement = GetStationPlatform({ stationStart, stationStart.z + 0 }); + if (stationElement == nullptr) + { + continue; + } + /* Check the first side of the station */ + int32_t direction = stationElement->getDirectionWithOffset(1); + found = CheckForAdjacentStation(stationStart, direction); + if (found) + break; + /* Check the other side of the station */ + direction = DirectionReverse(direction); + found = CheckForAdjacentStation(stationStart, direction); + if (found) + break; + } + } + return found; + } + + bool RideHasStationShelter(const Ride& ride) + { + const auto* stationObj = ride.getStationObject(); + return stationObj != nullptr && (stationObj->Flags & StationObjectFlags::hasShelter); + } + + bool RideHasRatings(const Ride& ride) + { + return !ride.ratings.isNull(); + } + + int32_t GetUnifiedBoosterSpeed(ride_type_t rideType, int32_t relativeSpeed) + { + return GetRideTypeDescriptor(rideType).GetUnifiedBoosterSpeed(relativeSpeed); + } + + void FixInvalidVehicleSpriteSizes() + { + auto& gameState = getGameState(); + for (const auto& ride : RideManager(gameState)) + { + for (auto entityIndex : ride.vehicles) + { + for (Vehicle* vehicle = getGameState().entities.TryGetEntity(entityIndex); vehicle != nullptr; + vehicle = getGameState().entities.TryGetEntity(vehicle->next_vehicle_on_train)) + { + auto carEntry = vehicle->Entry(); + if (carEntry == nullptr) + { + break; + } + + if (vehicle->spriteData.width == 0) + { + vehicle->spriteData.width = carEntry->spriteWidth; + } + if (vehicle->spriteData.heightMin == 0) + { + vehicle->spriteData.heightMin = carEntry->spriteHeightNegative; + } + if (vehicle->spriteData.heightMax == 0) + { + vehicle->spriteData.heightMax = carEntry->spriteHeightPositive; + } + } } } } - if (mode == RideMode::stationToStation) + bool RideEntryHasCategory(const RideObjectEntry& rideEntry, RideCategory category) { - if (!findTrackGap(*this, trackElement, &problematicTrackElement)) + auto rideType = rideEntry.GetFirstNonNullRideType(); + return GetRideTypeDescriptor(rideType).Category == category; + } + + ObjectEntryIndex RideGetEntryIndex(ride_type_t rideType, ObjectEntryIndex rideSubType) + { + auto subType = rideSubType; + + if (subType == kObjectEntryIndexNull) { - return { false, STR_RIDE_MUST_START_AND_END_WITH_STATIONS }; + auto& objManager = GetContext()->GetObjectManager(); + auto& rideEntries = objManager.GetAllRideEntries(rideType); + if (!rideEntries.empty()) + { + subType = rideEntries[0]; + for (auto rideEntryIndex : rideEntries) + { + const auto* rideEntry = GetRideEntryByIndex(rideEntryIndex); + if (rideEntry == nullptr) + { + return kObjectEntryIndexNull; + } + + // Can happen in select-by-track-type mode + if (!RideEntryIsInvented(rideEntryIndex) && !getGameState().cheats.ignoreResearchStatus) + { + continue; + } + + if (!GetRideTypeDescriptor(rideType).flags.has(RtdFlag::listVehiclesSeparately)) + { + subType = rideEntryIndex; + break; + } + } + } } - if (!RideCheckStationLength(trackElement, &problematicTrackElement)) - { - RideScrollToTrackError(problematicTrackElement); - return { false, STR_STATION_NOT_LONG_ENOUGH }; - } + return subType; + } - if (!RideCheckStartAndEndIsStation(trackElement)) + const StationObject* Ride::getStationObject() const + { + auto& objManager = GetContext()->GetObjectManager(); + return objManager.GetLoadedObject(entranceStyle); + } + + const MusicObject* Ride::getMusicObject() const + { + auto& objManager = GetContext()->GetObjectManager(); + return objManager.GetLoadedObject(music); + } + + // Normally, a station has at most one entrance and one exit, which are at the same height + // as the station. But in hacked parks, neither can be taken for granted. This code ensures + // that the ride.entrances and ride.exits arrays will point to one of them. There is + // an ever-so-slight chance two entrances/exits for the same station reside on the same tile. + // In cases like this, the one at station height will be considered the "true" one. + // If none exists at that height, newer and higher placed ones take precedence. + void DetermineRideEntranceAndExitLocations() + { + LOG_VERBOSE("Inspecting ride entrance / exit locations"); + + auto& gameState = getGameState(); + for (auto& ride : RideManager(gameState)) { - RideScrollToTrackError(problematicTrackElement); - return { false, STR_RIDE_MUST_START_AND_END_WITH_STATIONS }; + for (auto& station : ride.getStations()) + { + auto stationIndex = ride.getStationIndex(&station); + TileCoordsXYZD entranceLoc = station.Entrance; + TileCoordsXYZD exitLoc = station.Exit; + bool fixEntrance = false; + bool fixExit = false; + + // Skip if the station has no entrance + if (!entranceLoc.IsNull()) + { + const EntranceElement* entranceElement = MapGetRideEntranceElementAt(entranceLoc.ToCoordsXYZD(), false); + + if (entranceElement == nullptr || entranceElement->GetRideIndex() != ride.id + || entranceElement->GetStationIndex() != stationIndex) + { + fixEntrance = true; + } + else + { + station.Entrance.direction = entranceElement->getDirection(); + } + } + + if (!exitLoc.IsNull()) + { + const EntranceElement* entranceElement = MapGetRideExitElementAt(exitLoc.ToCoordsXYZD(), false); + + if (entranceElement == nullptr || entranceElement->GetRideIndex() != ride.id + || entranceElement->GetStationIndex() != stationIndex) + { + fixExit = true; + } + else + { + station.Exit.direction = entranceElement->getDirection(); + } + } + + if (!fixEntrance && !fixExit) + { + continue; + } + + // At this point, we know we have a disconnected entrance or exit. + // Search the map to find it. Skip the outer ring of invisible tiles. + bool alreadyFoundEntrance = false; + bool alreadyFoundExit = false; + for (int32_t y = 1; y < gameState.mapSize.y - 1; y++) + { + for (int32_t x = 1; x < gameState.mapSize.x - 1; x++) + { + TileElement* tileElement = MapGetFirstElementAt(TileCoordsXY{ x, y }); + + if (tileElement != nullptr) + { + do + { + if (tileElement->getType() != TileElementType::entrance) + { + continue; + } + const EntranceElement* entranceElement = tileElement->asEntrance(); + if (entranceElement->GetRideIndex() != ride.id) + { + continue; + } + if (entranceElement->GetStationIndex() != stationIndex) + { + continue; + } + + // The expected height is where entrances and exit reside in non-hacked parks. + const uint8_t expectedHeight = station.Height; + + if (fixEntrance && entranceElement->GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE) + { + if (alreadyFoundEntrance) + { + if (station.Entrance.z == expectedHeight) + continue; + if (station.Entrance.z > entranceElement->baseHeight) + continue; + } + + // Found our entrance + station.Entrance = { x, y, entranceElement->baseHeight, entranceElement->getDirection() }; + alreadyFoundEntrance = true; + + LOG_VERBOSE( + "Fixed disconnected entrance of ride %d, station %d to x = %d, y = %d and z = %d.", + ride.id, stationIndex, x, y, entranceElement->baseHeight); + } + else if (fixExit && entranceElement->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) + { + if (alreadyFoundExit) + { + if (station.Exit.z == expectedHeight) + continue; + if (station.Exit.z > entranceElement->baseHeight) + continue; + } + + // Found our exit + station.Exit = { x, y, entranceElement->baseHeight, entranceElement->getDirection() }; + alreadyFoundExit = true; + + LOG_VERBOSE( + "Fixed disconnected exit of ride %d, station %d to x = %d, y = %d and z = %d.", ride.id, + stationIndex, x, y, entranceElement->baseHeight); + } + } while (!(tileElement++)->isLastForTile()); + } + } + } + + if (fixEntrance && !alreadyFoundEntrance) + { + station.Entrance.SetNull(); + LOG_VERBOSE("Cleared disconnected entrance of ride %d, station %d.", ride.id, stationIndex); + } + if (fixExit && !alreadyFoundExit) + { + station.Exit.SetNull(); + LOG_VERBOSE("Cleared disconnected exit of ride %d, station %d.", ride.id, stationIndex); + } + } } } - return { true }; -} - -ResultWithMessage Ride::changeStatusCreateVehicles(bool isApplying, const CoordsXYE& trackElement, bool isSimulating) -{ - if (isApplying) - RideSetStartFinishPoints(id, trackElement); - - const auto& rtd = getRideTypeDescriptor(); - if (!rtd.flags.has(RtdFlag::noVehicles) && !flags.has(RideFlag::onTrack)) + void RideClearLeftoverEntrances(const Ride& ride) { - const auto createVehicleResult = createVehicles(trackElement, isApplying, isSimulating); - if (!createVehicleResult.Successful) + auto& gameState = getGameState(); + for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) { - return { false, createVehicleResult.Message }; + for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) + { + for (auto* entrance : TileElementsView(tilePos.ToCoordsXY())) + { + const bool isRideEntranceExit = entrance->GetEntranceType() == ENTRANCE_TYPE_RIDE_ENTRANCE + || entrance->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT; + if (!isRideEntranceExit) + continue; + if (entrance->GetRideIndex() != ride.id) + continue; + + TileElementRemove(entrance->as()); + } + } } } - if (rtd.flags.has(RtdFlag::allowCableLiftHill) && flags.has(RideFlag::cableLiftHillComponentUsed) - && !flags.has(RideFlag::cableLift)) + std::string Ride::getName() const { - const auto createCableLiftResult = RideCreateCableLift(id, isApplying); - if (!createCableLiftResult.Successful) - return { false, createCableLiftResult.Message }; + Formatter ft; + formatNameTo(ft); + return FormatStringIDLegacy(STR_STRINGID, reinterpret_cast(ft.Data())); } - return { true }; -} + void Ride::formatNameTo(Formatter& ft) const + { + if (!customName.empty()) + { + auto str = customName.c_str(); + ft.Add(STR_STRING); + ft.Add(str); + } + else + { + const auto rideTypeName = getTypeNaming().Name; + ft.Add(1).Add(rideTypeName).Add(defaultNameNumber); + } + } -RideMode RideModeGetBlockSectionedCounterpart(RideMode originalMode) -{ - assert(originalMode < RideMode::count); - return kRideModeBlockSectionedCounterpart[EnumValue(originalMode)]; -} + uint64_t Ride::getAvailableModes() const + { + if (getGameState().cheats.showAllOperatingModes) + return kAllRideModesAvailable; + + return getRideTypeDescriptor().RideModes; + } + + const RideTypeDescriptor& Ride::getRideTypeDescriptor() const + { + return GetRideTypeDescriptor(type); + } + + RideNaming Ride::getTypeNaming() const + { + return GetRideNaming(type, getRideEntry()); + } + + uint8_t Ride::getNumShelteredSections() const + { + return numShelteredSections & ShelteredSectionsBits::kNumShelteredSectionsMask; + } + + void Ride::increaseNumShelteredSections() + { + auto newNumShelteredSections = getNumShelteredSections(); + if (newNumShelteredSections != 0x1F) + newNumShelteredSections++; + numShelteredSections &= ~ShelteredSectionsBits::kNumShelteredSectionsMask; + numShelteredSections |= newNumShelteredSections; + } + + void Ride::updateRideTypeForAllPieces() + { + auto& gameState = getGameState(); + for (int32_t y = 0; y < gameState.mapSize.y; y++) + { + for (int32_t x = 0; x < gameState.mapSize.x; x++) + { + auto* tileElement = MapGetFirstElementAt(TileCoordsXY(x, y)); + if (tileElement == nullptr) + continue; + + do + { + if (tileElement->getType() != TileElementType::track) + continue; + + auto* trackElement = tileElement->asTrack(); + if (trackElement->GetRideIndex() != id) + continue; + + trackElement->SetRideType(type); + + } while (!(tileElement++)->isLastForTile()); + } + } + } + + bool Ride::hasRecolourableShopItems() const + { + const auto rideEntry = getRideEntry(); + if (rideEntry == nullptr) + return false; + + for (size_t itemIndex = 0; itemIndex < std::size(rideEntry->shop_item); itemIndex++) + { + const ShopItem currentItem = rideEntry->shop_item[itemIndex]; + if (currentItem != ShopItem::none && GetShopItemDescriptor(currentItem).IsRecolourable()) + { + return true; + } + } + return false; + } + + bool Ride::hasStation() const + { + return numStations != 0; + } + + std::vector GetTracklessRides() + { + // Iterate map and build list of seen ride IDs + std::vector seen; + seen.resize(256); + TileElementIterator it; + TileElementIteratorBegin(&it); + while (TileElementIteratorNext(&it)) + { + auto trackEl = it.element->asTrack(); + if (trackEl != nullptr && !trackEl->isGhost()) + { + auto rideId = trackEl->GetRideIndex().ToUnderlying(); + if (rideId >= seen.size()) + { + seen.resize(rideId + 1); + } + seen[rideId] = true; + } + } + + // Get all rides that did not get seen during map iteration + auto& gameState = getGameState(); + const auto& rideManager = RideManager(gameState); + std::vector result; + for (const auto& ride : rideManager) + { + const auto rideIndex = ride.id.ToUnderlying(); + if (seen.size() <= rideIndex || !seen[rideIndex]) + { + result.push_back(ride.id); + } + } + return result; + } + + ResultWithMessage Ride::changeStatusDoStationChecks(StationIndex& stationIndex) + { + auto stationIndexCheck = RideModeCheckStationPresent(*this); + stationIndex = stationIndexCheck.StationIndex; + if (stationIndex.IsNull()) + return { false, stationIndexCheck.Message }; + + auto stationNumbersCheck = RideModeCheckValidStationNumbers(*this); + if (!stationNumbersCheck.Successful) + return { false, stationNumbersCheck.Message }; + + return { true }; + } + + ResultWithMessage Ride::changeStatusGetStartElement(StationIndex stationIndex, CoordsXYE& trackElement) + { + auto startLoc = getStation(stationIndex).Start; + trackElement.x = startLoc.x; + trackElement.y = startLoc.y; + trackElement.element = reinterpret_cast(getOriginElement(stationIndex)); + if (trackElement.element == nullptr) + { + // Maze is strange, station start is 0... investigation required + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::maze) + return { false }; + } + + return { true }; + } + + ResultWithMessage Ride::changeStatusCheckCompleteCircuit(const CoordsXYE& trackElement) + { + CoordsXYE problematicTrackElement = {}; + if (mode == RideMode::race || mode == RideMode::continuousCircuit || isBlockSectioned()) + { + if (findTrackGap(*this, trackElement, &problematicTrackElement)) + { + RideScrollToTrackError(problematicTrackElement); + return { false, STR_TRACK_IS_NOT_A_COMPLETE_CIRCUIT }; + } + } + + return { true }; + } + + ResultWithMessage Ride::changeStatusCheckTrackValidity(const CoordsXYE& trackElement, bool isSimulating) + { + CoordsXYE problematicTrackElement = {}; + + if (isBlockSectioned()) + { + auto blockBrakeCheck = RideCheckBlockBrakes(trackElement, &problematicTrackElement, !isSimulating); + if (!blockBrakeCheck.Successful) + { + RideScrollToTrackError(problematicTrackElement); + return { false, blockBrakeCheck.Message }; + } + } + + if (subtype != kObjectEntryIndexNull && !getGameState().cheats.enableAllDrawableTrackPieces) + { + const auto* rideEntry = GetRideEntryByIndex(subtype); + if (rideEntry == nullptr) + { + return { false, STR_UNKNOWN_RIDE }; + } + if (rideEntry->flags.has(RideEntryFlag::noInversions)) + { + if (RideCheckTrackContainsInversions(trackElement, &problematicTrackElement)) + { + RideScrollToTrackError(problematicTrackElement); + return { false, STR_TRACK_UNSUITABLE_FOR_TYPE_OF_TRAIN }; + } + } + if (rideEntry->flags.has(RideEntryFlag::noBankedTrack)) + { + if (RideCheckTrackContainsBanked(trackElement, &problematicTrackElement)) + { + RideScrollToTrackError(problematicTrackElement); + return { false, STR_TRACK_UNSUITABLE_FOR_TYPE_OF_TRAIN }; + } + } + } + + if (mode == RideMode::stationToStation) + { + if (!findTrackGap(*this, trackElement, &problematicTrackElement)) + { + return { false, STR_RIDE_MUST_START_AND_END_WITH_STATIONS }; + } + + if (!RideCheckStationLength(trackElement, &problematicTrackElement)) + { + RideScrollToTrackError(problematicTrackElement); + return { false, STR_STATION_NOT_LONG_ENOUGH }; + } + + if (!RideCheckStartAndEndIsStation(trackElement)) + { + RideScrollToTrackError(problematicTrackElement); + return { false, STR_RIDE_MUST_START_AND_END_WITH_STATIONS }; + } + } + + return { true }; + } + + ResultWithMessage Ride::changeStatusCreateVehicles(bool isApplying, const CoordsXYE& trackElement, bool isSimulating) + { + if (isApplying) + RideSetStartFinishPoints(id, trackElement); + + const auto& rtd = getRideTypeDescriptor(); + if (!rtd.flags.has(RtdFlag::noVehicles) && !flags.has(RideFlag::onTrack)) + { + const auto createVehicleResult = createVehicles(trackElement, isApplying, isSimulating); + if (!createVehicleResult.Successful) + { + return { false, createVehicleResult.Message }; + } + } + + if (rtd.flags.has(RtdFlag::allowCableLiftHill) && flags.has(RideFlag::cableLiftHillComponentUsed) + && !flags.has(RideFlag::cableLift)) + { + const auto createCableLiftResult = RideCreateCableLift(id, isApplying); + if (!createCableLiftResult.Successful) + return { false, createCableLiftResult.Message }; + } + + return { true }; + } + + RideMode RideModeGetBlockSectionedCounterpart(RideMode originalMode) + { + assert(originalMode < RideMode::count); + return kRideModeBlockSectionedCounterpart[EnumValue(originalMode)]; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Ride.h b/src/openrct2/ride/Ride.h index 1f87036f5e..72e54828fe 100644 --- a/src/openrct2/ride/Ride.h +++ b/src/openrct2/ride/Ride.h @@ -27,868 +27,870 @@ #include #include -struct RideTypeDescriptor; -struct Vehicle; +struct IObjectManager; +struct RideObjectEntry; struct ResultWithMessage; +struct TrackDesign; +struct TrackDesignState; namespace OpenRCT2 { struct Guest; struct Staff; + struct Vehicle; class Formatter; class MusicObject; class StationObject; + struct RideTypeDescriptor; struct TileElement; struct TrackElement; -} // namespace OpenRCT2 -constexpr uint8_t kRideAdjacencyCheckDistance = 5; + enum class RideMode : uint8_t; + enum class RideStatus : uint8_t; -constexpr uint8_t kTuneIDNull = 0xFF; + constexpr uint8_t kRideAdjacencyCheckDistance = 5; -constexpr uint16_t kMaxStationLocations = OpenRCT2::Limits::kMaxStationsPerRide * 2; // Entrance and exit per station + constexpr uint8_t kTuneIDNull = 0xFF; -constexpr uint16_t kMazeClearanceHeight = 4 * kCoordsZStep; + constexpr uint16_t kMaxStationLocations = Limits::kMaxStationsPerRide * 2; // Entrance and exit per station -constexpr money64 kRideMinPrice = 0.00_GBP; -constexpr money64 kRideMaxPrice = 20.00_GBP; + constexpr uint16_t kMazeClearanceHeight = 4 * kCoordsZStep; -extern const StringId kRideInspectionIntervalNames[]; + constexpr money64 kRideMinPrice = 0.00_GBP; + constexpr money64 kRideMaxPrice = 20.00_GBP; -enum class RideInspection : uint8_t -{ - every10Minutes, - every20Minutes, - every30Minutes, - every45Minutes, - everyHour, - every2Hours, - never, -}; + extern const StringId kRideInspectionIntervalNames[]; -// Flags used by ride->windowInvalidateFlags -enum class RideInvalidateFlag : uint8_t -{ - customers, - income, - main, - list, - operatingSettings, - maintenance, - music, - ratings, -}; -using RideInvalidateFlags = FlagHolder; - -enum class RideMeasurementFlag : uint8_t -{ - running, - unloading, - gForces -}; -using RideMeasurementFlags = FlagHolder; - -enum class RideTestingFlag : uint8_t -{ - sheltered, - turnLeft, - turnRight, - turnBanked, - turnSloped, - dropDown, - poweredLift, - dropUp, -}; -using RideTestingFlags = FlagHolder; - -enum class RideFlag : uint8_t -{ - onTrack, - tested, - testInProgress, - noRawStats, - passStationNoStopping, - onRidePhoto, - breakdownPending, - brokenDown, - dueInspection, - queueFull, - crashed, - hasStalledVehicle, - everBeenOpened, - music, - indestructible, - indestructibleTrack, - cableLiftHillComponentUsed, - cableLift, - notCustomDesign, // Used for the Award for Best Custom-designed Rides - sixFlagsDeprecated, // Not used anymore - fixedRatings, // When set, the ratings will not be updated (useful for hacked rides). - randomShopColours, - reversedTrains, -}; -using RideFlags = FlagHolder; - -enum class Breakdown : uint8_t -{ - safetyCutOut, - restraintsStuckClosed, - restraintsStuckOpen, - doorsStuckClosed, - doorsStuckOpen, - vehicleMalfunction, - brakesFailure, - controlFailure, - - none = 255, -}; -constexpr auto kAllBreakdownTypes = std::to_array( + enum class RideInspection : uint8_t { - Breakdown::safetyCutOut, - Breakdown::restraintsStuckClosed, - Breakdown::restraintsStuckOpen, - Breakdown::doorsStuckClosed, - Breakdown::doorsStuckOpen, - Breakdown::vehicleMalfunction, - Breakdown::brakesFailure, - Breakdown::controlFailure, - }); -constexpr auto kBreakdownCount = kAllBreakdownTypes.size(); - -struct RideStation -{ - static constexpr uint8_t kNoTrain = std::numeric_limits::max(); - - CoordsXY Start; - uint8_t Height{}; - uint8_t Length{}; - uint8_t Depart{}; - uint8_t TrainAtStation{ kNoTrain }; - TileCoordsXYZD Entrance; - TileCoordsXYZD Exit; - int32_t SegmentLength{}; // Length of track between this station and the next. - uint16_t SegmentTime{}; // Time for train to reach the next station from this station. - uint8_t QueueTime{}; - uint16_t QueueLength{}; - EntityId LastPeepInQueue{ EntityId::GetNull() }; - - int32_t GetBaseZ() const; - void SetBaseZ(int32_t newZ); - CoordsXYZ GetStart() const; -}; - -struct RideMeasurement -{ - static constexpr size_t kMaxItems = 4800; - - RideMeasurementFlags flags{}; - uint32_t last_use_tick{}; - uint16_t num_items{}; - uint16_t current_item{}; - uint8_t vehicle_index{}; - StationIndex current_station{}; - int8_t vertical[kMaxItems]{}; - int8_t lateral[kMaxItems]{}; - uint8_t velocity[kMaxItems]{}; - uint8_t altitude[kMaxItems]{}; -}; - -enum class RideClassification -{ - ride, - shopOrStall, - kioskOrFacility -}; - -enum class MechanicStatus : uint8_t -{ - undefined, - calling, - heading, - fixing, - hasFixedStationBrakes -}; - -namespace OpenRCT2::ShelteredSectionsBits -{ - constexpr uint8_t kNumShelteredSectionsMask = 0b00011111; - constexpr uint8_t kRotatingWhileSheltered = 0b00100000; - constexpr uint8_t kBankingWhileSheltered = 0b01000000; -} // namespace OpenRCT2::ShelteredSectionsBits - -struct TrackDesign; -struct TrackDesignState; -enum class RideMode : uint8_t; -enum class RideStatus : uint8_t; - -enum class SpecialElement : uint8_t -{ - spinningTunnel = 5, - splash = 5, - rapids = 5, - reverser = 6, - waterfall = 6, - whirlpool = 7, -}; -using SpecialElements = FlagHolder; - -/** - * Ride structure. - * - * This is based on RCT2's ride structure. - * Padding and no longer used fields have been removed. - */ -struct Ride -{ - RideId id{ RideId::GetNull() }; - ride_type_t type{ kRideTypeNull }; - // pointer to static info. for example, wild mouse type is 0x36, subtype is - // 0x4c. - OpenRCT2::ObjectEntryIndex subtype{ OpenRCT2::kObjectEntryIndexNull }; - RideMode mode{}; - VehicleColourSettings vehicleColourSettings{}; - VehicleColour vehicleColours[OpenRCT2::Limits::kMaxVehicleColours]{}; - // 0 = closed, 1 = open, 2 = test - RideStatus status{}; - std::string customName; - uint16_t defaultNameNumber{}; - CoordsXY overallView; - EntityId vehicles[OpenRCT2::Limits::kMaxTrainsPerRide + 1]{}; // Points to the first car in the train - uint8_t departFlags{}; - uint8_t numStations{}; - uint8_t numTrains{}; - uint8_t numCarsPerTrain{}; - uint8_t proposedNumTrains{}; - uint8_t proposedNumCarsPerTrain{}; - uint8_t maxTrains{}; - uint8_t minCarsPerTrain{}; - uint8_t maxCarsPerTrain{}; - uint8_t minWaitingTime{}; - uint8_t maxWaitingTime{}; - union - { - uint8_t operationOption; - uint8_t timeLimit; - uint8_t numLaps; - uint8_t launchSpeed; - uint8_t speed; - uint8_t rotations{}; + every10Minutes, + every20Minutes, + every30Minutes, + every45Minutes, + everyHour, + every2Hours, + never, }; - uint8_t boatHireReturnDirection{}; - TileCoordsXY boatHireReturnPosition; - uint8_t numHelices{}; - SpecialElements specialTrackElements{}; - // Use ToHumanReadableSpeed if converting to display - int32_t maxSpeed{}; - int32_t averageSpeed{}; - uint8_t currentTestSegment{}; - uint8_t averageSpeedTestTimeout{}; - fixed16_2dp maxPositiveVerticalG{}; - fixed16_2dp maxNegativeVerticalG{}; - fixed16_2dp maxLateralG{}; - fixed16_2dp previousVerticalG{}; - fixed16_2dp previousLateralG{}; - RideTestingFlags testingFlags{}; - // x y z map location of the current track piece during a test - // this is to prevent counting special tracks multiple times - TileCoordsXYZ curTestTrackLocation; - // Next 3 variables are related (XXXX XYYY ZZZa aaaa) - uint16_t turnCountDefault{}; // X = current turn count - uint16_t turnCountBanked{}; - uint16_t turnCountSloped{}; // X = number turns > 3 elements - // Y is number of powered lifts, X is drops - uint8_t numDrops{}; - uint8_t numPoweredLifts{}; - uint8_t startDropHeight{}; - uint8_t highestDropHeight{}; - int32_t shelteredLength{}; - // Unused always 0? Should affect nausea - uint16_t var11C{}; - uint8_t numShelteredSections{}; // (?abY YYYY) - // Customer counter in the current 960 game tick (about 30 seconds) interval - uint16_t curNumCustomers{}; - // Counts ticks to update customer intervals, resets each 960 game ticks. - uint16_t numCustomersTimeout{}; - // Customer count in the last 10 * 960 game ticks (sliding window) - uint16_t numCustomers[OpenRCT2::Limits::kCustomerHistorySize]{}; - money64 price[OpenRCT2::RCT2::ObjectLimits::kMaxShopItemsPerRideEntry]{}; - TileCoordsXYZ chairliftBullwheelLocation[2]; - OpenRCT2::RideRating::Tuple ratings{}; - money64 value{}; - uint16_t chairliftBullwheelRotation{}; - uint8_t satisfaction{}; - uint8_t satisfactionTimeout{}; - uint8_t satisfactionNext{}; - // Various flags stating whether a ride window needs to be refreshed - RideInvalidateFlags windowInvalidateFlags{}; - uint32_t totalCustomers{}; - money64 totalProfit{}; - uint8_t popularity{}; - uint8_t popularityTimeout{}; // Updated every purchase and ?possibly by time? - uint8_t popularityNext{}; // When timeout reached this will be the next popularity - uint16_t numRiders{}; - uint8_t musicTuneId{}; - uint8_t slideInUse{}; - union + // Flags used by ride->windowInvalidateFlags + enum class RideInvalidateFlag : uint8_t { - EntityId slidePeep; - uint16_t mazeTiles{}; + customers, + income, + main, + list, + operatingSettings, + maintenance, + music, + ratings, }; - OpenRCT2::Drawing::Colour slidePeepTShirtColour{}; - uint8_t spiralSlideProgress{}; - int32_t buildDate{}; - money64 upkeepCost{}; - EntityId raceWinner{}; - uint32_t musicPosition{}; - Breakdown breakdownReasonPending{}; - MechanicStatus mechanicStatus{}; - EntityId mechanic{ EntityId::GetNull() }; - StationIndex inspectionStation{ StationIndex::GetNull() }; - uint8_t brokenTrain{}; - uint8_t brokenCar{}; - Breakdown breakdownReason{}; - union + using RideInvalidateFlags = FlagHolder; + + enum class RideMeasurementFlag : uint8_t { - struct + running, + unloading, + gForces + }; + using RideMeasurementFlags = FlagHolder; + + enum class RideTestingFlag : uint8_t + { + sheltered, + turnLeft, + turnRight, + turnBanked, + turnSloped, + dropDown, + poweredLift, + dropUp, + }; + using RideTestingFlags = FlagHolder; + + enum class RideFlag : uint8_t + { + onTrack, + tested, + testInProgress, + noRawStats, + passStationNoStopping, + onRidePhoto, + breakdownPending, + brokenDown, + dueInspection, + queueFull, + crashed, + hasStalledVehicle, + everBeenOpened, + music, + indestructible, + indestructibleTrack, + cableLiftHillComponentUsed, + cableLift, + notCustomDesign, // Used for the Award for Best Custom-designed Rides + sixFlagsDeprecated, // Not used anymore + fixedRatings, // When set, the ratings will not be updated (useful for hacked rides). + randomShopColours, + reversedTrains, + }; + using RideFlags = FlagHolder; + + enum class Breakdown : uint8_t + { + safetyCutOut, + restraintsStuckClosed, + restraintsStuckOpen, + doorsStuckClosed, + doorsStuckOpen, + vehicleMalfunction, + brakesFailure, + controlFailure, + + none = 255, + }; + constexpr auto kAllBreakdownTypes = std::to_array( { - uint8_t reliabilitySubvalue; // 0 - 255, acts like the decimals for reliabilityPercentage - uint8_t reliabilityPercentage; // Starts at 100 and decreases from there. - }; - uint16_t reliability{}; + Breakdown::safetyCutOut, + Breakdown::restraintsStuckClosed, + Breakdown::restraintsStuckOpen, + Breakdown::doorsStuckClosed, + Breakdown::doorsStuckOpen, + Breakdown::vehicleMalfunction, + Breakdown::brakesFailure, + Breakdown::controlFailure, + }); + constexpr auto kBreakdownCount = kAllBreakdownTypes.size(); + + struct RideStation + { + static constexpr uint8_t kNoTrain = std::numeric_limits::max(); + + CoordsXY Start; + uint8_t Height{}; + uint8_t Length{}; + uint8_t Depart{}; + uint8_t TrainAtStation{ kNoTrain }; + TileCoordsXYZD Entrance; + TileCoordsXYZD Exit; + int32_t SegmentLength{}; // Length of track between this station and the next. + uint16_t SegmentTime{}; // Time for train to reach the next station from this station. + uint8_t QueueTime{}; + uint16_t QueueLength{}; + EntityId LastPeepInQueue{ EntityId::GetNull() }; + + int32_t GetBaseZ() const; + void SetBaseZ(int32_t newZ); + CoordsXYZ GetStart() const; }; - // Small constant used to increase the unreliability as the game continues, - // making breakdowns more and more likely. - uint8_t unreliabilityFactor{}; - // Range from [0, 100] - uint8_t downtime{}; - RideInspection inspectionInterval{}; - uint8_t lastInspection{}; - uint8_t downtimeHistory[OpenRCT2::Limits::kDowntimeHistorySize]{}; - uint32_t numPrimaryItemsSold{}; - uint32_t numSecondaryItemsSold{}; - // Used to oscillate the sound when ride breaks down. - // 0 = no change, 255 = max change - uint8_t breakdownSoundModifier{}; - uint8_t notFixedTimeout{}; - uint8_t lastCrashType{}; - uint8_t connectedMessageThrottle{}; - money64 incomePerHour{}; - money64 profit{}; - TrackColour trackColours[kNumRideColourSchemes]{}; - OpenRCT2::ObjectEntryIndex music{ OpenRCT2::kObjectEntryIndexNull }; - OpenRCT2::ObjectEntryIndex entranceStyle{ OpenRCT2::kObjectEntryIndexNull }; - uint16_t vehicleChangeTimeout{}; - uint8_t numBlockBrakes{}; - uint8_t liftHillSpeed{}; - uint32_t guestsFavourite{}; - RideFlags flags{}; - uint16_t totalAirTime{}; - StationIndex currentTestStation{ StationIndex::GetNull() }; - uint8_t numCircuits{}; - CoordsXYZ cableLiftLoc{}; - EntityId cableLift{ EntityId::GetNull() }; - // These two fields are used to warn users about issues. - // Such issue can be hacked rides with incompatible options set. - // They don't require export/import. - uint8_t currentIssues{}; - uint32_t lastIssueTime{}; + struct RideMeasurement + { + static constexpr size_t kMaxItems = 4800; -private: - std::array stations{}; + RideMeasurementFlags flags{}; + uint32_t last_use_tick{}; + uint16_t num_items{}; + uint16_t current_item{}; + uint8_t vehicle_index{}; + StationIndex current_station{}; + int8_t vertical[kMaxItems]{}; + int8_t lateral[kMaxItems]{}; + uint8_t velocity[kMaxItems]{}; + uint8_t altitude[kMaxItems]{}; + }; -public: - uint8_t numInversions{}; - uint8_t numHoles{}; - uint8_t shelteredEighths{}; + enum class RideClassification + { + ride, + shopOrStall, + kioskOrFacility + }; - std::unique_ptr measurement; + enum class MechanicStatus : uint8_t + { + undefined, + calling, + heading, + fixing, + hasFixedStationBrakes + }; -public: - RideStation& getStation(StationIndex stationIndex = StationIndex::FromUnderlying(0)); - const RideStation& getStation(StationIndex stationIndex = StationIndex::FromUnderlying(0)) const; - std::span getStations(); - std::span getStations() const; - StationIndex getStationIndex(const RideStation* station) const; + namespace ShelteredSectionsBits + { + constexpr uint8_t kNumShelteredSectionsMask = 0b00011111; + constexpr uint8_t kRotatingWhileSheltered = 0b00100000; + constexpr uint8_t kBankingWhileSheltered = 0b01000000; + } // namespace ShelteredSectionsBits - // Returns the logical station number from the given station. Index 0 = station 1, index 1 = station 2. It accounts for gaps - // in the station array. e.g. if only slot 0 and 2 are in use, index 2 returns 2 instead of 3. - StationIndex::UnderlyingType getStationNumber(StationIndex in) const; + enum class SpecialElement : uint8_t + { + spinningTunnel = 5, + splash = 5, + rapids = 5, + reverser = 6, + waterfall = 6, + whirlpool = 7, + }; + using SpecialElements = FlagHolder; - void chainQueues() const; - -private: - void update(); - void updateQueueLength(StationIndex stationIndex); - ResultWithMessage createVehicles(const CoordsXYE& element, bool isApplying, bool isSimulating); - void moveTrainsToBlockBrakes(const CoordsXYZ& firstBlockPosition, OpenRCT2::TrackElement& firstBlock); - money64 calculateIncomePerHour() const; - void constructMissingEntranceOrExit() const; - - ResultWithMessage changeStatusDoStationChecks(StationIndex& stationIndex); - ResultWithMessage changeStatusGetStartElement(StationIndex stationIndex, CoordsXYE& trackElement); - ResultWithMessage changeStatusCheckCompleteCircuit(const CoordsXYE& trackElement); - ResultWithMessage changeStatusCheckTrackValidity(const CoordsXYE& trackElement, bool isSimulating); - ResultWithMessage changeStatusCreateVehicles(bool isApplying, const CoordsXYE& trackElement, bool isSimulating); - -public: - bool canBreakDown() const; - RideClassification getClassification() const; - bool isRide() const; - void renew(); - void remove(); - void crash(uint8_t vehicleIndex); - void setRideEntry(OpenRCT2::ObjectEntryIndex entryIndex); - - void setNumTrains(int32_t newNumTrains); - void setNumCarsPerTrain(int32_t numCarsPerVehicle); - void setReversedTrains(bool reversedTrains); - void updateMaxVehicles(); - void updateNumberOfCircuits(); - - bool hasSpinningTunnel() const; - bool hasWaterSplash() const; - bool hasRapids() const; - bool hasLogReverser() const; - bool hasWaterfall() const; - bool hasWhirlpool() const; - - bool isPoweredLaunched() const; - bool isBlockSectioned() const; - bool canHaveMultipleCircuits() const; - bool supportsStatus(RideStatus s) const; - bool hasFailingBrakes() const; - - void stopGuestsQueuing(); - void validateStations(); - - ResultWithMessage open(bool isApplying); - ResultWithMessage test(bool isApplying); - ResultWithMessage simulate(bool isApplying); - - RideMode getDefaultMode() const; - - void setColourPreset(uint8_t trackColourPreset, uint8_t vehicleColourPreset); - - const RideObjectEntry* getRideEntry() const; - - size_t getNumPrices() const; - int32_t getAge() const; - int32_t getTotalQueueLength() const; - int32_t getMaxQueueTime() const; - - void queueInsertGuestAtFront(StationIndex stationIndex, OpenRCT2::Guest* peep); - OpenRCT2::Guest* getQueueHeadGuest(StationIndex stationIndex) const; - - void setNameToDefault(); - std::string getName() const; - void formatNameTo(OpenRCT2::Formatter&) const; - void formatStatusTo(OpenRCT2::Formatter&) const; - - static void updateAll(); - static bool nameExists(std::string_view name, RideId excludeRideId = RideId::GetNull()); - - [[nodiscard]] std::unique_ptr saveToTrackDesign(TrackDesignState& tds) const; - - uint64_t getAvailableModes() const; - const RideTypeDescriptor& getRideTypeDescriptor() const; - RideNaming getTypeNaming() const; - OpenRCT2::TrackElement* getOriginElement(StationIndex stationIndex) const; - - std::pair getMeasurement(); - - uint8_t getNumShelteredSections() const; - void increaseNumShelteredSections(); - - void removeVehicles(); /** - * Updates all pieces of the ride to match the internal ride type. (Track pieces can have different ride types from the ride - * they belong to, to enable “merging”.) + * Ride structure. + * + * This is based on RCT2's ride structure. + * Padding and no longer used fields have been removed. */ - void updateRideTypeForAllPieces(); + struct Ride + { + RideId id{ RideId::GetNull() }; + ride_type_t type{ kRideTypeNull }; + // pointer to static info. for example, wild mouse type is 0x36, subtype is + // 0x4c. + ObjectEntryIndex subtype{ kObjectEntryIndexNull }; + RideMode mode{}; + VehicleColourSettings vehicleColourSettings{}; + VehicleColour vehicleColours[Limits::kMaxVehicleColours]{}; + // 0 = closed, 1 = open, 2 = test + RideStatus status{}; + std::string customName; + uint16_t defaultNameNumber{}; + CoordsXY overallView; + EntityId vehicles[Limits::kMaxTrainsPerRide + 1]{}; // Points to the first car in the train + uint8_t departFlags{}; + uint8_t numStations{}; + uint8_t numTrains{}; + uint8_t numCarsPerTrain{}; + uint8_t proposedNumTrains{}; + uint8_t proposedNumCarsPerTrain{}; + uint8_t maxTrains{}; + uint8_t minCarsPerTrain{}; + uint8_t maxCarsPerTrain{}; + uint8_t minWaitingTime{}; + uint8_t maxWaitingTime{}; + union + { + uint8_t operationOption; + uint8_t timeLimit; + uint8_t numLaps; + uint8_t launchSpeed; + uint8_t speed; + uint8_t rotations{}; + }; - void updateSatisfaction(uint8_t happiness); - void updatePopularity(uint8_t pop_amount); - void removePeeps(); + uint8_t boatHireReturnDirection{}; + TileCoordsXY boatHireReturnPosition; + uint8_t numHelices{}; + SpecialElements specialTrackElements{}; + // Use ToHumanReadableSpeed if converting to display + int32_t maxSpeed{}; + int32_t averageSpeed{}; + uint8_t currentTestSegment{}; + uint8_t averageSpeedTestTimeout{}; + fixed16_2dp maxPositiveVerticalG{}; + fixed16_2dp maxNegativeVerticalG{}; + fixed16_2dp maxLateralG{}; + fixed16_2dp previousVerticalG{}; + fixed16_2dp previousLateralG{}; + RideTestingFlags testingFlags{}; + // x y z map location of the current track piece during a test + // this is to prevent counting special tracks multiple times + TileCoordsXYZ curTestTrackLocation; + // Next 3 variables are related (XXXX XYYY ZZZa aaaa) + uint16_t turnCountDefault{}; // X = current turn count + uint16_t turnCountBanked{}; + uint16_t turnCountSloped{}; // X = number turns > 3 elements + // Y is number of powered lifts, X is drops + uint8_t numDrops{}; + uint8_t numPoweredLifts{}; + uint8_t startDropHeight{}; + uint8_t highestDropHeight{}; + int32_t shelteredLength{}; + // Unused always 0? Should affect nausea + uint16_t var11C{}; + uint8_t numShelteredSections{}; // (?abY YYYY) + // Customer counter in the current 960 game tick (about 30 seconds) interval + uint16_t curNumCustomers{}; + // Counts ticks to update customer intervals, resets each 960 game ticks. + uint16_t numCustomersTimeout{}; + // Customer count in the last 10 * 960 game ticks (sliding window) + uint16_t numCustomers[Limits::kCustomerHistorySize]{}; + money64 price[RCT2::ObjectLimits::kMaxShopItemsPerRideEntry]{}; + TileCoordsXYZ chairliftBullwheelLocation[2]; + RideRating::Tuple ratings{}; + money64 value{}; + uint16_t chairliftBullwheelRotation{}; + uint8_t satisfaction{}; + uint8_t satisfactionTimeout{}; + uint8_t satisfactionNext{}; + // Various flags stating whether a ride window needs to be refreshed + RideInvalidateFlags windowInvalidateFlags{}; + uint32_t totalCustomers{}; + money64 totalProfit{}; + uint8_t popularity{}; + uint8_t popularityTimeout{}; // Updated every purchase and ?possibly by time? + uint8_t popularityNext{}; // When timeout reached this will be the next popularity + uint16_t numRiders{}; + uint8_t musicTuneId{}; + uint8_t slideInUse{}; + union + { + EntityId slidePeep; + uint16_t mazeTiles{}; + }; + Drawing::Colour slidePeepTShirtColour{}; + uint8_t spiralSlideProgress{}; + int32_t buildDate{}; + money64 upkeepCost{}; + EntityId raceWinner{}; + uint32_t musicPosition{}; + Breakdown breakdownReasonPending{}; + MechanicStatus mechanicStatus{}; + EntityId mechanic{ EntityId::GetNull() }; + StationIndex inspectionStation{ StationIndex::GetNull() }; + uint8_t brokenTrain{}; + uint8_t brokenCar{}; + Breakdown breakdownReason{}; + union + { + struct + { + uint8_t reliabilitySubvalue; // 0 - 255, acts like the decimals for reliabilityPercentage + uint8_t reliabilityPercentage; // Starts at 100 and decreases from there. + }; + uint16_t reliability{}; + }; + // Small constant used to increase the unreliability as the game continues, + // making breakdowns more and more likely. + uint8_t unreliabilityFactor{}; + // Range from [0, 100] + uint8_t downtime{}; + RideInspection inspectionInterval{}; + uint8_t lastInspection{}; + uint8_t downtimeHistory[Limits::kDowntimeHistorySize]{}; + uint32_t numPrimaryItemsSold{}; + uint32_t numSecondaryItemsSold{}; + // Used to oscillate the sound when ride breaks down. + // 0 = no change, 255 = max change + uint8_t breakdownSoundModifier{}; + uint8_t notFixedTimeout{}; + uint8_t lastCrashType{}; + uint8_t connectedMessageThrottle{}; + money64 incomePerHour{}; + money64 profit{}; + TrackColour trackColours[kNumRideColourSchemes]{}; + ObjectEntryIndex music{ kObjectEntryIndexNull }; + ObjectEntryIndex entranceStyle{ kObjectEntryIndexNull }; + uint16_t vehicleChangeTimeout{}; + uint8_t numBlockBrakes{}; + uint8_t liftHillSpeed{}; + uint32_t guestsFavourite{}; + RideFlags flags{}; + uint16_t totalAirTime{}; + StationIndex currentTestStation{ StationIndex::GetNull() }; + uint8_t numCircuits{}; + CoordsXYZ cableLiftLoc{}; + EntityId cableLift{ EntityId::GetNull() }; - int32_t getTotalLength() const; - int32_t getTotalTime() const; + // These two fields are used to warn users about issues. + // Such issue can be hacked rides with incompatible options set. + // They don't require export/import. + uint8_t currentIssues{}; + uint32_t lastIssueTime{}; - const OpenRCT2::StationObject* getStationObject() const; - const OpenRCT2::MusicObject* getMusicObject() const; + private: + std::array stations{}; - bool hasRecolourableShopItems() const; - bool hasStation() const; + public: + uint8_t numInversions{}; + uint8_t numHoles{}; + uint8_t shelteredEighths{}; - // TO-DO: those friend functions are temporary, find a way to not access the private fields - friend void updateSpiralSlide(Ride& ride); - friend void updateChairlift(Ride& ride); -}; -void updateSpiralSlide(Ride& ride); -void updateChairlift(Ride& ride); + std::unique_ptr measurement; -enum -{ - RIDE_TYPE_SPIRAL_ROLLER_COASTER = 0, - RIDE_TYPE_STAND_UP_ROLLER_COASTER, - RIDE_TYPE_SUSPENDED_SWINGING_COASTER, - RIDE_TYPE_INVERTED_ROLLER_COASTER, - RIDE_TYPE_JUNIOR_ROLLER_COASTER, - RIDE_TYPE_MINIATURE_RAILWAY, - RIDE_TYPE_MONORAIL, - RIDE_TYPE_MINI_SUSPENDED_COASTER, - RIDE_TYPE_BOAT_HIRE, - RIDE_TYPE_WOODEN_WILD_MOUSE, - RIDE_TYPE_STEEPLECHASE = 10, - RIDE_TYPE_CAR_RIDE, - RIDE_TYPE_LAUNCHED_FREEFALL, - RIDE_TYPE_BOBSLEIGH_COASTER, - RIDE_TYPE_OBSERVATION_TOWER, - RIDE_TYPE_LOOPING_ROLLER_COASTER, - RIDE_TYPE_DINGHY_SLIDE, - RIDE_TYPE_MINE_TRAIN_COASTER, - RIDE_TYPE_CHAIRLIFT, - RIDE_TYPE_CORKSCREW_ROLLER_COASTER, - RIDE_TYPE_MAZE = 20, - RIDE_TYPE_SPIRAL_SLIDE, - RIDE_TYPE_GO_KARTS, - RIDE_TYPE_LOG_FLUME, - RIDE_TYPE_RIVER_RAPIDS, - RIDE_TYPE_DODGEMS, - RIDE_TYPE_SWINGING_SHIP, - RIDE_TYPE_SWINGING_INVERTER_SHIP, - RIDE_TYPE_FOOD_STALL, - RIDE_TYPE_1D, - RIDE_TYPE_DRINK_STALL = 30, - RIDE_TYPE_1F, - RIDE_TYPE_SHOP, - RIDE_TYPE_MERRY_GO_ROUND, - RIDE_TYPE_22, - RIDE_TYPE_INFORMATION_KIOSK, - RIDE_TYPE_TOILETS, - RIDE_TYPE_FERRIS_WHEEL, - RIDE_TYPE_MOTION_SIMULATOR, - RIDE_TYPE_3D_CINEMA, - RIDE_TYPE_TOP_SPIN = 40, - RIDE_TYPE_SPACE_RINGS, - RIDE_TYPE_REVERSE_FREEFALL_COASTER, - RIDE_TYPE_LIFT, - RIDE_TYPE_VERTICAL_DROP_ROLLER_COASTER, - RIDE_TYPE_CASH_MACHINE, - RIDE_TYPE_TWIST, - RIDE_TYPE_HAUNTED_HOUSE, - RIDE_TYPE_FIRST_AID, - RIDE_TYPE_CIRCUS, - RIDE_TYPE_GHOST_TRAIN = 50, - RIDE_TYPE_TWISTER_ROLLER_COASTER, - RIDE_TYPE_WOODEN_ROLLER_COASTER, - RIDE_TYPE_SIDE_FRICTION_ROLLER_COASTER, - RIDE_TYPE_STEEL_WILD_MOUSE, - RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER, - RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER_ALT, - RIDE_TYPE_FLYING_ROLLER_COASTER, - RIDE_TYPE_FLYING_ROLLER_COASTER_ALT, - RIDE_TYPE_VIRGINIA_REEL, - RIDE_TYPE_SPLASH_BOATS = 60, - RIDE_TYPE_MINI_HELICOPTERS, - RIDE_TYPE_LAY_DOWN_ROLLER_COASTER, - RIDE_TYPE_SUSPENDED_MONORAIL, - RIDE_TYPE_LAY_DOWN_ROLLER_COASTER_ALT, - RIDE_TYPE_REVERSER_ROLLER_COASTER, - RIDE_TYPE_HEARTLINE_TWISTER_COASTER, - RIDE_TYPE_MINI_GOLF, - RIDE_TYPE_GIGA_COASTER, - RIDE_TYPE_ROTO_DROP, - RIDE_TYPE_FLYING_SAUCERS = 70, - RIDE_TYPE_CROOKED_HOUSE, - RIDE_TYPE_MONORAIL_CYCLES, - RIDE_TYPE_COMPACT_INVERTED_COASTER, - RIDE_TYPE_WATER_COASTER, - RIDE_TYPE_AIR_POWERED_VERTICAL_COASTER, - RIDE_TYPE_INVERTED_HAIRPIN_COASTER, - RIDE_TYPE_MAGIC_CARPET, - RIDE_TYPE_SUBMARINE_RIDE, - RIDE_TYPE_RIVER_RAFTS, - RIDE_TYPE_50 = 80, - RIDE_TYPE_ENTERPRISE, - RIDE_TYPE_52, - RIDE_TYPE_53, - RIDE_TYPE_54, - RIDE_TYPE_55, - RIDE_TYPE_INVERTED_IMPULSE_COASTER, - RIDE_TYPE_MINI_ROLLER_COASTER, - RIDE_TYPE_MINE_RIDE, - RIDE_TYPE_59, - RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER = 90, - RIDE_TYPE_HYPERCOASTER, - RIDE_TYPE_HYPER_TWISTER, - RIDE_TYPE_MONSTER_TRUCKS, - RIDE_TYPE_SPINNING_WILD_MOUSE, - RIDE_TYPE_CLASSIC_MINI_ROLLER_COASTER, - RIDE_TYPE_HYBRID_COASTER, - RIDE_TYPE_SINGLE_RAIL_ROLLER_COASTER, - RIDE_TYPE_ALPINE_COASTER, - RIDE_TYPE_CLASSIC_WOODEN_ROLLER_COASTER, - RIDE_TYPE_CLASSIC_STAND_UP_ROLLER_COASTER, - RIDE_TYPE_LSM_LAUNCHED_ROLLER_COASTER, - RIDE_TYPE_CLASSIC_WOODEN_TWISTER_ROLLER_COASTER, + public: + RideStation& getStation(StationIndex stationIndex = StationIndex::FromUnderlying(0)); + const RideStation& getStation(StationIndex stationIndex = StationIndex::FromUnderlying(0)) const; + std::span getStations(); + std::span getStations() const; + StationIndex getStationIndex(const RideStation* station) const; - RIDE_TYPE_COUNT -}; + // Returns the logical station number from the given station. Index 0 = station 1, index 1 = station 2. It accounts for + // gaps in the station array. e.g. if only slot 0 and 2 are in use, index 2 returns 2 instead of 3. + StationIndex::UnderlyingType getStationNumber(StationIndex in) const; -enum class RideStatus : uint8_t -{ - closed, - open, - testing, - simulating, - count, -}; + void chainQueues() const; -enum class RideMode : uint8_t -{ - normal, - continuousCircuit, - reverseInclineLaunchedShuttle, - poweredLaunchPassthrough, // RCT2 style, pass through station - shuttle, - boatHire, - upwardLaunch, - rotatingLift, - stationToStation, - singleRidePerAdmission, - unlimitedRidesPerAdmission = 10, - maze, - race, - dodgems, - swing, - shopStall, - rotation, - forwardRotation, - backwardRotation, - filmAvengingAviators, - mouseTails3DFilm = 20, - spaceRings, - beginners, - limPoweredLaunch, - filmThrillRiders, - stormChasers3DFilm, - spaceRaiders3DFilm, - intense, - berserk, - hauntedHouse, - circus = 30, - downwardLaunch, - crookedHouse, - freefallDrop, - continuousCircuitBlockSectioned, - poweredLaunch, // RCT1 style, don't pass through station - poweredLaunchBlockSectioned, + private: + void update(); + void updateQueueLength(StationIndex stationIndex); + ResultWithMessage createVehicles(const CoordsXYE& element, bool isApplying, bool isSimulating); + void moveTrainsToBlockBrakes(const CoordsXYZ& firstBlockPosition, TrackElement& firstBlock); + money64 calculateIncomePerHour() const; + void constructMissingEntranceOrExit() const; - count, - nullMode = 255, -}; + ResultWithMessage changeStatusDoStationChecks(StationIndex& stationIndex); + ResultWithMessage changeStatusGetStartElement(StationIndex stationIndex, CoordsXYE& trackElement); + ResultWithMessage changeStatusCheckCompleteCircuit(const CoordsXYE& trackElement); + ResultWithMessage changeStatusCheckTrackValidity(const CoordsXYE& trackElement, bool isSimulating); + ResultWithMessage changeStatusCreateVehicles(bool isApplying, const CoordsXYE& trackElement, bool isSimulating); -RideMode& operator++(RideMode& d, int); + public: + bool canBreakDown() const; + RideClassification getClassification() const; + bool isRide() const; + void renew(); + void remove(); + void crash(uint8_t vehicleIndex); + void setRideEntry(ObjectEntryIndex entryIndex); -enum class RideCategory : uint8_t -{ - transport, - gentle, - rollerCoaster, - thrill, - water, - shop, + void setNumTrains(int32_t newNumTrains); + void setNumCarsPerTrain(int32_t numCarsPerVehicle); + void setReversedTrains(bool reversedTrains); + void updateMaxVehicles(); + void updateNumberOfCircuits(); - none = 255, -}; + bool hasSpinningTunnel() const; + bool hasWaterSplash() const; + bool hasRapids() const; + bool hasLogReverser() const; + bool hasWaterfall() const; + bool hasWhirlpool() const; -enum -{ - MUSIC_STYLE_DODGEMS_BEAT, - MUSIC_STYLE_FAIRGROUND_ORGAN, - MUSIC_STYLE_ROMAN_FANFARE, - MUSIC_STYLE_ORIENTAL, - MUSIC_STYLE_MARTIAN, - MUSIC_STYLE_JUNGLE_DRUMS, - MUSIC_STYLE_EGYPTIAN, - MUSIC_STYLE_TOYLAND, - MUSIC_STYLE_CIRCUS_SHOW, - MUSIC_STYLE_SPACE, - MUSIC_STYLE_HORROR, - MUSIC_STYLE_TECHNO, - MUSIC_STYLE_GENTLE, - MUSIC_STYLE_SUMMER, - MUSIC_STYLE_WATER, - MUSIC_STYLE_WILD_WEST, - MUSIC_STYLE_JURASSIC, - MUSIC_STYLE_ROCK, - MUSIC_STYLE_RAGTIME, - MUSIC_STYLE_FANTASY, - MUSIC_STYLE_ROCK_STYLE_2, - MUSIC_STYLE_ICE, - MUSIC_STYLE_SNOW, - MUSIC_STYLE_CUSTOM_MUSIC_1, - MUSIC_STYLE_CUSTOM_MUSIC_2, - MUSIC_STYLE_MEDIEVAL, - MUSIC_STYLE_URBAN, - MUSIC_STYLE_ORGAN, - MUSIC_STYLE_MECHANICAL, - MUSIC_STYLE_MODERN, - MUSIC_STYLE_PIRATES, - MUSIC_STYLE_ROCK_STYLE_3, - MUSIC_STYLE_CANDY_STYLE, - MUSIC_STYLE_COUNT -}; + bool isPoweredLaunched() const; + bool isBlockSectioned() const; + bool canHaveMultipleCircuits() const; + bool supportsStatus(RideStatus s) const; + bool hasFailingBrakes() const; -enum -{ - RIDE_DEPART_WAIT_FOR_LOAD_MASK = 7, - RIDE_DEPART_WAIT_FOR_LOAD = 1 << 3, - RIDE_DEPART_LEAVE_WHEN_ANOTHER_ARRIVES = 1 << 4, - RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS = 1 << 5, - RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH = 1 << 6, - RIDE_DEPART_WAIT_FOR_MAXIMUM_LENGTH = 1 << 7 -}; + void stopGuestsQueuing(); + void validateStations(); -enum -{ - WAIT_FOR_LOAD_QUARTER, - WAIT_FOR_LOAD_HALF, - WAIT_FOR_LOAD_THREE_QUARTER, - WAIT_FOR_LOAD_FULL, - WAIT_FOR_LOAD_ANY, + ResultWithMessage open(bool isApplying); + ResultWithMessage test(bool isApplying); + ResultWithMessage simulate(bool isApplying); - WAIT_FOR_LOAD_COUNT, -}; + RideMode getDefaultMode() const; -enum -{ - RIDE_CRASH_TYPE_NONE = 0, - RIDE_CRASH_TYPE_NO_FATALITIES = 2, - RIDE_CRASH_TYPE_FATALITIES = 8 -}; + void setColourPreset(uint8_t trackColourPreset, uint8_t vehicleColourPreset); -enum MazeWallType : uint8_t -{ - brick, - hedges, - ice, - wooden, -}; + const RideObjectEntry* getRideEntry() const; -enum -{ - RIDE_ISSUE_NONE = 0, - RIDE_ISSUE_GUESTS_STUCK = (1 << 0), -}; + size_t getNumPrices() const; + int32_t getAge() const; + int32_t getTotalQueueLength() const; + int32_t getMaxQueueTime() const; -constexpr uint8_t kMaxRideMeasurements = 8; -constexpr money64 kRideValueUndefined = kMoney64Undefined; -constexpr uint16_t kRideInitialReliability = ((100 << 8) | 0xFF); // Upper byte is percentage, lower byte is "decimal". + void queueInsertGuestAtFront(StationIndex stationIndex, Guest* peep); + Guest* getQueueHeadGuest(StationIndex stationIndex) const; -constexpr uint8_t kStationDepartFlag = (1 << 7); -constexpr uint8_t kStationDepartMask = static_cast(~kStationDepartFlag); + void setNameToDefault(); + std::string getName() const; + void formatNameTo(Formatter&) const; + void formatStatusTo(Formatter&) const; -constexpr uint16_t kCurrentTurnCountMask = 0xF800; -constexpr uint16_t kTurnMask1Element = 0x001F; -constexpr uint16_t kTurnMask2Elements = 0x00E0; -constexpr uint16_t kTurnMask3Elements = 0x0700; -constexpr uint16_t kTurnMask4PlusElements = 0xF800; + static void updateAll(); + static bool nameExists(std::string_view name, RideId excludeRideId = RideId::GetNull()); -Ride* GetRide(RideId index); + [[nodiscard]] std::unique_ptr saveToTrackDesign(TrackDesignState& tds) const; -RideId GetNextFreeRideId(); -Ride* RideAllocateAtIndex(RideId index); -Ride& RideGetTemporaryForPreview(); -void RideDelete(RideId id); + uint64_t getAvailableModes() const; + const RideTypeDescriptor& getRideTypeDescriptor() const; + RideNaming getTypeNaming() const; + TrackElement* getOriginElement(StationIndex stationIndex) const; -const RideObjectEntry* GetRideEntryByIndex(OpenRCT2::ObjectEntryIndex index); -std::string_view GetRideEntryName(OpenRCT2::ObjectEntryIndex index); + std::pair getMeasurement(); -int32_t RideGetCount(); -void RideInitAll(); -void ResetAllRideBuildDates(); -void RideUpdateFavouritedStat(); -void RideCheckAllReachable(); + uint8_t getNumShelteredSections() const; + void increaseNumShelteredSections(); -bool RideTryGetOriginElement(const Ride& ride, CoordsXYE* output); -void RideClearBlockedTiles(const Ride& ride); -OpenRCT2::Staff* RideGetMechanic(const Ride& ride); -OpenRCT2::Staff* RideGetAssignedMechanic(const Ride& ride); -VehicleColour RideGetVehicleColour(const Ride& ride, int32_t vehicleIndex); -int32_t RideGetUnusedPresetVehicleColour(OpenRCT2::ObjectEntryIndex subType, uint32_t randomValue); -void RideSetVehicleColoursToRandomPreset(Ride& ride, uint8_t preset_index); -void RideMeasurementsUpdate(); -void RideBreakdownAddNewsItem(const Ride& ride); -OpenRCT2::Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection); -int32_t RideInitialiseConstructionWindow(Ride& ride); -void RideSetMapTooltip(const OpenRCT2::TileElement& tileElement); -void RidePrepareBreakdown(Ride& ride, Breakdown breakdownReason); -OpenRCT2::TileElement* RideGetStationStartTrackElement(const Ride& ride, StationIndex stationIndex); -OpenRCT2::TileElement* RideGetStationExitElement(const CoordsXYZ& elementPos); -money64 RideGetRefundPrice(const Ride& ride); -int32_t RideGetRandomColourPresetIndex(ride_type_t rideType); -money64 RideGetCommonPrice(const Ride& forRide); + void removeVehicles(); + /** + * Updates all pieces of the ride to match the internal ride type. (Track pieces can have different ride types from the + * ride they belong to, to enable “merging”.) + */ + void updateRideTypeForAllPieces(); -void RideClearForConstruction(Ride& ride); -void InvalidateTestResults(Ride& ride); + void updateSatisfaction(uint8_t happiness); + void updatePopularity(uint8_t pop_amount); + void removePeeps(); -void IncrementTurnCount1Element(Ride& ride, uint8_t type); -void IncrementTurnCount2Elements(Ride& ride, uint8_t type); -void IncrementTurnCount3Elements(Ride& ride, uint8_t type); -void IncrementTurnCount4PlusElements(Ride& ride, uint8_t type); -int32_t GetTurnCount1Element(const Ride& ride, uint8_t type); -int32_t GetTurnCount2Elements(const Ride& ride, uint8_t type); -int32_t GetTurnCount3Elements(const Ride& ride, uint8_t type); -int32_t GetTurnCount4PlusElements(const Ride& ride, uint8_t type); + int32_t getTotalLength() const; + int32_t getTotalTime() const; -bool RideHasAnyTrackElements(const Ride& ride); + const StationObject* getStationObject() const; + const MusicObject* getMusicObject() const; -void RideGetStartOfTrack(CoordsXYE* output); + bool hasRecolourableShopItems() const; + bool hasStation() const; -money64 RideEntranceExitPlaceGhost( - const Ride& ride, const CoordsXY& entranceExitCoords, Direction direction, int32_t placeType, StationIndex stationNum); + // TO-DO: those friend functions are temporary, find a way to not access the private fields + friend void updateSpiralSlide(Ride& ride); + friend void updateChairlift(Ride& ride); + }; + void updateSpiralSlide(Ride& ride); + void updateChairlift(Ride& ride); -ResultWithMessage RideAreAllPossibleEntrancesAndExitsBuilt(const Ride& ride); -void RideFixBreakdown(Ride& ride, int32_t reliabilityIncreaseFactor); + enum + { + RIDE_TYPE_SPIRAL_ROLLER_COASTER = 0, + RIDE_TYPE_STAND_UP_ROLLER_COASTER, + RIDE_TYPE_SUSPENDED_SWINGING_COASTER, + RIDE_TYPE_INVERTED_ROLLER_COASTER, + RIDE_TYPE_JUNIOR_ROLLER_COASTER, + RIDE_TYPE_MINIATURE_RAILWAY, + RIDE_TYPE_MONORAIL, + RIDE_TYPE_MINI_SUSPENDED_COASTER, + RIDE_TYPE_BOAT_HIRE, + RIDE_TYPE_WOODEN_WILD_MOUSE, + RIDE_TYPE_STEEPLECHASE = 10, + RIDE_TYPE_CAR_RIDE, + RIDE_TYPE_LAUNCHED_FREEFALL, + RIDE_TYPE_BOBSLEIGH_COASTER, + RIDE_TYPE_OBSERVATION_TOWER, + RIDE_TYPE_LOOPING_ROLLER_COASTER, + RIDE_TYPE_DINGHY_SLIDE, + RIDE_TYPE_MINE_TRAIN_COASTER, + RIDE_TYPE_CHAIRLIFT, + RIDE_TYPE_CORKSCREW_ROLLER_COASTER, + RIDE_TYPE_MAZE = 20, + RIDE_TYPE_SPIRAL_SLIDE, + RIDE_TYPE_GO_KARTS, + RIDE_TYPE_LOG_FLUME, + RIDE_TYPE_RIVER_RAPIDS, + RIDE_TYPE_DODGEMS, + RIDE_TYPE_SWINGING_SHIP, + RIDE_TYPE_SWINGING_INVERTER_SHIP, + RIDE_TYPE_FOOD_STALL, + RIDE_TYPE_1D, + RIDE_TYPE_DRINK_STALL = 30, + RIDE_TYPE_1F, + RIDE_TYPE_SHOP, + RIDE_TYPE_MERRY_GO_ROUND, + RIDE_TYPE_22, + RIDE_TYPE_INFORMATION_KIOSK, + RIDE_TYPE_TOILETS, + RIDE_TYPE_FERRIS_WHEEL, + RIDE_TYPE_MOTION_SIMULATOR, + RIDE_TYPE_3D_CINEMA, + RIDE_TYPE_TOP_SPIN = 40, + RIDE_TYPE_SPACE_RINGS, + RIDE_TYPE_REVERSE_FREEFALL_COASTER, + RIDE_TYPE_LIFT, + RIDE_TYPE_VERTICAL_DROP_ROLLER_COASTER, + RIDE_TYPE_CASH_MACHINE, + RIDE_TYPE_TWIST, + RIDE_TYPE_HAUNTED_HOUSE, + RIDE_TYPE_FIRST_AID, + RIDE_TYPE_CIRCUS, + RIDE_TYPE_GHOST_TRAIN = 50, + RIDE_TYPE_TWISTER_ROLLER_COASTER, + RIDE_TYPE_WOODEN_ROLLER_COASTER, + RIDE_TYPE_SIDE_FRICTION_ROLLER_COASTER, + RIDE_TYPE_STEEL_WILD_MOUSE, + RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER, + RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER_ALT, + RIDE_TYPE_FLYING_ROLLER_COASTER, + RIDE_TYPE_FLYING_ROLLER_COASTER_ALT, + RIDE_TYPE_VIRGINIA_REEL, + RIDE_TYPE_SPLASH_BOATS = 60, + RIDE_TYPE_MINI_HELICOPTERS, + RIDE_TYPE_LAY_DOWN_ROLLER_COASTER, + RIDE_TYPE_SUSPENDED_MONORAIL, + RIDE_TYPE_LAY_DOWN_ROLLER_COASTER_ALT, + RIDE_TYPE_REVERSER_ROLLER_COASTER, + RIDE_TYPE_HEARTLINE_TWISTER_COASTER, + RIDE_TYPE_MINI_GOLF, + RIDE_TYPE_GIGA_COASTER, + RIDE_TYPE_ROTO_DROP, + RIDE_TYPE_FLYING_SAUCERS = 70, + RIDE_TYPE_CROOKED_HOUSE, + RIDE_TYPE_MONORAIL_CYCLES, + RIDE_TYPE_COMPACT_INVERTED_COASTER, + RIDE_TYPE_WATER_COASTER, + RIDE_TYPE_AIR_POWERED_VERTICAL_COASTER, + RIDE_TYPE_INVERTED_HAIRPIN_COASTER, + RIDE_TYPE_MAGIC_CARPET, + RIDE_TYPE_SUBMARINE_RIDE, + RIDE_TYPE_RIVER_RAFTS, + RIDE_TYPE_50 = 80, + RIDE_TYPE_ENTERPRISE, + RIDE_TYPE_52, + RIDE_TYPE_53, + RIDE_TYPE_54, + RIDE_TYPE_55, + RIDE_TYPE_INVERTED_IMPULSE_COASTER, + RIDE_TYPE_MINI_ROLLER_COASTER, + RIDE_TYPE_MINE_RIDE, + RIDE_TYPE_59, + RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER = 90, + RIDE_TYPE_HYPERCOASTER, + RIDE_TYPE_HYPER_TWISTER, + RIDE_TYPE_MONSTER_TRUCKS, + RIDE_TYPE_SPINNING_WILD_MOUSE, + RIDE_TYPE_CLASSIC_MINI_ROLLER_COASTER, + RIDE_TYPE_HYBRID_COASTER, + RIDE_TYPE_SINGLE_RAIL_ROLLER_COASTER, + RIDE_TYPE_ALPINE_COASTER, + RIDE_TYPE_CLASSIC_WOODEN_ROLLER_COASTER, + RIDE_TYPE_CLASSIC_STAND_UP_ROLLER_COASTER, + RIDE_TYPE_LSM_LAUNCHED_ROLLER_COASTER, + RIDE_TYPE_CLASSIC_WOODEN_TWISTER_ROLLER_COASTER, -void BlockBrakeSetLinkedBrakesClosed(const CoordsXYZ& vehicleTrackLocation, OpenRCT2::TrackElement& tileElement, bool isOpen); + RIDE_TYPE_COUNT + }; -uint8_t RideEntryGetVehicleAtPosition(int32_t rideEntryIndex, int32_t numCarsPerTrain, int32_t position); -void RideUpdateVehicleColours(const Ride& ride); + enum class RideStatus : uint8_t + { + closed, + open, + testing, + simulating, + count, + }; -OpenRCT2::BitSet RideEntryGetSupportedTrackPieces(const RideObjectEntry& rideEntry); + enum class RideMode : uint8_t + { + normal, + continuousCircuit, + reverseInclineLaunchedShuttle, + poweredLaunchPassthrough, // RCT2 style, pass through station + shuttle, + boatHire, + upwardLaunch, + rotatingLift, + stationToStation, + singleRidePerAdmission, + unlimitedRidesPerAdmission = 10, + maze, + race, + dodgems, + swing, + shopStall, + rotation, + forwardRotation, + backwardRotation, + filmAvengingAviators, + mouseTails3DFilm = 20, + spaceRings, + beginners, + limPoweredLaunch, + filmThrillRiders, + stormChasers3DFilm, + spaceRaiders3DFilm, + intense, + berserk, + hauntedHouse, + circus = 30, + downwardLaunch, + crookedHouse, + freefallDrop, + continuousCircuitBlockSectioned, + poweredLaunch, // RCT1 style, don't pass through station + poweredLaunchBlockSectioned, -uint32_t RideCustomersPerHour(const Ride& ride); -uint32_t RideCustomersInLast5Minutes(const Ride& ride); + count, + nullMode = 255, + }; -Vehicle* RideGetBrokenVehicle(const Ride& ride); + RideMode& operator++(RideMode& d, int); -money64 RideGetPrice(const Ride& ride); + enum class RideCategory : uint8_t + { + transport, + gentle, + rollerCoaster, + thrill, + water, + shop, -OpenRCT2::TileElement* GetStationPlatform(const CoordsXYRangedZ& coords); -bool RideHasAdjacentStation(const Ride& ride); -bool RideHasStationShelter(const Ride& ride); -bool RideHasRatings(const Ride& ride); + none = 255, + }; -int32_t GetUnifiedBoosterSpeed(ride_type_t rideType, int32_t relativeSpeed); -void FixInvalidVehicleSpriteSizes(); -bool RideEntryHasCategory(const RideObjectEntry& rideEntry, RideCategory category); + enum + { + MUSIC_STYLE_DODGEMS_BEAT, + MUSIC_STYLE_FAIRGROUND_ORGAN, + MUSIC_STYLE_ROMAN_FANFARE, + MUSIC_STYLE_ORIENTAL, + MUSIC_STYLE_MARTIAN, + MUSIC_STYLE_JUNGLE_DRUMS, + MUSIC_STYLE_EGYPTIAN, + MUSIC_STYLE_TOYLAND, + MUSIC_STYLE_CIRCUS_SHOW, + MUSIC_STYLE_SPACE, + MUSIC_STYLE_HORROR, + MUSIC_STYLE_TECHNO, + MUSIC_STYLE_GENTLE, + MUSIC_STYLE_SUMMER, + MUSIC_STYLE_WATER, + MUSIC_STYLE_WILD_WEST, + MUSIC_STYLE_JURASSIC, + MUSIC_STYLE_ROCK, + MUSIC_STYLE_RAGTIME, + MUSIC_STYLE_FANTASY, + MUSIC_STYLE_ROCK_STYLE_2, + MUSIC_STYLE_ICE, + MUSIC_STYLE_SNOW, + MUSIC_STYLE_CUSTOM_MUSIC_1, + MUSIC_STYLE_CUSTOM_MUSIC_2, + MUSIC_STYLE_MEDIEVAL, + MUSIC_STYLE_URBAN, + MUSIC_STYLE_ORGAN, + MUSIC_STYLE_MECHANICAL, + MUSIC_STYLE_MODERN, + MUSIC_STYLE_PIRATES, + MUSIC_STYLE_ROCK_STYLE_3, + MUSIC_STYLE_CANDY_STYLE, + MUSIC_STYLE_COUNT + }; -OpenRCT2::ObjectEntryIndex RideGetEntryIndex(ride_type_t rideType, OpenRCT2::ObjectEntryIndex rideSubType); + enum + { + RIDE_DEPART_WAIT_FOR_LOAD_MASK = 7, + RIDE_DEPART_WAIT_FOR_LOAD = 1 << 3, + RIDE_DEPART_LEAVE_WHEN_ANOTHER_ARRIVES = 1 << 4, + RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS = 1 << 5, + RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH = 1 << 6, + RIDE_DEPART_WAIT_FOR_MAXIMUM_LENGTH = 1 << 7 + }; -void DetermineRideEntranceAndExitLocations(); -void RideClearLeftoverEntrances(const Ride& ride); + enum + { + WAIT_FOR_LOAD_QUARTER, + WAIT_FOR_LOAD_HALF, + WAIT_FOR_LOAD_THREE_QUARTER, + WAIT_FOR_LOAD_FULL, + WAIT_FOR_LOAD_ANY, -void SetBrakeClosedMultiTile(OpenRCT2::TrackElement& trackElement, const CoordsXY& trackLocation, bool isClosed); + WAIT_FOR_LOAD_COUNT, + }; -std::vector GetTracklessRides(); + enum + { + RIDE_CRASH_TYPE_NONE = 0, + RIDE_CRASH_TYPE_NO_FATALITIES = 2, + RIDE_CRASH_TYPE_FATALITIES = 8 + }; -void CircusMusicUpdate(Ride& ride); -void DefaultMusicUpdate(Ride& ride); + enum MazeWallType : uint8_t + { + brick, + hedges, + ice, + wooden, + }; -RideMode RideModeGetBlockSectionedCounterpart(RideMode originalMode); + enum + { + RIDE_ISSUE_NONE = 0, + RIDE_ISSUE_GUESTS_STUCK = (1 << 0), + }; + + constexpr uint8_t kMaxRideMeasurements = 8; + constexpr money64 kRideValueUndefined = kMoney64Undefined; + constexpr uint16_t kRideInitialReliability = ((100 << 8) | 0xFF); // Upper byte is percentage, lower byte is "decimal". + + constexpr uint8_t kStationDepartFlag = (1 << 7); + constexpr uint8_t kStationDepartMask = static_cast(~kStationDepartFlag); + + constexpr uint16_t kCurrentTurnCountMask = 0xF800; + constexpr uint16_t kTurnMask1Element = 0x001F; + constexpr uint16_t kTurnMask2Elements = 0x00E0; + constexpr uint16_t kTurnMask3Elements = 0x0700; + constexpr uint16_t kTurnMask4PlusElements = 0xF800; + + Ride* GetRide(RideId index); + + RideId GetNextFreeRideId(); + Ride* RideAllocateAtIndex(RideId index); + Ride& RideGetTemporaryForPreview(); + void RideDelete(RideId id); + + const RideObjectEntry* GetRideEntryByIndex(ObjectEntryIndex index); + std::string_view GetRideEntryName(ObjectEntryIndex index); + + int32_t RideGetCount(); + void RideInitAll(); + void ResetAllRideBuildDates(); + void RideUpdateFavouritedStat(); + void RideCheckAllReachable(); + + bool RideTryGetOriginElement(const Ride& ride, CoordsXYE* output); + void RideClearBlockedTiles(const Ride& ride); + Staff* RideGetMechanic(const Ride& ride); + Staff* RideGetAssignedMechanic(const Ride& ride); + VehicleColour RideGetVehicleColour(const Ride& ride, int32_t vehicleIndex); + int32_t RideGetUnusedPresetVehicleColour(ObjectEntryIndex subType, uint32_t randomValue); + void RideSetVehicleColoursToRandomPreset(Ride& ride, uint8_t preset_index); + void RideMeasurementsUpdate(); + void RideBreakdownAddNewsItem(const Ride& ride); + Staff* RideFindClosestMechanic(const Ride& ride, int32_t forInspection); + int32_t RideInitialiseConstructionWindow(Ride& ride); + void RideSetMapTooltip(const TileElement& tileElement); + void RidePrepareBreakdown(Ride& ride, Breakdown breakdownReason); + TileElement* RideGetStationStartTrackElement(const Ride& ride, StationIndex stationIndex); + TileElement* RideGetStationExitElement(const CoordsXYZ& elementPos); + money64 RideGetRefundPrice(const Ride& ride); + int32_t RideGetRandomColourPresetIndex(ride_type_t rideType); + money64 RideGetCommonPrice(const Ride& forRide); + + void RideClearForConstruction(Ride& ride); + void InvalidateTestResults(Ride& ride); + + void IncrementTurnCount1Element(Ride& ride, uint8_t type); + void IncrementTurnCount2Elements(Ride& ride, uint8_t type); + void IncrementTurnCount3Elements(Ride& ride, uint8_t type); + void IncrementTurnCount4PlusElements(Ride& ride, uint8_t type); + int32_t GetTurnCount1Element(const Ride& ride, uint8_t type); + int32_t GetTurnCount2Elements(const Ride& ride, uint8_t type); + int32_t GetTurnCount3Elements(const Ride& ride, uint8_t type); + int32_t GetTurnCount4PlusElements(const Ride& ride, uint8_t type); + + bool RideHasAnyTrackElements(const Ride& ride); + + void RideGetStartOfTrack(CoordsXYE* output); + + money64 RideEntranceExitPlaceGhost( + const Ride& ride, const CoordsXY& entranceExitCoords, Direction direction, int32_t placeType, StationIndex stationNum); + + ResultWithMessage RideAreAllPossibleEntrancesAndExitsBuilt(const Ride& ride); + void RideFixBreakdown(Ride& ride, int32_t reliabilityIncreaseFactor); + + void BlockBrakeSetLinkedBrakesClosed(const CoordsXYZ& vehicleTrackLocation, TrackElement& tileElement, bool isOpen); + + uint8_t RideEntryGetVehicleAtPosition(int32_t rideEntryIndex, int32_t numCarsPerTrain, int32_t position); + void RideUpdateVehicleColours(const Ride& ride); + + BitSet RideEntryGetSupportedTrackPieces(const RideObjectEntry& rideEntry); + + uint32_t RideCustomersPerHour(const Ride& ride); + uint32_t RideCustomersInLast5Minutes(const Ride& ride); + + Vehicle* RideGetBrokenVehicle(const Ride& ride); + + money64 RideGetPrice(const Ride& ride); + + TileElement* GetStationPlatform(const CoordsXYRangedZ& coords); + bool RideHasAdjacentStation(const Ride& ride); + bool RideHasStationShelter(const Ride& ride); + bool RideHasRatings(const Ride& ride); + + int32_t GetUnifiedBoosterSpeed(ride_type_t rideType, int32_t relativeSpeed); + void FixInvalidVehicleSpriteSizes(); + bool RideEntryHasCategory(const RideObjectEntry& rideEntry, RideCategory category); + + ObjectEntryIndex RideGetEntryIndex(ride_type_t rideType, ObjectEntryIndex rideSubType); + + void DetermineRideEntranceAndExitLocations(); + void RideClearLeftoverEntrances(const Ride& ride); + + void SetBrakeClosedMultiTile(TrackElement& trackElement, const CoordsXY& trackLocation, bool isClosed); + + std::vector GetTracklessRides(); + + void CircusMusicUpdate(Ride& ride); + void DefaultMusicUpdate(Ride& ride); + + RideMode RideModeGetBlockSectionedCounterpart(RideMode originalMode); +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideAudio.h b/src/openrct2/ride/RideAudio.h index a4bf8d1163..4a7e15e087 100644 --- a/src/openrct2/ride/RideAudio.h +++ b/src/openrct2/ride/RideAudio.h @@ -15,7 +15,11 @@ #include struct CoordsXYZ; -struct Ride; + +namespace OpenRCT2 +{ + struct Ride; +} namespace OpenRCT2::RideAudio { diff --git a/src/openrct2/ride/RideBreakdownMap.h b/src/openrct2/ride/RideBreakdownMap.h index 280f1536b0..2f4d364243 100644 --- a/src/openrct2/ride/RideBreakdownMap.h +++ b/src/openrct2/ride/RideBreakdownMap.h @@ -13,13 +13,18 @@ #include "Ride.h" #ifdef ENABLE_SCRIPTING -static const EnumMap kBreakdownMap( - { { "safety_cut_out", Breakdown::safetyCutOut }, - { "restraints_stuck_closed", Breakdown::restraintsStuckClosed }, - { "restraints_stuck_open", Breakdown::restraintsStuckOpen }, - { "doors_stuck_closed", Breakdown::doorsStuckClosed }, - { "doors_stuck_open", Breakdown::doorsStuckOpen }, - { "vehicle_malfunction", Breakdown::vehicleMalfunction }, - { "brakes_failure", Breakdown::brakesFailure }, - { "control_failure", Breakdown::controlFailure } }); + +namespace OpenRCT2 +{ + static const EnumMap kBreakdownMap( + { { "safety_cut_out", Breakdown::safetyCutOut }, + { "restraints_stuck_closed", Breakdown::restraintsStuckClosed }, + { "restraints_stuck_open", Breakdown::restraintsStuckOpen }, + { "doors_stuck_closed", Breakdown::doorsStuckClosed }, + { "doors_stuck_open", Breakdown::doorsStuckOpen }, + { "vehicle_malfunction", Breakdown::vehicleMalfunction }, + { "brakes_failure", Breakdown::brakesFailure }, + { "control_failure", Breakdown::controlFailure } }); +} + #endif diff --git a/src/openrct2/ride/RideConstruction.cpp b/src/openrct2/ride/RideConstruction.cpp index 38f76c271c..bce2f95da4 100644 --- a/src/openrct2/ride/RideConstruction.cpp +++ b/src/openrct2/ride/RideConstruction.cpp @@ -49,1696 +49,1701 @@ #include #include -using namespace OpenRCT2; -using namespace OpenRCT2::TrackMetadata; -using OpenRCT2::GameActions::CommandFlag; -using OpenRCT2::GameActions::CommandFlags; - -struct TrackDescriptor +namespace OpenRCT2 { - bool startsDiagonally; - TrackPitch slopeStart; - TrackRoll rollStart; - TrackCurve trackCurve; - TrackPitch slopeEnd; - TrackRoll rollEnd; - TrackElemType trackElement; -}; + using namespace OpenRCT2::TrackMetadata; + using OpenRCT2::GameActions::CommandFlag; + using OpenRCT2::GameActions::CommandFlags; -// clang-format off -static constexpr TrackDescriptor kNextSelectedPiece[186] = { - { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagDown60 }, - { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagDown60ToDown25 }, - { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagDown60ToFlat }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagDown25ToDown60 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagDown25 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagDown25ToLeftBank }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagDown25ToFlat }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagDown25ToRightBank }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonal }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagLeftBankToDown25 }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBank }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankToFlat }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagLeftBankToUp25 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::none, TrackElemType::leftEighthToOrthogonal }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagFlatToDown60 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagFlatToDown25 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagFlatToLeftBank }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagFlat }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagFlatToRightBank }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagFlatToUp25 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagFlatToUp60 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::none, TrackElemType::rightEighthToOrthogonal }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagRightBankToDown25 }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankToFlat }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBank }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagRightBankToUp25 }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonal }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagUp25ToLeftBank }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagUp25ToFlat }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagUp25ToRightBank }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagUp25 }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagUp25ToUp60 }, - { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagUp60ToFlat }, - { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagUp60ToUp25 }, - { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagUp60 }, - { false, TrackPitch::down90, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down90, TrackRoll::none, TrackElemType::leftQuarterTurn1TileDown90 }, - { false, TrackPitch::down90, TrackRoll::none, TrackCurve::none, TrackPitch::down90, TrackRoll::none, TrackElemType::down90 }, - { false, TrackPitch::down90, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down90ToDown60 }, - { false, TrackPitch::down90, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down90, TrackRoll::none, TrackElemType::rightQuarterTurn1TileDown90 }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down60, TrackRoll::none, TrackElemType::leftQuarterTurn1TileDown60 }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down90, TrackRoll::none, TrackElemType::down60ToDown90 }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down60 }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::down60ToDown25 }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::down60ToFlat }, - { false, TrackPitch::down60, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down60, TrackRoll::none, TrackElemType::rightQuarterTurn1TileDown60 }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3TileDown25 }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::left, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn5TileDown25 }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::down25LeftBanked }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::leftBankedDown25ToDown25 }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedDown25ToLeftBankedFlat }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankedDown25ToFlat }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down25, TrackRoll::none, TrackElemType::leftQuarterTurn3TilesDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::left, TrackElemType::leftQuarterTurn3TilesDown25ToLeftBank }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::left, TrackPitch::down25, TrackRoll::none, TrackElemType::leftQuarterTurn5TilesDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down25ToDown60 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::down25ToLeftBankedDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::down25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::down25ToRightBankedDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::down25ToLeftBank }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::down25ToFlat }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::down25ToRightBank }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::right, TrackPitch::down25, TrackRoll::none, TrackElemType::rightQuarterTurn5TilesDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::right, TrackElemType::rightQuarterTurn3TilesDown25ToRightBank }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down25, TrackRoll::none, TrackElemType::rightQuarterTurn3TilesDown25 }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::rightBankedDown25ToDown25 }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::down25RightBanked }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankedDown25ToFlat }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedDown25ToRightBankedFlat }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::right, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn5TileDown25 }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3TileDown25 }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3Tiles }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankToLeftQuarterTurn3TilesUp25 }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::left, TrackPitch::none, TrackRoll::left, TrackElemType::bankedLeftQuarterTurn5Tiles }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::left, TrackElemType::leftEighthBankToDiag }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedFlatToLeftBankedDown25 }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::leftBankToDown25 }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBank }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankToFlat }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedFlatToLeftBankedUp25 }, - { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankToUp25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn3Tiles }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::left, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn5Tiles }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::none, TrackElemType::leftEighthToDiag }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::flatToDown60 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::flatToLeftBankedDown25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::flatToDown25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::flatToRightBankedDown25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::flatToLeftBank }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::flat }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftVerySmall, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn1Tile }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightVerySmall, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn1Tile }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::flatToRightBank }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::flatToLeftBankedUp25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::flatToUp25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::flatToRightBankedUp25 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::flatToUp60 }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::none, TrackElemType::rightEighthToDiag }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::right, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn5Tiles }, - { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn3Tiles }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::rightBankToDown25 }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedFlatToRightBankedDown25 }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankToFlat }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBank }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankToUp25 }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedFlatToRightBankedUp25 }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::right, TrackElemType::rightEighthBankToDiag }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::right, TrackPitch::none, TrackRoll::right, TrackElemType::bankedRightQuarterTurn5Tiles }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3Tiles }, - { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankToRightQuarterTurn3TilesUp25 }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3TileUp25 }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::left, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn5TileUp25 }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedUp25ToLeftBankedFlat }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankedUp25ToFlat }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::up25LeftBanked }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankedUp25ToUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::leftQuarterTurn3TilesUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::left, TrackPitch::up25, TrackRoll::none, TrackElemType::leftQuarterTurn5TilesUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::up25ToLeftBank }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::up25ToFlat }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::up25ToRightBank }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::up25ToLeftBankedUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::up25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::up25ToRightBankedUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up25ToUp60 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::right, TrackPitch::up25, TrackRoll::none, TrackElemType::rightQuarterTurn5TilesUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::rightQuarterTurn3TilesUp25 }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankedUp25ToFlat }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedUp25ToRightBankedFlat }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankedUp25ToUp25 }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::up25RightBanked }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::right, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn5TileUp25 }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3TileUp25 }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up60, TrackRoll::none, TrackElemType::leftQuarterTurn1TileUp60 }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::up60ToFlat }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::up60ToUp25 }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up60 }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up90, TrackRoll::none, TrackElemType::up60ToUp90 }, - { false, TrackPitch::up60, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up60, TrackRoll::none, TrackElemType::rightQuarterTurn1TileUp60 }, - { false, TrackPitch::up90, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up90, TrackRoll::none, TrackElemType::leftQuarterTurn1TileUp90 }, - { false, TrackPitch::up90, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up90ToUp60 }, - { false, TrackPitch::up90, TrackRoll::none, TrackCurve::none, TrackPitch::up90, TrackRoll::none, TrackElemType::up90 }, - { false, TrackPitch::up90, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up90, TrackRoll::none, TrackElemType::rightQuarterTurn1TileUp90 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::leftEighthToDiagUp25 }, - { false, TrackPitch::up25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::rightEighthToDiagUp25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::leftEighthToDiagDown25 }, - { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::rightEighthToDiagDown25 }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::leftEighthToOrthogonalUp25 }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::rightEighthToOrthogonalUp25 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::leftEighthToOrthogonalDown25 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::rightEighthToOrthogonalDown25 }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagUp25ToLeftBankedUp25 }, - { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagUp25ToRightBankedUp25 }, - { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagLeftBankedUp25ToUp25 }, - { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagRightBankedUp25ToUp25 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagDown25ToLeftBankedDown25 }, - { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagDown25ToRightBankedDown25 }, - { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagLeftBankedDown25ToDown25 }, - { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagRightBankedDown25ToDown25 }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagLeftBankedFlatToLeftBankedUp25 }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagRightBankedFlatToRightBankedUp25 }, - { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBankedUp25ToLeftBankedFlat }, - { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBankedUp25ToRightBankedFlat }, - { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagLeftBankedFlatToLeftBankedDown25 }, - { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagRightBankedFlatToRightBankedDown25 }, - { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBankedDown25ToLeftBankedFlat }, - { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBankedDown25ToRightBankedFlat }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagFlatToLeftBankedUp25 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagFlatToRightBankedUp25 }, - { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankedUp25ToFlat }, - { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankedUp25ToFlat }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagFlatToLeftBankedDown25 }, - { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagFlatToRightBankedDown25 }, - { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankedDown25ToFlat }, - { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankedDown25ToFlat }, - { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagUp25LeftBanked }, - { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagUp25RightBanked }, - { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagDown25LeftBanked }, - { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagDown25RightBanked }, - { false, TrackPitch::up25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::left, TrackElemType::leftEighthBankToDiagUp25 }, - { false, TrackPitch::up25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::right, TrackElemType::rightEighthBankToDiagUp25 }, - { false, TrackPitch::down25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::left, TrackElemType::leftEighthBankToDiagDown25 }, - { false, TrackPitch::down25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::right, TrackElemType::rightEighthBankToDiagDown25 }, - { true, TrackPitch::up25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonalUp25 }, - { true, TrackPitch::up25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonalUp25 }, - { true, TrackPitch::down25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonalDown25 }, - { true, TrackPitch::down25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonalDown25 }, -}; -// clang-format on - -money64 _currentTrackPrice; - -TypeOrCurve _currentlySelectedTrack{}; -RideConstructionState _rideConstructionState; -RideId _currentRideIndex; - -CoordsXYZ _currentTrackBegin; - -uint8_t _currentTrackPieceDirection; -TrackElemType _currentTrackPieceType; -TrackSelectionFlags _currentTrackSelectionFlags; -uint32_t _rideConstructionNextArrowPulse = 0; -TrackPitch _currentTrackPitchEnd; -TrackRoll _currentTrackRollEnd; -bool _currentTrackHasLiftHill; -SelectedAlternative _currentTrackAlternative{}; -TrackElemType _selectedTrackType; - -TrackRoll _previousTrackRollEnd; -TrackPitch _previousTrackPitchEnd; - -CoordsXYZ _previousTrackPiece; - -uint8_t _currentBrakeSpeed; -RideColourScheme _currentColourScheme; -uint8_t _currentSeatRotationAngle; - -CoordsXYZD _unkF440C5; - -uint8_t gRideEntranceExitPlaceType; -RideId gRideEntranceExitPlaceRideIndex; -StationIndex gRideEntranceExitPlaceStationIndex; -RideConstructionState gRideEntranceExitPlacePreviousRideConstructionState; -Direction gRideEntranceExitPlaceDirection; - -using namespace OpenRCT2; -using namespace OpenRCT2::TrackMetadata; - -static int32_t ride_check_if_construction_allowed(Ride& ride) -{ - Formatter ft; - const auto* rideEntry = ride.getRideEntry(); - if (rideEntry == nullptr) + struct TrackDescriptor { - ContextShowError(STR_INVALID_RIDE_TYPE, STR_CANT_EDIT_INVALID_RIDE_TYPE, ft); - return 0; - } - if (ride.flags.has(RideFlag::brokenDown)) + bool startsDiagonally; + TrackPitch slopeStart; + TrackRoll rollStart; + TrackCurve trackCurve; + TrackPitch slopeEnd; + TrackRoll rollEnd; + TrackElemType trackElement; + }; + + // clang-format off + static constexpr TrackDescriptor kNextSelectedPiece[186] = { + { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagDown60 }, + { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagDown60ToDown25 }, + { true, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagDown60ToFlat }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagDown25ToDown60 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagDown25 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagDown25ToLeftBank }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagDown25ToFlat }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagDown25ToRightBank }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonal }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagLeftBankToDown25 }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBank }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankToFlat }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagLeftBankToUp25 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::none, TrackElemType::leftEighthToOrthogonal }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::diagFlatToDown60 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagFlatToDown25 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagFlatToLeftBank }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagFlat }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagFlatToRightBank }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagFlatToUp25 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagFlatToUp60 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::none, TrackElemType::rightEighthToOrthogonal }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagRightBankToDown25 }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankToFlat }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBank }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagRightBankToUp25 }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonal }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagUp25ToLeftBank }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagUp25ToFlat }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagUp25ToRightBank }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagUp25 }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagUp25ToUp60 }, + { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagUp60ToFlat }, + { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagUp60ToUp25 }, + { true, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::diagUp60 }, + { false, TrackPitch::down90, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down90, TrackRoll::none, TrackElemType::leftQuarterTurn1TileDown90 }, + { false, TrackPitch::down90, TrackRoll::none, TrackCurve::none, TrackPitch::down90, TrackRoll::none, TrackElemType::down90 }, + { false, TrackPitch::down90, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down90ToDown60 }, + { false, TrackPitch::down90, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down90, TrackRoll::none, TrackElemType::rightQuarterTurn1TileDown90 }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down60, TrackRoll::none, TrackElemType::leftQuarterTurn1TileDown60 }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down90, TrackRoll::none, TrackElemType::down60ToDown90 }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down60 }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::down60ToDown25 }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::down60ToFlat }, + { false, TrackPitch::down60, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down60, TrackRoll::none, TrackElemType::rightQuarterTurn1TileDown60 }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3TileDown25 }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::left, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn5TileDown25 }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::down25LeftBanked }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::leftBankedDown25ToDown25 }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedDown25ToLeftBankedFlat }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankedDown25ToFlat }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::down25, TrackRoll::none, TrackElemType::leftQuarterTurn3TilesDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::left, TrackElemType::leftQuarterTurn3TilesDown25ToLeftBank }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::left, TrackPitch::down25, TrackRoll::none, TrackElemType::leftQuarterTurn5TilesDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::down25ToDown60 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::down25ToLeftBankedDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::down25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::down25ToRightBankedDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::down25ToLeftBank }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::down25ToFlat }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::down25ToRightBank }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::right, TrackPitch::down25, TrackRoll::none, TrackElemType::rightQuarterTurn5TilesDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::right, TrackElemType::rightQuarterTurn3TilesDown25ToRightBank }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::down25, TrackRoll::none, TrackElemType::rightQuarterTurn3TilesDown25 }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::rightBankedDown25ToDown25 }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::down25RightBanked }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankedDown25ToFlat }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedDown25ToRightBankedFlat }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::right, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn5TileDown25 }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3TileDown25 }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3Tiles }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankToLeftQuarterTurn3TilesUp25 }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::left, TrackPitch::none, TrackRoll::left, TrackElemType::bankedLeftQuarterTurn5Tiles }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::left, TrackElemType::leftEighthBankToDiag }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::leftBankedFlatToLeftBankedDown25 }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::leftBankToDown25 }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBank }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankToFlat }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedFlatToLeftBankedUp25 }, + { false, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankToUp25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn3Tiles }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::left, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn5Tiles }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::none, TrackRoll::none, TrackElemType::leftEighthToDiag }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down60, TrackRoll::none, TrackElemType::flatToDown60 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::flatToLeftBankedDown25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::flatToDown25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::flatToRightBankedDown25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::flatToLeftBank }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::flat }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::leftVerySmall, TrackPitch::none, TrackRoll::none, TrackElemType::leftQuarterTurn1Tile }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightVerySmall, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn1Tile }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::flatToRightBank }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::flatToLeftBankedUp25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::flatToUp25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::flatToRightBankedUp25 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::flatToUp60 }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::none, TrackElemType::rightEighthToDiag }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::right, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn5Tiles }, + { false, TrackPitch::none, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::none, TrackElemType::rightQuarterTurn3Tiles }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::rightBankToDown25 }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::rightBankedFlatToRightBankedDown25 }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankToFlat }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBank }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankToUp25 }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedFlatToRightBankedUp25 }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::none, TrackRoll::right, TrackElemType::rightEighthBankToDiag }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::right, TrackPitch::none, TrackRoll::right, TrackElemType::bankedRightQuarterTurn5Tiles }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3Tiles }, + { false, TrackPitch::none, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankToRightQuarterTurn3TilesUp25 }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn3TileUp25 }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::left, TrackPitch::up25, TrackRoll::left, TrackElemType::leftBankedQuarterTurn5TileUp25 }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::leftBankedUp25ToLeftBankedFlat }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::leftBankedUp25ToFlat }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::up25LeftBanked }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::leftBankedUp25ToUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::leftQuarterTurn3TilesUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::left, TrackPitch::up25, TrackRoll::none, TrackElemType::leftQuarterTurn5TilesUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::up25ToLeftBank }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::up25ToFlat }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::up25ToRightBank }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::up25ToLeftBankedUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::up25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::up25ToRightBankedUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up25ToUp60 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::right, TrackPitch::up25, TrackRoll::none, TrackElemType::rightQuarterTurn5TilesUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::none, TrackElemType::rightQuarterTurn3TilesUp25 }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::rightBankedUp25ToFlat }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::rightBankedUp25ToRightBankedFlat }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::rightBankedUp25ToUp25 }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::up25RightBanked }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::right, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn5TileUp25 }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::rightSmall, TrackPitch::up25, TrackRoll::right, TrackElemType::rightBankedQuarterTurn3TileUp25 }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up60, TrackRoll::none, TrackElemType::leftQuarterTurn1TileUp60 }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::up60ToFlat }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::up60ToUp25 }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up60 }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::none, TrackPitch::up90, TrackRoll::none, TrackElemType::up60ToUp90 }, + { false, TrackPitch::up60, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up60, TrackRoll::none, TrackElemType::rightQuarterTurn1TileUp60 }, + { false, TrackPitch::up90, TrackRoll::none, TrackCurve::leftSmall, TrackPitch::up90, TrackRoll::none, TrackElemType::leftQuarterTurn1TileUp90 }, + { false, TrackPitch::up90, TrackRoll::none, TrackCurve::none, TrackPitch::up60, TrackRoll::none, TrackElemType::up90ToUp60 }, + { false, TrackPitch::up90, TrackRoll::none, TrackCurve::none, TrackPitch::up90, TrackRoll::none, TrackElemType::up90 }, + { false, TrackPitch::up90, TrackRoll::none, TrackCurve::rightSmall, TrackPitch::up90, TrackRoll::none, TrackElemType::rightQuarterTurn1TileUp90 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::leftEighthToDiagUp25 }, + { false, TrackPitch::up25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::rightEighthToDiagUp25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::leftEighthToDiagDown25 }, + { false, TrackPitch::down25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::rightEighthToDiagDown25 }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::leftEighthToOrthogonalUp25 }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::none, TrackElemType::rightEighthToOrthogonalUp25 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::leftEighthToOrthogonalDown25 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::none, TrackElemType::rightEighthToOrthogonalDown25 }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagUp25ToLeftBankedUp25 }, + { true, TrackPitch::up25, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagUp25ToRightBankedUp25 }, + { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagLeftBankedUp25ToUp25 }, + { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::none, TrackElemType::diagRightBankedUp25ToUp25 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagDown25ToLeftBankedDown25 }, + { true, TrackPitch::down25, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagDown25ToRightBankedDown25 }, + { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagLeftBankedDown25ToDown25 }, + { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::none, TrackElemType::diagRightBankedDown25ToDown25 }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagLeftBankedFlatToLeftBankedUp25 }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagRightBankedFlatToRightBankedUp25 }, + { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBankedUp25ToLeftBankedFlat }, + { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBankedUp25ToRightBankedFlat }, + { true, TrackPitch::none, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagLeftBankedFlatToLeftBankedDown25 }, + { true, TrackPitch::none, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagRightBankedFlatToRightBankedDown25 }, + { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::left, TrackElemType::diagLeftBankedDown25ToLeftBankedFlat }, + { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::right, TrackElemType::diagRightBankedDown25ToRightBankedFlat }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagFlatToLeftBankedUp25 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagFlatToRightBankedUp25 }, + { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankedUp25ToFlat }, + { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankedUp25ToFlat }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagFlatToLeftBankedDown25 }, + { true, TrackPitch::none, TrackRoll::none, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagFlatToRightBankedDown25 }, + { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagLeftBankedDown25ToFlat }, + { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::none, TrackRoll::none, TrackElemType::diagRightBankedDown25ToFlat }, + { true, TrackPitch::up25, TrackRoll::left, TrackCurve::none, TrackPitch::up25, TrackRoll::left, TrackElemType::diagUp25LeftBanked }, + { true, TrackPitch::up25, TrackRoll::right, TrackCurve::none, TrackPitch::up25, TrackRoll::right, TrackElemType::diagUp25RightBanked }, + { true, TrackPitch::down25, TrackRoll::left, TrackCurve::none, TrackPitch::down25, TrackRoll::left, TrackElemType::diagDown25LeftBanked }, + { true, TrackPitch::down25, TrackRoll::right, TrackCurve::none, TrackPitch::down25, TrackRoll::right, TrackElemType::diagDown25RightBanked }, + { false, TrackPitch::up25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::left, TrackElemType::leftEighthBankToDiagUp25 }, + { false, TrackPitch::up25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::right, TrackElemType::rightEighthBankToDiagUp25 }, + { false, TrackPitch::down25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::left, TrackElemType::leftEighthBankToDiagDown25 }, + { false, TrackPitch::down25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::right, TrackElemType::rightEighthBankToDiagDown25 }, + { true, TrackPitch::up25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::up25, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonalUp25 }, + { true, TrackPitch::up25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::up25, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonalUp25 }, + { true, TrackPitch::down25, TrackRoll::left, TrackCurve::leftLarge, TrackPitch::down25, TrackRoll::left, TrackElemType::leftEighthBankToOrthogonalDown25 }, + { true, TrackPitch::down25, TrackRoll::right, TrackCurve::rightLarge, TrackPitch::down25, TrackRoll::right, TrackElemType::rightEighthBankToOrthogonalDown25 }, + }; + // clang-format on + + money64 _currentTrackPrice; + + TypeOrCurve _currentlySelectedTrack{}; + RideConstructionState _rideConstructionState; + RideId _currentRideIndex; + + CoordsXYZ _currentTrackBegin; + + uint8_t _currentTrackPieceDirection; + TrackElemType _currentTrackPieceType; + TrackSelectionFlags _currentTrackSelectionFlags; + uint32_t _rideConstructionNextArrowPulse = 0; + TrackPitch _currentTrackPitchEnd; + TrackRoll _currentTrackRollEnd; + bool _currentTrackHasLiftHill; + SelectedAlternative _currentTrackAlternative{}; + TrackElemType _selectedTrackType; + + TrackRoll _previousTrackRollEnd; + TrackPitch _previousTrackPitchEnd; + + CoordsXYZ _previousTrackPiece; + + uint8_t _currentBrakeSpeed; + RideColourScheme _currentColourScheme; + uint8_t _currentSeatRotationAngle; + + CoordsXYZD _unkF440C5; + + uint8_t gRideEntranceExitPlaceType; + RideId gRideEntranceExitPlaceRideIndex; + StationIndex gRideEntranceExitPlaceStationIndex; + RideConstructionState gRideEntranceExitPlacePreviousRideConstructionState; + Direction gRideEntranceExitPlaceDirection; + + using namespace OpenRCT2::TrackMetadata; + + static int32_t ride_check_if_construction_allowed(Ride& ride) { - ride.formatNameTo(ft); - ContextShowError(STR_CANT_START_CONSTRUCTION_ON, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING, ft); - return 0; - } - - if (ride.status != RideStatus::closed && ride.status != RideStatus::simulating) - { - ride.formatNameTo(ft); - ContextShowError(STR_CANT_START_CONSTRUCTION_ON, STR_MUST_BE_CLOSED_FIRST, ft); - return 0; - } - - return 1; -} - -static WindowBase* ride_create_or_find_construction_window(RideId rideIndex) -{ - auto* windowManager = Ui::GetWindowManager(); - auto intent = Intent(INTENT_ACTION_RIDE_CONSTRUCTION_FOCUS); - intent.PutExtra(INTENT_EXTRA_RIDE_ID, rideIndex.ToUnderlying()); - windowManager->BroadcastIntent(intent); - return windowManager->FindByClass(WindowClass::rideConstruction); -} - -/** - * - * rct2: 0x006B4857 - */ -void RideConstructionStart(Ride& ride) -{ - CoordsXYE trackElement; - if (RideTryGetOriginElement(ride, &trackElement)) - { - findTrackGap(ride, trackElement, &trackElement); - - WindowBase* w = WindowGetMain(); - if (w != nullptr && RideModify(trackElement)) - WindowScrollToLocation(*w, { trackElement, trackElement.element->getBaseZ() }); - } - else - { - RideInitialiseConstructionWindow(ride); - } -} - -/** - * - * rct2: 0x006DD4D5 - */ -static void ride_remove_cable_lift(Ride& ride) -{ - if (ride.flags.has(RideFlag::cableLift)) - { - ride.flags.unset(RideFlag::cableLift); - auto spriteIndex = ride.cableLift; - do + Formatter ft; + const auto* rideEntry = ride.getRideEntry(); + if (rideEntry == nullptr) { - Vehicle* vehicle = getGameState().entities.GetEntity(spriteIndex); - if (vehicle == nullptr) - { - return; - } - vehicle->invalidate(); - spriteIndex = vehicle->next_vehicle_on_train; - getGameState().entities.EntityRemove(vehicle); - } while (!spriteIndex.IsNull()); - } -} - -/** - * - * rct2: 0x006DD506 - */ -void Ride::removeVehicles() -{ - if (flags.has(RideFlag::onTrack)) - { - flags.unset(RideFlag::onTrack, RideFlag::testInProgress, RideFlag::hasStalledVehicle); - - for (size_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) + ContextShowError(STR_INVALID_RIDE_TYPE, STR_CANT_EDIT_INVALID_RIDE_TYPE, ft); + return 0; + } + if (ride.flags.has(RideFlag::brokenDown)) { - auto spriteIndex = vehicles[i]; - while (!spriteIndex.IsNull()) + ride.formatNameTo(ft); + ContextShowError(STR_CANT_START_CONSTRUCTION_ON, STR_HAS_BROKEN_DOWN_AND_REQUIRES_FIXING, ft); + return 0; + } + + if (ride.status != RideStatus::closed && ride.status != RideStatus::simulating) + { + ride.formatNameTo(ft); + ContextShowError(STR_CANT_START_CONSTRUCTION_ON, STR_MUST_BE_CLOSED_FIRST, ft); + return 0; + } + + return 1; + } + + static WindowBase* ride_create_or_find_construction_window(RideId rideIndex) + { + auto* windowManager = Ui::GetWindowManager(); + auto intent = Intent(INTENT_ACTION_RIDE_CONSTRUCTION_FOCUS); + intent.PutExtra(INTENT_EXTRA_RIDE_ID, rideIndex.ToUnderlying()); + windowManager->BroadcastIntent(intent); + return windowManager->FindByClass(WindowClass::rideConstruction); + } + + /** + * + * rct2: 0x006B4857 + */ + void RideConstructionStart(Ride& ride) + { + CoordsXYE trackElement; + if (RideTryGetOriginElement(ride, &trackElement)) + { + findTrackGap(ride, trackElement, &trackElement); + + WindowBase* w = WindowGetMain(); + if (w != nullptr && RideModify(trackElement)) + WindowScrollToLocation(*w, { trackElement, trackElement.element->getBaseZ() }); + } + else + { + RideInitialiseConstructionWindow(ride); + } + } + + /** + * + * rct2: 0x006DD4D5 + */ + static void ride_remove_cable_lift(Ride& ride) + { + if (ride.flags.has(RideFlag::cableLift)) + { + ride.flags.unset(RideFlag::cableLift); + auto spriteIndex = ride.cableLift; + do { Vehicle* vehicle = getGameState().entities.GetEntity(spriteIndex); if (vehicle == nullptr) { - break; + return; } vehicle->invalidate(); spriteIndex = vehicle->next_vehicle_on_train; getGameState().entities.EntityRemove(vehicle); - } - - vehicles[i] = EntityId::GetNull(); - } - - for (size_t i = 0; i < Limits::kMaxStationsPerRide; i++) - stations[i].TrainAtStation = RideStation::kNoTrain; - - // Also clean up orphaned vehicles for good measure. - for (auto* vehicle : TrainManager::View()) - { - if (vehicle->ride == id) - { - vehicle->invalidate(); - getGameState().entities.EntityRemove(vehicle); - } - } - } -} - -/** - * - * rct2: 0x006DD4AC - */ -void RideClearForConstruction(Ride& ride) -{ - ride.measurement = {}; - - ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown); - ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); - - // Open circuit rides will go directly into building mode (creating ghosts) where it would normally clear the stats, - // however this causes desyncs since it's directly run from the window and other clients would not get it. - // To prevent these problems, unconditionally invalidate the test results on all clients in multiplayer games. - if (Network::GetMode() != Network::Mode::none) - { - InvalidateTestResults(ride); - } - - ride_remove_cable_lift(ride); - ride.removeVehicles(); - RideClearBlockedTiles(ride); - - // Force close simulating rides, to reset flag widget in Construction UI - if (ride.status == RideStatus::simulating) - { - ride.status = RideStatus::closed; - } - - auto* windowMgr = Ui::GetWindowManager(); - auto w = windowMgr->FindByNumber(WindowClass::ride, ride.id.ToUnderlying()); - if (w != nullptr) - w->onResize(); -} - -/** - * - * rct2: 0x006664DF - */ -void Ride::removePeeps() -{ - // Find first station - auto stationIndex = RideGetFirstValidStationStart(*this); - - // Get exit position and direction - auto exitPosition = CoordsXYZD{ 0, 0, 0, kInvalidDirection }; - if (!stationIndex.IsNull()) - { - auto location = getStation(stationIndex).Exit.ToCoordsXYZD(); - if (!location.IsNull()) - { - auto direction = DirectionReverse(location.direction); - exitPosition = location; - exitPosition.x += (DirectionOffsets[direction].x * 20) + kCoordsXYHalfTile; - exitPosition.y += (DirectionOffsets[direction].y * 20) + kCoordsXYHalfTile; - exitPosition.z += 2; - - // Reverse direction - exitPosition.direction = DirectionReverse(exitPosition.direction); - - exitPosition.direction *= 8; + } while (!spriteIndex.IsNull()); } } - // Place all the guests at exit - for (auto peep : EntityList()) + /** + * + * rct2: 0x006DD506 + */ + void Ride::removeVehicles() { - if (peep->State == PeepState::queuingFront || peep->State == PeepState::enteringRide - || peep->State == PeepState::leavingRide || peep->State == PeepState::onRide) + if (flags.has(RideFlag::onTrack)) { - if (peep->CurrentRide != id) - continue; + flags.unset(RideFlag::onTrack, RideFlag::testInProgress, RideFlag::hasStalledVehicle); - PeepDecrementNumRiders(peep); - if (peep->State == PeepState::queuingFront && peep->RideSubState == PeepRideSubState::atEntrance) - peep->removeFromQueue(); + for (size_t i = 0; i <= Limits::kMaxTrainsPerRide; i++) + { + auto spriteIndex = vehicles[i]; + while (!spriteIndex.IsNull()) + { + Vehicle* vehicle = getGameState().entities.GetEntity(spriteIndex); + if (vehicle == nullptr) + { + break; + } + vehicle->invalidate(); + spriteIndex = vehicle->next_vehicle_on_train; + getGameState().entities.EntityRemove(vehicle); + } - if (exitPosition.direction == kInvalidDirection) - { - CoordsXYZ newLoc = { peep->NextLoc.ToTileCentre(), peep->NextLoc.z }; - if (peep->GetNextIsSloped()) - newLoc.z += kCoordsZStep; - newLoc.z++; - peep->moveTo(newLoc); - } - else - { - peep->moveTo(exitPosition); - peep->orientation = exitPosition.direction; + vehicles[i] = EntityId::GetNull(); } - peep->State = PeepState::falling; - peep->SwitchToSpecialSprite(0); + for (size_t i = 0; i < Limits::kMaxStationsPerRide; i++) + stations[i].TrainAtStation = RideStation::kNoTrain; - peep->happiness = std::min(peep->happiness, peep->happinessTarget) / 2; - peep->happinessTarget = peep->happiness; - peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; + // Also clean up orphaned vehicles for good measure. + for (auto* vehicle : TrainManager::View()) + { + if (vehicle->ride == id) + { + vehicle->invalidate(); + getGameState().entities.EntityRemove(vehicle); + } + } } } - // Place all the staff at exit - for (auto peep : EntityList()) + + /** + * + * rct2: 0x006DD4AC + */ + void RideClearForConstruction(Ride& ride) { - if (peep->State == PeepState::fixing || peep->State == PeepState::inspecting) + ride.measurement = {}; + + ride.flags.unset(RideFlag::breakdownPending, RideFlag::brokenDown); + ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + + // Open circuit rides will go directly into building mode (creating ghosts) where it would normally clear the stats, + // however this causes desyncs since it's directly run from the window and other clients would not get it. + // To prevent these problems, unconditionally invalidate the test results on all clients in multiplayer games. + if (Network::GetMode() != Network::Mode::none) { - if (peep->CurrentRide != id) - continue; - - if (exitPosition.direction == kInvalidDirection) - { - CoordsXYZ newLoc = { peep->NextLoc.ToTileCentre(), peep->NextLoc.z }; - if (peep->GetNextIsSloped()) - newLoc.z += kCoordsZStep; - newLoc.z++; - peep->moveTo(newLoc); - } - else - { - peep->moveTo(exitPosition); - peep->orientation = exitPosition.direction; - } - - peep->State = PeepState::falling; - peep->SwitchToSpecialSprite(0); - - peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; + InvalidateTestResults(ride); } - } - numRiders = 0; - slideInUse = 0; - windowInvalidateFlags.set(RideInvalidateFlag::main); -} -void RideClearBlockedTiles(const Ride& ride) -{ - auto& gameState = getGameState(); - for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) - { - for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) + ride_remove_cable_lift(ride); + ride.removeVehicles(); + RideClearBlockedTiles(ride); + + // Force close simulating rides, to reset flag widget in Construction UI + if (ride.status == RideStatus::simulating) { - for (auto* trackElement : TileElementsView(tilePos.ToCoordsXY())) + ride.status = RideStatus::closed; + } + + auto* windowMgr = Ui::GetWindowManager(); + auto w = windowMgr->FindByNumber(WindowClass::ride, ride.id.ToUnderlying()); + if (w != nullptr) + w->onResize(); + } + + /** + * + * rct2: 0x006664DF + */ + void Ride::removePeeps() + { + // Find first station + auto stationIndex = RideGetFirstValidStationStart(*this); + + // Get exit position and direction + auto exitPosition = CoordsXYZD{ 0, 0, 0, kInvalidDirection }; + if (!stationIndex.IsNull()) + { + auto location = getStation(stationIndex).Exit.ToCoordsXYZD(); + if (!location.IsNull()) { - if (trackElement->GetRideIndex() != ride.id) + auto direction = DirectionReverse(location.direction); + exitPosition = location; + exitPosition.x += (DirectionOffsets[direction].x * 20) + kCoordsXYHalfTile; + exitPosition.y += (DirectionOffsets[direction].y * 20) + kCoordsXYHalfTile; + exitPosition.z += 2; + + // Reverse direction + exitPosition.direction = DirectionReverse(exitPosition.direction); + + exitPosition.direction *= 8; + } + } + + // Place all the guests at exit + for (auto peep : EntityList()) + { + if (peep->State == PeepState::queuingFront || peep->State == PeepState::enteringRide + || peep->State == PeepState::leavingRide || peep->State == PeepState::onRide) + { + if (peep->CurrentRide != id) continue; - // Unblock footpath element that is at same position - auto* footpathElement = MapGetFootpathElement(TileCoordsXYZ{ tilePos, trackElement->baseHeight }.ToCoordsXYZ()); + PeepDecrementNumRiders(peep); + if (peep->State == PeepState::queuingFront && peep->RideSubState == PeepRideSubState::atEntrance) + peep->removeFromQueue(); - if (footpathElement == nullptr) + if (exitPosition.direction == kInvalidDirection) + { + CoordsXYZ newLoc = { peep->NextLoc.ToTileCentre(), peep->NextLoc.z }; + if (peep->GetNextIsSloped()) + newLoc.z += kCoordsZStep; + newLoc.z++; + peep->moveTo(newLoc); + } + else + { + peep->moveTo(exitPosition); + peep->orientation = exitPosition.direction; + } + + peep->State = PeepState::falling; + peep->SwitchToSpecialSprite(0); + + peep->happiness = std::min(peep->happiness, peep->happinessTarget) / 2; + peep->happinessTarget = peep->happiness; + peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; + } + } + // Place all the staff at exit + for (auto peep : EntityList()) + { + if (peep->State == PeepState::fixing || peep->State == PeepState::inspecting) + { + if (peep->CurrentRide != id) continue; - footpathElement->SetIsBlockedByVehicle(false); + if (exitPosition.direction == kInvalidDirection) + { + CoordsXYZ newLoc = { peep->NextLoc.ToTileCentre(), peep->NextLoc.z }; + if (peep->GetNextIsSloped()) + newLoc.z += kCoordsZStep; + newLoc.z++; + peep->moveTo(newLoc); + } + else + { + peep->moveTo(exitPosition); + peep->orientation = exitPosition.direction; + } + + peep->State = PeepState::falling; + peep->SwitchToSpecialSprite(0); + + peep->WindowInvalidateFlags |= PEEP_INVALIDATE_PEEP_STATS; } } - } -} - -/** - * Gets the origin track element (sequence 0). Seems to do more than that though and even invalidates track. - * rct2: 0x006C683D - * ax : x - * bx : direction << 8, type - * cx : y - * dx : z - * si : extra_params - * di : output_element - * bp : flags - */ -std::optional GetTrackElementOriginAndApplyChanges( - const CoordsXYZD& location, TrackElemType type, uint16_t extra_params, TileElement** output_element, - TrackElementSetFlags flags) -{ - // Find the relevant track piece, prefer sequence 0 (this ensures correct behaviour for diagonal track pieces) - auto trackElement = MapGetTrackElementAtOfTypeSeq(location, type, 0); - if (trackElement == nullptr) - { - trackElement = MapGetTrackElementAtOfType(location, type); - if (trackElement == nullptr) - { - return std::nullopt; - } + numRiders = 0; + slideInUse = 0; + windowInvalidateFlags.set(RideInvalidateFlag::main); } - // Possibly z should be & 0xF8 - const auto& ted = GetTrackElementDescriptor(type); - - // Now find all the elements that belong to this track piece - int32_t sequence = trackElement->GetSequenceIndex(); - uint8_t mapDirection = trackElement->getDirection(); - if (sequence >= ted.sequenceData.numSequences) - return std::nullopt; - - const auto& trackBlock = ted.sequenceData.sequences[sequence].clearance; - - CoordsXY offsets = { trackBlock.x, trackBlock.y }; - CoordsXY newCoords = location; - newCoords += offsets.Rotate(DirectionReverse(mapDirection)); - - auto retCoordsXYZ = CoordsXYZ{ newCoords.x, newCoords.y, location.z - trackBlock.z }; - - int32_t start_z = retCoordsXYZ.z; - assert(ted.sequenceData.numSequences > 0); - const auto block0 = ted.sequenceData.sequences[0].clearance; - - retCoordsXYZ.z += block0.z; - for (int32_t i = 0; i < ted.sequenceData.numSequences; i++) + void RideClearBlockedTiles(const Ride& ride) { - const auto& block = ted.sequenceData.sequences[i].clearance; - CoordsXY cur = { retCoordsXYZ }; - offsets = { block.x, block.y }; - cur += offsets.Rotate(mapDirection); - int32_t cur_z = start_z + block.z; - - MapInvalidateTileFull(cur); - - trackElement = MapGetTrackElementAtOfTypeSeq({ cur, cur_z, static_cast(location.direction) }, type, i); - if (trackElement == nullptr) + auto& gameState = getGameState(); + for (TileCoordsXY tilePos = {}; tilePos.x < gameState.mapSize.x; ++tilePos.x) { - return std::nullopt; - } - if (i == 0 && output_element != nullptr) - { - *output_element = reinterpret_cast(trackElement); - } - if (flags.has(TrackElementSetFlag::highlightOff)) - { - trackElement->SetHighlight(false); - } - if (flags.has(TrackElementSetFlag::highlightOn)) - { - trackElement->SetHighlight(true); - } - if (flags.has(TrackElementSetFlag::colourScheme)) - { - auto newScheme = static_cast(extra_params & 0xFF); - trackElement->SetColourScheme(newScheme); - - if (_previousTrackPiece == retCoordsXYZ) + for (tilePos.y = 0; tilePos.y < gameState.mapSize.y; ++tilePos.y) { - _currentColourScheme = newScheme; + for (auto* trackElement : TileElementsView(tilePos.ToCoordsXY())) + { + if (trackElement->GetRideIndex() != ride.id) + continue; + + // Unblock footpath element that is at same position + auto* footpathElement = MapGetFootpathElement( + TileCoordsXYZ{ tilePos, trackElement->baseHeight }.ToCoordsXYZ()); + + if (footpathElement == nullptr) + continue; + + footpathElement->SetIsBlockedByVehicle(false); + } } } - if (flags.has(TrackElementSetFlag::seatRotation)) - { - trackElement->SetSeatRotation(static_cast(extra_params & 0xFF)); - } - if (flags.has(TrackElementSetFlag::cableLiftOn)) - { - trackElement->SetHasCableLift(true); - } - if (flags.has(TrackElementSetFlag::cableLiftOff)) - { - trackElement->SetHasCableLift(false); - } - if (flags.has(TrackElementSetFlag::brakeClosed)) - { - trackElement->SetBrakeClosed(extra_params != 0); - } - if (flags.has(TrackElementSetFlag::brakeBoosterSpeed)) - { - trackElement->SetBrakeBoosterSpeed(static_cast(extra_params & 0xFF)); - } } - return retCoordsXYZ; -} -static void WindowRideConstructionUpdateActiveElements() -{ - auto intent = Intent(INTENT_ACTION_RIDE_CONSTRUCTION_UPDATE_ACTIVE_ELEMENTS); - ContextBroadcastIntent(&intent); -} - -/** - * - * rct2: 0x006C96C0 - */ -void RideConstructionRemoveGhosts() -{ - if (_currentTrackSelectionFlags.has(TrackSelectionFlag::entranceOrExit)) + /** + * Gets the origin track element (sequence 0). Seems to do more than that though and even invalidates track. + * rct2: 0x006C683D + * ax : x + * bx : direction << 8, type + * cx : y + * dx : z + * si : extra_params + * di : output_element + * bp : flags + */ + std::optional GetTrackElementOriginAndApplyChanges( + const CoordsXYZD& location, TrackElemType type, uint16_t extra_params, TileElement** output_element, + TrackElementSetFlags flags) { - RideEntranceExitRemoveGhost(); - _currentTrackSelectionFlags.unset(TrackSelectionFlag::entranceOrExit); + // Find the relevant track piece, prefer sequence 0 (this ensures correct behaviour for diagonal track pieces) + auto trackElement = MapGetTrackElementAtOfTypeSeq(location, type, 0); + if (trackElement == nullptr) + { + trackElement = MapGetTrackElementAtOfType(location, type); + if (trackElement == nullptr) + { + return std::nullopt; + } + } + + // Possibly z should be & 0xF8 + const auto& ted = GetTrackElementDescriptor(type); + + // Now find all the elements that belong to this track piece + int32_t sequence = trackElement->GetSequenceIndex(); + uint8_t mapDirection = trackElement->getDirection(); + if (sequence >= ted.sequenceData.numSequences) + return std::nullopt; + + const auto& trackBlock = ted.sequenceData.sequences[sequence].clearance; + + CoordsXY offsets = { trackBlock.x, trackBlock.y }; + CoordsXY newCoords = location; + newCoords += offsets.Rotate(DirectionReverse(mapDirection)); + + auto retCoordsXYZ = CoordsXYZ{ newCoords.x, newCoords.y, location.z - trackBlock.z }; + + int32_t start_z = retCoordsXYZ.z; + assert(ted.sequenceData.numSequences > 0); + const auto block0 = ted.sequenceData.sequences[0].clearance; + + retCoordsXYZ.z += block0.z; + for (int32_t i = 0; i < ted.sequenceData.numSequences; i++) + { + const auto& block = ted.sequenceData.sequences[i].clearance; + CoordsXY cur = { retCoordsXYZ }; + offsets = { block.x, block.y }; + cur += offsets.Rotate(mapDirection); + int32_t cur_z = start_z + block.z; + + MapInvalidateTileFull(cur); + + trackElement = MapGetTrackElementAtOfTypeSeq({ cur, cur_z, static_cast(location.direction) }, type, i); + if (trackElement == nullptr) + { + return std::nullopt; + } + if (i == 0 && output_element != nullptr) + { + *output_element = reinterpret_cast(trackElement); + } + if (flags.has(TrackElementSetFlag::highlightOff)) + { + trackElement->SetHighlight(false); + } + if (flags.has(TrackElementSetFlag::highlightOn)) + { + trackElement->SetHighlight(true); + } + if (flags.has(TrackElementSetFlag::colourScheme)) + { + auto newScheme = static_cast(extra_params & 0xFF); + trackElement->SetColourScheme(newScheme); + + if (_previousTrackPiece == retCoordsXYZ) + { + _currentColourScheme = newScheme; + } + } + if (flags.has(TrackElementSetFlag::seatRotation)) + { + trackElement->SetSeatRotation(static_cast(extra_params & 0xFF)); + } + if (flags.has(TrackElementSetFlag::cableLiftOn)) + { + trackElement->SetHasCableLift(true); + } + if (flags.has(TrackElementSetFlag::cableLiftOff)) + { + trackElement->SetHasCableLift(false); + } + if (flags.has(TrackElementSetFlag::brakeClosed)) + { + trackElement->SetBrakeClosed(extra_params != 0); + } + if (flags.has(TrackElementSetFlag::brakeBoosterSpeed)) + { + trackElement->SetBrakeBoosterSpeed(static_cast(extra_params & 0xFF)); + } + } + return retCoordsXYZ; } - if (_currentTrackSelectionFlags.has(TrackSelectionFlag::track)) + + static void WindowRideConstructionUpdateActiveElements() { - auto intent = Intent(INTENT_ACTION_REMOVE_PROVISIONAL_TRACK_PIECE); + auto intent = Intent(INTENT_ACTION_RIDE_CONSTRUCTION_UPDATE_ACTIVE_ELEMENTS); ContextBroadcastIntent(&intent); - _currentTrackSelectionFlags.unset(TrackSelectionFlag::track); } -} -/* - * rct2: 0x006C9627 - */ -void RideConstructionInvalidateCurrentTrack() -{ - switch (_rideConstructionState) + /** + * + * rct2: 0x006C96C0 + */ + void RideConstructionRemoveGhosts() { - case RideConstructionState::selected: - GetTrackElementOriginAndApplyChanges( - { _currentTrackBegin, static_cast(_currentTrackPieceDirection & 3) }, _currentTrackPieceType, 0, - nullptr, { TrackElementSetFlag::highlightOff }); - break; - case RideConstructionState::mazeBuild: - case RideConstructionState::mazeMove: - case RideConstructionState::mazeFill: - case RideConstructionState::front: - case RideConstructionState::back: - if (_currentTrackSelectionFlags.has(TrackSelectionFlag::arrow)) - { - MapInvalidateTileFull(_currentTrackBegin.ToTileStart()); - } - RideConstructionRemoveGhosts(); - break; - case RideConstructionState::place: - case RideConstructionState::entranceExit: - default: - if (_currentTrackSelectionFlags.has(TrackSelectionFlag::arrow)) - { - _currentTrackSelectionFlags.unset(TrackSelectionFlag::arrow); - gMapSelectFlags.unset(MapSelectFlag::enableArrow); - } - RideConstructionRemoveGhosts(); - break; - } -} - -/** - * - * rct2: 0x006C9B19 - */ -static void ride_construction_reset_current_piece() -{ - auto ride = GetRide(_currentRideIndex); - if (ride == nullptr) - return; - - const auto& rtd = ride->getRideTypeDescriptor(); - - if (rtd.flags.has(RtdFlag::hasTrack) || ride->numStations == 0) - { - _currentlySelectedTrack = rtd.StartTrackPiece; - _currentTrackPitchEnd = TrackPitch::none; - _currentTrackRollEnd = TrackRoll::none; - _currentTrackHasLiftHill = false; - _currentTrackAlternative.clearAll(); - if (rtd.flags.has(RtdFlag::startConstructionInverted)) + if (_currentTrackSelectionFlags.has(TrackSelectionFlag::entranceOrExit)) { - _currentTrackAlternative.set(AlternativeTrackFlag::inverted); + RideEntranceExitRemoveGhost(); + _currentTrackSelectionFlags.unset(TrackSelectionFlag::entranceOrExit); } - _previousTrackPitchEnd = TrackPitch::none; - _previousTrackRollEnd = TrackRoll::none; - } - else - { - _currentlySelectedTrack = TrackElemType::none; - _rideConstructionState = RideConstructionState::state0; - } -} - -/** - * - * rct2: 0x006C9800 - */ -void RideConstructionSetDefaultNextPiece() -{ - auto rideIndex = _currentRideIndex; - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return; - - const auto& rtd = ride->getRideTypeDescriptor(); - - int32_t z, direction; - TrackElemType trackType; - TrackBeginEnd trackBeginEnd; - CoordsXYE xyElement; - TileElement* tileElement; - _currentTrackPrice = kMoney64Undefined; - - const TrackElementDescriptor* ted; - switch (_rideConstructionState) - { - case RideConstructionState::front: + if (_currentTrackSelectionFlags.has(TrackSelectionFlag::track)) { - direction = _currentTrackPieceDirection; - if (!trackBlockGetPreviousFromZero(_currentTrackBegin, *ride, direction, &trackBeginEnd)) - { - ride_construction_reset_current_piece(); - return; - } - tileElement = trackBeginEnd.begin_element; - trackType = tileElement->asTrack()->GetTrackType(); - - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) - { - ride_construction_reset_current_piece(); - return; - } - - // Set whether track is covered - _currentTrackAlternative.unset(AlternativeTrackFlag::inverted); - if (rtd.flags.has(RtdFlag::hasInvertedVariant)) - { - if (tileElement->asTrack()->IsInverted()) - { - _currentTrackAlternative.set(AlternativeTrackFlag::inverted); - } - } - - ted = &GetTrackElementDescriptor(trackType); - auto bank = ted->definition.rollEnd; - auto slope = ted->definition.pitchEnd; - - // Set track curve - _currentlySelectedTrack = ted->curveChain.next; - - // Set track banking - if (rtd.flags.has(RtdFlag::hasInvertedVariant)) - { - if (bank == TrackRoll::upsideDown) - { - bank = TrackRoll::none; - _currentTrackAlternative.flip(AlternativeTrackFlag::inverted); - } - } - _currentTrackRollEnd = bank; - _previousTrackRollEnd = bank; - - const auto& trackElement = tileElement->asTrack(); - - // Set track slope and lift hill - _currentTrackPitchEnd = slope; - _previousTrackPitchEnd = slope; - _currentTrackHasLiftHill = trackElement->HasChain() - && ((slope != TrackPitch::down25 && slope != TrackPitch::down60) - || getGameState().cheats.enableChainLiftOnAllTrack); - - if (trackTypeHasSpeedSetting(trackElement->GetTrackType())) - _currentBrakeSpeed = trackElement->GetBrakeBoosterSpeed(); - _currentColourScheme = static_cast(trackElement->GetColourScheme()); - _currentSeatRotationAngle = trackElement->GetSeatRotation(); - - _previousTrackPiece.x = trackBeginEnd.begin_x; - _previousTrackPiece.y = trackBeginEnd.begin_y; - _previousTrackPiece.z = trackElement->getBaseZ(); - break; + auto intent = Intent(INTENT_ACTION_REMOVE_PROVISIONAL_TRACK_PIECE); + ContextBroadcastIntent(&intent); + _currentTrackSelectionFlags.unset(TrackSelectionFlag::track); } - case RideConstructionState::back: - { - direction = DirectionReverse(_currentTrackPieceDirection); - if (!trackBlockGetNextFromZero(_currentTrackBegin, *ride, direction, &xyElement, &z, &direction, false)) - { - ride_construction_reset_current_piece(); - return; - } - tileElement = xyElement.element; - trackType = tileElement->asTrack()->GetTrackType(); - - // Set whether track is covered - _currentTrackAlternative.unset(AlternativeTrackFlag::inverted); - if (rtd.flags.has(RtdFlag::hasInvertedVariant)) - { - if (tileElement->asTrack()->IsInverted()) - { - _currentTrackAlternative.set(AlternativeTrackFlag::inverted); - } - } - - ted = &GetTrackElementDescriptor(trackType); - auto bank = ted->definition.rollStart; - auto slope = ted->definition.pitchStart; - - // Set track curve - _currentlySelectedTrack = ted->curveChain.previous; - - // Set track banking - if (rtd.flags.has(RtdFlag::hasInvertedVariant)) - { - if (bank == TrackRoll::upsideDown) - { - bank = TrackRoll::none; - _currentTrackAlternative.flip(AlternativeTrackFlag::inverted); - } - } - _currentTrackRollEnd = bank; - _previousTrackRollEnd = bank; - - const auto& trackElement = tileElement->asTrack(); - - // Set track slope and lift hill - _currentTrackPitchEnd = slope; - _previousTrackPitchEnd = slope; - if (!getGameState().cheats.enableChainLiftOnAllTrack) - { - _currentTrackHasLiftHill = trackElement->HasChain(); - } - - if (trackTypeHasSpeedSetting(trackElement->GetTrackType())) - _currentBrakeSpeed = trackElement->GetBrakeBoosterSpeed(); - _currentColourScheme = static_cast(trackElement->GetColourScheme()); - _currentSeatRotationAngle = trackElement->GetSeatRotation(); - - _previousTrackPiece.x = xyElement.x; - _previousTrackPiece.y = xyElement.y; - _previousTrackPiece.z = trackElement->getBaseZ(); - break; - } - default: - break; } -} -/** - * - * rct2: 0x006C9296 - */ -void RideSelectNextSection() -{ - if (_rideConstructionState == RideConstructionState::selected) + /* + * rct2: 0x006C9627 + */ + void RideConstructionInvalidateCurrentTrack() { - RideConstructionInvalidateCurrentTrack(); - int32_t direction = _currentTrackPieceDirection; - auto type = _currentTrackPieceType; - TileElement* tileElement; - auto newCoords = GetTrackElementOriginAndApplyChanges( - { _currentTrackBegin, static_cast(direction & 3) }, type, 0, &tileElement, {}); - if (!newCoords.has_value()) + switch (_rideConstructionState) { - _rideConstructionState = RideConstructionState::state0; - WindowRideConstructionUpdateActiveElements(); + case RideConstructionState::selected: + GetTrackElementOriginAndApplyChanges( + { _currentTrackBegin, static_cast(_currentTrackPieceDirection & 3) }, _currentTrackPieceType, 0, + nullptr, { TrackElementSetFlag::highlightOff }); + break; + case RideConstructionState::mazeBuild: + case RideConstructionState::mazeMove: + case RideConstructionState::mazeFill: + case RideConstructionState::front: + case RideConstructionState::back: + if (_currentTrackSelectionFlags.has(TrackSelectionFlag::arrow)) + { + MapInvalidateTileFull(_currentTrackBegin.ToTileStart()); + } + RideConstructionRemoveGhosts(); + break; + case RideConstructionState::place: + case RideConstructionState::entranceExit: + default: + if (_currentTrackSelectionFlags.has(TrackSelectionFlag::arrow)) + { + _currentTrackSelectionFlags.unset(TrackSelectionFlag::arrow); + gMapSelectFlags.unset(MapSelectFlag::enableArrow); + } + RideConstructionRemoveGhosts(); + break; + } + } + + /** + * + * rct2: 0x006C9B19 + */ + static void ride_construction_reset_current_piece() + { + auto ride = GetRide(_currentRideIndex); + if (ride == nullptr) return; - } - CoordsXYE inputElement, outputElement; - inputElement.x = newCoords->x; - inputElement.y = newCoords->y; - inputElement.element = tileElement; - if (trackBlockGetNext(&inputElement, &outputElement, &newCoords->z, &direction)) + const auto& rtd = ride->getRideTypeDescriptor(); + + if (rtd.flags.has(RtdFlag::hasTrack) || ride->numStations == 0) { - newCoords->x = outputElement.x; - newCoords->y = outputElement.y; - tileElement = outputElement.element; - _currentTrackBegin = *newCoords; - _currentTrackPieceDirection = tileElement->getDirection(); - _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - WindowRideConstructionUpdateActiveElements(); + _currentlySelectedTrack = rtd.StartTrackPiece; + _currentTrackPitchEnd = TrackPitch::none; + _currentTrackRollEnd = TrackRoll::none; + _currentTrackHasLiftHill = false; + _currentTrackAlternative.clearAll(); + if (rtd.flags.has(RtdFlag::startConstructionInverted)) + { + _currentTrackAlternative.set(AlternativeTrackFlag::inverted); + } + _previousTrackPitchEnd = TrackPitch::none; + _previousTrackRollEnd = TrackRoll::none; } else { - _rideConstructionState = RideConstructionState::front; - _currentTrackBegin = { outputElement, newCoords->z }; - _currentTrackPieceDirection = direction; - _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - RideConstructionSetDefaultNextPiece(); - WindowRideConstructionUpdateActiveElements(); - } - } - else if (_rideConstructionState == RideConstructionState::back) - { - gMapSelectFlags.unset(MapSelectFlag::enableArrow); - - if (RideSelectForwardsFromBack()) - { - WindowRideConstructionUpdateActiveElements(); - } - } -} - -/** - * - * rct2: 0x006C93B8 - */ -void RideSelectPreviousSection() -{ - if (_rideConstructionState == RideConstructionState::selected) - { - RideConstructionInvalidateCurrentTrack(); - int32_t direction = _currentTrackPieceDirection; - auto type = _currentTrackPieceType; - TileElement* tileElement; - auto newCoords = GetTrackElementOriginAndApplyChanges( - { _currentTrackBegin, static_cast(direction & 3) }, type, 0, &tileElement, {}); - if (newCoords == std::nullopt) - { + _currentlySelectedTrack = TrackElemType::none; _rideConstructionState = RideConstructionState::state0; - WindowRideConstructionUpdateActiveElements(); - return; } + } + /** + * + * rct2: 0x006C9800 + */ + void RideConstructionSetDefaultNextPiece() + { + auto rideIndex = _currentRideIndex; + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return; + + const auto& rtd = ride->getRideTypeDescriptor(); + + int32_t z, direction; + TrackElemType trackType; TrackBeginEnd trackBeginEnd; - if (trackBlockGetPrevious({ *newCoords, tileElement }, &trackBeginEnd)) + CoordsXYE xyElement; + TileElement* tileElement; + _currentTrackPrice = kMoney64Undefined; + + const TrackElementDescriptor* ted; + switch (_rideConstructionState) { - _currentTrackBegin.x = trackBeginEnd.begin_x; - _currentTrackBegin.y = trackBeginEnd.begin_y; - _currentTrackBegin.z = trackBeginEnd.begin_z; - _currentTrackPieceDirection = trackBeginEnd.begin_direction; - _currentTrackPieceType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - WindowRideConstructionUpdateActiveElements(); - } - else - { - _rideConstructionState = RideConstructionState::back; - _currentTrackBegin.x = trackBeginEnd.end_x; - _currentTrackBegin.y = trackBeginEnd.end_y; - _currentTrackBegin.z = trackBeginEnd.begin_z; - _currentTrackPieceDirection = trackBeginEnd.end_direction; - _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - RideConstructionSetDefaultNextPiece(); - WindowRideConstructionUpdateActiveElements(); + case RideConstructionState::front: + { + direction = _currentTrackPieceDirection; + if (!trackBlockGetPreviousFromZero(_currentTrackBegin, *ride, direction, &trackBeginEnd)) + { + ride_construction_reset_current_piece(); + return; + } + tileElement = trackBeginEnd.begin_element; + trackType = tileElement->asTrack()->GetTrackType(); + + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + { + ride_construction_reset_current_piece(); + return; + } + + // Set whether track is covered + _currentTrackAlternative.unset(AlternativeTrackFlag::inverted); + if (rtd.flags.has(RtdFlag::hasInvertedVariant)) + { + if (tileElement->asTrack()->IsInverted()) + { + _currentTrackAlternative.set(AlternativeTrackFlag::inverted); + } + } + + ted = &GetTrackElementDescriptor(trackType); + auto bank = ted->definition.rollEnd; + auto slope = ted->definition.pitchEnd; + + // Set track curve + _currentlySelectedTrack = ted->curveChain.next; + + // Set track banking + if (rtd.flags.has(RtdFlag::hasInvertedVariant)) + { + if (bank == TrackRoll::upsideDown) + { + bank = TrackRoll::none; + _currentTrackAlternative.flip(AlternativeTrackFlag::inverted); + } + } + _currentTrackRollEnd = bank; + _previousTrackRollEnd = bank; + + const auto& trackElement = tileElement->asTrack(); + + // Set track slope and lift hill + _currentTrackPitchEnd = slope; + _previousTrackPitchEnd = slope; + _currentTrackHasLiftHill = trackElement->HasChain() + && ((slope != TrackPitch::down25 && slope != TrackPitch::down60) + || getGameState().cheats.enableChainLiftOnAllTrack); + + if (trackTypeHasSpeedSetting(trackElement->GetTrackType())) + _currentBrakeSpeed = trackElement->GetBrakeBoosterSpeed(); + _currentColourScheme = static_cast(trackElement->GetColourScheme()); + _currentSeatRotationAngle = trackElement->GetSeatRotation(); + + _previousTrackPiece.x = trackBeginEnd.begin_x; + _previousTrackPiece.y = trackBeginEnd.begin_y; + _previousTrackPiece.z = trackElement->getBaseZ(); + break; + } + case RideConstructionState::back: + { + direction = DirectionReverse(_currentTrackPieceDirection); + if (!trackBlockGetNextFromZero(_currentTrackBegin, *ride, direction, &xyElement, &z, &direction, false)) + { + ride_construction_reset_current_piece(); + return; + } + tileElement = xyElement.element; + trackType = tileElement->asTrack()->GetTrackType(); + + // Set whether track is covered + _currentTrackAlternative.unset(AlternativeTrackFlag::inverted); + if (rtd.flags.has(RtdFlag::hasInvertedVariant)) + { + if (tileElement->asTrack()->IsInverted()) + { + _currentTrackAlternative.set(AlternativeTrackFlag::inverted); + } + } + + ted = &GetTrackElementDescriptor(trackType); + auto bank = ted->definition.rollStart; + auto slope = ted->definition.pitchStart; + + // Set track curve + _currentlySelectedTrack = ted->curveChain.previous; + + // Set track banking + if (rtd.flags.has(RtdFlag::hasInvertedVariant)) + { + if (bank == TrackRoll::upsideDown) + { + bank = TrackRoll::none; + _currentTrackAlternative.flip(AlternativeTrackFlag::inverted); + } + } + _currentTrackRollEnd = bank; + _previousTrackRollEnd = bank; + + const auto& trackElement = tileElement->asTrack(); + + // Set track slope and lift hill + _currentTrackPitchEnd = slope; + _previousTrackPitchEnd = slope; + if (!getGameState().cheats.enableChainLiftOnAllTrack) + { + _currentTrackHasLiftHill = trackElement->HasChain(); + } + + if (trackTypeHasSpeedSetting(trackElement->GetTrackType())) + _currentBrakeSpeed = trackElement->GetBrakeBoosterSpeed(); + _currentColourScheme = static_cast(trackElement->GetColourScheme()); + _currentSeatRotationAngle = trackElement->GetSeatRotation(); + + _previousTrackPiece.x = xyElement.x; + _previousTrackPiece.y = xyElement.y; + _previousTrackPiece.z = trackElement->getBaseZ(); + break; + } + default: + break; } } - else if (_rideConstructionState == RideConstructionState::front) - { - gMapSelectFlags.unset(MapSelectFlag::enableArrow); - if (RideSelectBackwardsFromFront()) + /** + * + * rct2: 0x006C9296 + */ + void RideSelectNextSection() + { + if (_rideConstructionState == RideConstructionState::selected) { - WindowRideConstructionUpdateActiveElements(); + RideConstructionInvalidateCurrentTrack(); + int32_t direction = _currentTrackPieceDirection; + auto type = _currentTrackPieceType; + TileElement* tileElement; + auto newCoords = GetTrackElementOriginAndApplyChanges( + { _currentTrackBegin, static_cast(direction & 3) }, type, 0, &tileElement, {}); + if (!newCoords.has_value()) + { + _rideConstructionState = RideConstructionState::state0; + WindowRideConstructionUpdateActiveElements(); + return; + } + + CoordsXYE inputElement, outputElement; + inputElement.x = newCoords->x; + inputElement.y = newCoords->y; + inputElement.element = tileElement; + if (trackBlockGetNext(&inputElement, &outputElement, &newCoords->z, &direction)) + { + newCoords->x = outputElement.x; + newCoords->y = outputElement.y; + tileElement = outputElement.element; + _currentTrackBegin = *newCoords; + _currentTrackPieceDirection = tileElement->getDirection(); + _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + WindowRideConstructionUpdateActiveElements(); + } + else + { + _rideConstructionState = RideConstructionState::front; + _currentTrackBegin = { outputElement, newCoords->z }; + _currentTrackPieceDirection = direction; + _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + RideConstructionSetDefaultNextPiece(); + WindowRideConstructionUpdateActiveElements(); + } } - } -} - -/** - * - * rct2: 0x006CC2CA - */ -static bool ride_modify_entrance_or_exit(const CoordsXYE& tileElement) -{ - if (tileElement.element == nullptr) - return false; - - auto entranceElement = tileElement.element->asEntrance(); - if (entranceElement == nullptr) - return false; - - auto rideIndex = entranceElement->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) - return false; - - auto entranceType = entranceElement->GetEntranceType(); - if (entranceType != ENTRANCE_TYPE_RIDE_ENTRANCE && entranceType != ENTRANCE_TYPE_RIDE_EXIT) - return false; - - auto stationIndex = entranceElement->GetStationIndex(); - - // Get or create construction window for ride - auto* windowMgr = Ui::GetWindowManager(); - auto constructionWindow = windowMgr->FindByClass(WindowClass::rideConstruction); - if (constructionWindow == nullptr) - { - if (!RideInitialiseConstructionWindow(*ride)) - return false; - - constructionWindow = windowMgr->FindByClass(WindowClass::rideConstruction); - if (constructionWindow == nullptr) - return false; - } - - RideConstructionInvalidateCurrentTrack(); - if (_rideConstructionState != RideConstructionState::entranceExit || !isToolActive(WindowClass::rideConstruction)) - { - // Replace entrance / exit - ToolSet( - *constructionWindow, - entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE ? WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE : WC_RIDE_CONSTRUCTION__WIDX_EXIT, - Tool::crosshair); - gRideEntranceExitPlaceType = entranceType; - gRideEntranceExitPlaceRideIndex = rideIndex; - gRideEntranceExitPlaceStationIndex = stationIndex; - gInputFlags.set(InputFlag::allowRightMouseRemoval); - if (_rideConstructionState != RideConstructionState::entranceExit) + else if (_rideConstructionState == RideConstructionState::back) { - gRideEntranceExitPlacePreviousRideConstructionState = _rideConstructionState; - _rideConstructionState = RideConstructionState::entranceExit; - } - - WindowRideConstructionUpdateActiveElements(); - gMapSelectFlags.unset(MapSelectFlag::enableConstruct); - } - else - { - // Remove entrance / exit - auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( - { tileElement.x, tileElement.y }, rideIndex, stationIndex, entranceType == ENTRANCE_TYPE_RIDE_EXIT); - - rideEntranceExitRemove.SetCallback([=](const GameActions::GameAction* ga, const GameActions::Result* result) { - gRideEntranceExitPlaceType = entranceType; - windowMgr->InvalidateByClass(WindowClass::rideConstruction); - - auto newToolWidgetIndex = (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) ? WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE - : WC_RIDE_CONSTRUCTION__WIDX_EXIT; - - ToolCancel(); - ToolSet(*constructionWindow, newToolWidgetIndex, Tool::crosshair); - }); - - GameActions::Execute(&rideEntranceExitRemove, getGameState()); - } - - windowMgr->InvalidateByClass(WindowClass::rideConstruction); - return true; -} - -/** - * - * rct2: 0x006CC287 - */ -static bool ride_modify_maze(const CoordsXYE& tileElement) -{ - if (tileElement.element != nullptr) - { - auto trackElement = tileElement.element->asTrack(); - if (trackElement != nullptr) - { - _currentRideIndex = trackElement->GetRideIndex(); - _rideConstructionState = RideConstructionState::mazeBuild; - _currentTrackBegin.x = tileElement.x; - _currentTrackBegin.y = tileElement.y; - _currentTrackBegin.z = trackElement->getBaseZ(); - _currentTrackSelectionFlags.clearAll(); - _rideConstructionNextArrowPulse = 0; gMapSelectFlags.unset(MapSelectFlag::enableArrow); - auto intent = Intent(INTENT_ACTION_UPDATE_MAZE_CONSTRUCTION); - ContextBroadcastIntent(&intent); - return true; + if (RideSelectForwardsFromBack()) + { + WindowRideConstructionUpdateActiveElements(); + } } } - return false; -} -/** - * - * rct2: 0x006CC056 - */ -bool RideModify(const CoordsXYE& input) -{ - auto tileElement = input; - if (tileElement.element == nullptr) - return false; - - auto rideIndex = tileElement.element->GetRideIndex(); - auto ride = GetRide(rideIndex); - if (ride == nullptr) + /** + * + * rct2: 0x006C93B8 + */ + void RideSelectPreviousSection() { - return false; + if (_rideConstructionState == RideConstructionState::selected) + { + RideConstructionInvalidateCurrentTrack(); + int32_t direction = _currentTrackPieceDirection; + auto type = _currentTrackPieceType; + TileElement* tileElement; + auto newCoords = GetTrackElementOriginAndApplyChanges( + { _currentTrackBegin, static_cast(direction & 3) }, type, 0, &tileElement, {}); + if (newCoords == std::nullopt) + { + _rideConstructionState = RideConstructionState::state0; + WindowRideConstructionUpdateActiveElements(); + return; + } + + TrackBeginEnd trackBeginEnd; + if (trackBlockGetPrevious({ *newCoords, tileElement }, &trackBeginEnd)) + { + _currentTrackBegin.x = trackBeginEnd.begin_x; + _currentTrackBegin.y = trackBeginEnd.begin_y; + _currentTrackBegin.z = trackBeginEnd.begin_z; + _currentTrackPieceDirection = trackBeginEnd.begin_direction; + _currentTrackPieceType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + WindowRideConstructionUpdateActiveElements(); + } + else + { + _rideConstructionState = RideConstructionState::back; + _currentTrackBegin.x = trackBeginEnd.end_x; + _currentTrackBegin.y = trackBeginEnd.end_y; + _currentTrackBegin.z = trackBeginEnd.begin_z; + _currentTrackPieceDirection = trackBeginEnd.end_direction; + _currentTrackPieceType = tileElement->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + RideConstructionSetDefaultNextPiece(); + WindowRideConstructionUpdateActiveElements(); + } + } + else if (_rideConstructionState == RideConstructionState::front) + { + gMapSelectFlags.unset(MapSelectFlag::enableArrow); + + if (RideSelectBackwardsFromFront()) + { + WindowRideConstructionUpdateActiveElements(); + } + } } - auto rideEntry = ride->getRideEntry(); - if (rideEntry == nullptr || !ride_check_if_construction_allowed(*ride)) - return false; - - if (ride->flags.has(RideFlag::indestructible) && !getGameState().cheats.makeAllDestructible) + /** + * + * rct2: 0x006CC2CA + */ + static bool ride_modify_entrance_or_exit(const CoordsXYE& tileElement) { - Formatter ft; - ride->formatNameTo(ft); - ContextShowError( - STR_CANT_START_CONSTRUCTION_ON, STR_LOCAL_AUTHORITY_FORBIDS_DEMOLITION_OR_MODIFICATIONS_TO_THIS_RIDE, ft); - return false; - } + if (tileElement.element == nullptr) + return false; - // Stop the ride again to clear all vehicles and peeps (compatible with network games) - if (ride->status != RideStatus::simulating) - { - auto gameAction = GameActions::RideSetStatusAction(ride->id, RideStatus::closed); - GameActions::Execute(&gameAction, getGameState()); - } + auto entranceElement = tileElement.element->asEntrance(); + if (entranceElement == nullptr) + return false; - // Check if element is a station entrance or exit - if (tileElement.element->getType() == TileElementType::entrance) - return ride_modify_entrance_or_exit(tileElement); + auto rideIndex = entranceElement->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + return false; - if (tileElement.element->getType() != TileElementType::track) - return false; + auto entranceType = entranceElement->GetEntranceType(); + if (entranceType != ENTRANCE_TYPE_RIDE_ENTRANCE && entranceType != ENTRANCE_TYPE_RIDE_EXIT) + return false; - if (ride->getRideTypeDescriptor().flags.has(RtdFlag::cannotHaveGaps)) - { - CoordsXYE endOfTrackElement{}; - if (findTrackGap(*ride, tileElement, &endOfTrackElement)) - tileElement = endOfTrackElement; - } + auto stationIndex = entranceElement->GetStationIndex(); - const auto tileCoords = CoordsXYZ{ tileElement, tileElement.element->getBaseZ() }; - const auto direction = tileElement.element->getDirection(); - const auto type = tileElement.element->asTrack()->GetTrackType(); + // Get or create construction window for ride + auto* windowMgr = Ui::GetWindowManager(); + auto constructionWindow = windowMgr->FindByClass(WindowClass::rideConstruction); + if (constructionWindow == nullptr) + { + if (!RideInitialiseConstructionWindow(*ride)) + return false; - ride_create_or_find_construction_window(rideIndex); + constructionWindow = windowMgr->FindByClass(WindowClass::rideConstruction); + if (constructionWindow == nullptr) + return false; + } - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - { - return ride_modify_maze(tileElement); - } + RideConstructionInvalidateCurrentTrack(); + if (_rideConstructionState != RideConstructionState::entranceExit || !isToolActive(WindowClass::rideConstruction)) + { + // Replace entrance / exit + ToolSet( + *constructionWindow, + entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE ? WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE + : WC_RIDE_CONSTRUCTION__WIDX_EXIT, + Tool::crosshair); + gRideEntranceExitPlaceType = entranceType; + gRideEntranceExitPlaceRideIndex = rideIndex; + gRideEntranceExitPlaceStationIndex = stationIndex; + gInputFlags.set(InputFlag::allowRightMouseRemoval); + if (_rideConstructionState != RideConstructionState::entranceExit) + { + gRideEntranceExitPlacePreviousRideConstructionState = _rideConstructionState; + _rideConstructionState = RideConstructionState::entranceExit; + } - auto newCoords = GetTrackElementOriginAndApplyChanges({ tileCoords, direction }, type, 0, nullptr, {}); - if (!newCoords.has_value()) - return false; + WindowRideConstructionUpdateActiveElements(); + gMapSelectFlags.unset(MapSelectFlag::enableConstruct); + } + else + { + // Remove entrance / exit + auto rideEntranceExitRemove = GameActions::RideEntranceExitRemoveAction( + { tileElement.x, tileElement.y }, rideIndex, stationIndex, entranceType == ENTRANCE_TYPE_RIDE_EXIT); - _currentRideIndex = rideIndex; - _rideConstructionState = RideConstructionState::selected; - _currentTrackBegin = newCoords.value(); - _currentTrackPieceDirection = direction; - _currentTrackPieceType = type; - _currentTrackSelectionFlags.clearAll(); - _rideConstructionNextArrowPulse = 0; - gMapSelectFlags.unset(MapSelectFlag::enableArrow); + rideEntranceExitRemove.SetCallback([=](const GameActions::GameAction* ga, const GameActions::Result* result) { + gRideEntranceExitPlaceType = entranceType; + windowMgr->InvalidateByClass(WindowClass::rideConstruction); - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) - { - WindowRideConstructionUpdateActiveElements(); + auto newToolWidgetIndex = (entranceType == ENTRANCE_TYPE_RIDE_ENTRANCE) ? WC_RIDE_CONSTRUCTION__WIDX_ENTRANCE + : WC_RIDE_CONSTRUCTION__WIDX_EXIT; + + ToolCancel(); + ToolSet(*constructionWindow, newToolWidgetIndex, Tool::crosshair); + }); + + GameActions::Execute(&rideEntranceExitRemove, getGameState()); + } + + windowMgr->InvalidateByClass(WindowClass::rideConstruction); return true; } - RideSelectNextSection(); - if (_rideConstructionState == RideConstructionState::front) + /** + * + * rct2: 0x006CC287 + */ + static bool ride_modify_maze(const CoordsXYE& tileElement) { - WindowRideConstructionUpdateActiveElements(); - return true; + if (tileElement.element != nullptr) + { + auto trackElement = tileElement.element->asTrack(); + if (trackElement != nullptr) + { + _currentRideIndex = trackElement->GetRideIndex(); + _rideConstructionState = RideConstructionState::mazeBuild; + _currentTrackBegin.x = tileElement.x; + _currentTrackBegin.y = tileElement.y; + _currentTrackBegin.z = trackElement->getBaseZ(); + _currentTrackSelectionFlags.clearAll(); + _rideConstructionNextArrowPulse = 0; + gMapSelectFlags.unset(MapSelectFlag::enableArrow); + + auto intent = Intent(INTENT_ACTION_UPDATE_MAZE_CONSTRUCTION); + ContextBroadcastIntent(&intent); + return true; + } + } + return false; } - _rideConstructionState = RideConstructionState::selected; - _currentTrackBegin = *newCoords; - _currentTrackPieceDirection = direction; - _currentTrackPieceType = type; - _currentTrackSelectionFlags.clearAll(); - - RideSelectPreviousSection(); - - if (_rideConstructionState != RideConstructionState::back) + /** + * + * rct2: 0x006CC056 + */ + bool RideModify(const CoordsXYE& input) { + auto tileElement = input; + if (tileElement.element == nullptr) + return false; + + auto rideIndex = tileElement.element->GetRideIndex(); + auto ride = GetRide(rideIndex); + if (ride == nullptr) + { + return false; + } + + auto rideEntry = ride->getRideEntry(); + if (rideEntry == nullptr || !ride_check_if_construction_allowed(*ride)) + return false; + + if (ride->flags.has(RideFlag::indestructible) && !getGameState().cheats.makeAllDestructible) + { + Formatter ft; + ride->formatNameTo(ft); + ContextShowError( + STR_CANT_START_CONSTRUCTION_ON, STR_LOCAL_AUTHORITY_FORBIDS_DEMOLITION_OR_MODIFICATIONS_TO_THIS_RIDE, ft); + return false; + } + + // Stop the ride again to clear all vehicles and peeps (compatible with network games) + if (ride->status != RideStatus::simulating) + { + auto gameAction = GameActions::RideSetStatusAction(ride->id, RideStatus::closed); + GameActions::Execute(&gameAction, getGameState()); + } + + // Check if element is a station entrance or exit + if (tileElement.element->getType() == TileElementType::entrance) + return ride_modify_entrance_or_exit(tileElement); + + if (tileElement.element->getType() != TileElementType::track) + return false; + + if (ride->getRideTypeDescriptor().flags.has(RtdFlag::cannotHaveGaps)) + { + CoordsXYE endOfTrackElement{}; + if (findTrackGap(*ride, tileElement, &endOfTrackElement)) + tileElement = endOfTrackElement; + } + + const auto tileCoords = CoordsXYZ{ tileElement, tileElement.element->getBaseZ() }; + const auto direction = tileElement.element->getDirection(); + const auto type = tileElement.element->asTrack()->GetTrackType(); + + ride_create_or_find_construction_window(rideIndex); + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + { + return ride_modify_maze(tileElement); + } + + auto newCoords = GetTrackElementOriginAndApplyChanges({ tileCoords, direction }, type, 0, nullptr, {}); + if (!newCoords.has_value()) + return false; + + _currentRideIndex = rideIndex; + _rideConstructionState = RideConstructionState::selected; + _currentTrackBegin = newCoords.value(); + _currentTrackPieceDirection = direction; + _currentTrackPieceType = type; + _currentTrackSelectionFlags.clearAll(); + _rideConstructionNextArrowPulse = 0; + gMapSelectFlags.unset(MapSelectFlag::enableArrow); + + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + { + WindowRideConstructionUpdateActiveElements(); + return true; + } + + RideSelectNextSection(); + if (_rideConstructionState == RideConstructionState::front) + { + WindowRideConstructionUpdateActiveElements(); + return true; + } + _rideConstructionState = RideConstructionState::selected; _currentTrackBegin = *newCoords; _currentTrackPieceDirection = direction; _currentTrackPieceType = type; _currentTrackSelectionFlags.clearAll(); + + RideSelectPreviousSection(); + + if (_rideConstructionState != RideConstructionState::back) + { + _rideConstructionState = RideConstructionState::selected; + _currentTrackBegin = *newCoords; + _currentTrackPieceDirection = direction; + _currentTrackPieceType = type; + _currentTrackSelectionFlags.clearAll(); + } + + WindowRideConstructionUpdateActiveElements(); + return true; } - WindowRideConstructionUpdateActiveElements(); - return true; -} - -/** - * - * rct2: 0x006CC3FB - */ -int32_t RideInitialiseConstructionWindow(Ride& ride) -{ - WindowBase* w; - - ToolCancel(); - - if (!ride_check_if_construction_allowed(ride)) - return 0; - - RideClearForConstruction(ride); - ride.removePeeps(); - - w = ride_create_or_find_construction_window(ride.id); - - ToolSet(*w, WC_RIDE_CONSTRUCTION__WIDX_CONSTRUCT, Tool::crosshair); - gInputFlags.set(InputFlag::allowRightMouseRemoval); - - _currentlySelectedTrack = ride.getRideTypeDescriptor().StartTrackPiece; - _currentTrackPitchEnd = TrackPitch::none; - _currentTrackRollEnd = TrackRoll::none; - _currentTrackHasLiftHill = false; - _currentTrackAlternative.clearAll(); - - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::startConstructionInverted)) - _currentTrackAlternative.set(AlternativeTrackFlag::inverted); - - _previousTrackRollEnd = TrackRoll::none; - _previousTrackPitchEnd = TrackPitch::none; - - _currentTrackPieceDirection = 0; - _rideConstructionState = RideConstructionState::place; - _currentTrackSelectionFlags.clearAll(); - - WindowRideConstructionUpdateActiveElements(); - return 1; -} - -/** - * - * rct2: 0x006CB7FB - */ -money64 RideGetRefundPrice(const Ride& ride) -{ - CoordsXYE trackElement; - money64 cost = 0; - - if (!RideTryGetOriginElement(ride, &trackElement)) + /** + * + * rct2: 0x006CC3FB + */ + int32_t RideInitialiseConstructionWindow(Ride& ride) { - return 0; // Ride has no track to refund + WindowBase* w; + + ToolCancel(); + + if (!ride_check_if_construction_allowed(ride)) + return 0; + + RideClearForConstruction(ride); + ride.removePeeps(); + + w = ride_create_or_find_construction_window(ride.id); + + ToolSet(*w, WC_RIDE_CONSTRUCTION__WIDX_CONSTRUCT, Tool::crosshair); + gInputFlags.set(InputFlag::allowRightMouseRemoval); + + _currentlySelectedTrack = ride.getRideTypeDescriptor().StartTrackPiece; + _currentTrackPitchEnd = TrackPitch::none; + _currentTrackRollEnd = TrackRoll::none; + _currentTrackHasLiftHill = false; + _currentTrackAlternative.clearAll(); + + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::startConstructionInverted)) + _currentTrackAlternative.set(AlternativeTrackFlag::inverted); + + _previousTrackRollEnd = TrackRoll::none; + _previousTrackPitchEnd = TrackPitch::none; + + _currentTrackPieceDirection = 0; + _rideConstructionState = RideConstructionState::place; + _currentTrackSelectionFlags.clearAll(); + + WindowRideConstructionUpdateActiveElements(); + return 1; } - // Find the start in case it is not a complete circuit - RideGetStartOfTrack(&trackElement); - - uint8_t direction = trackElement.element->getDirection(); - - // Used in the following loop to know when we have - // completed all of the elements and are back at the - // start. - TileElement* initial_map = trackElement.element; - CoordsXYE slowIt = trackElement; - bool moveSlowIt = true; - - do + /** + * + * rct2: 0x006CB7FB + */ + money64 RideGetRefundPrice(const Ride& ride) { - auto trackRemoveAction = GameActions::TrackRemoveAction( - trackElement.element->asTrack()->GetTrackType(), trackElement.element->asTrack()->GetSequenceIndex(), - { trackElement.x, trackElement.y, trackElement.element->getBaseZ(), direction }); - trackRemoveAction.SetFlags(CommandFlag::allowDuringPaused); + CoordsXYE trackElement; + money64 cost = 0; - auto res = GameActions::Query(&trackRemoveAction, getGameState()); - - cost += res.cost; - - if (!trackBlockGetNext(&trackElement, &trackElement, nullptr, nullptr)) + if (!RideTryGetOriginElement(ride, &trackElement)) { - break; + return 0; // Ride has no track to refund } - moveSlowIt = !moveSlowIt; - if (moveSlowIt) - { - if (!trackBlockGetNext(&slowIt, &slowIt, nullptr, nullptr) || slowIt.element == trackElement.element) - { - break; - } - } + // Find the start in case it is not a complete circuit + RideGetStartOfTrack(&trackElement); - direction = trackElement.element->getDirection(); + uint8_t direction = trackElement.element->getDirection(); - } while (trackElement.element != initial_map); + // Used in the following loop to know when we have + // completed all of the elements and are back at the + // start. + TileElement* initial_map = trackElement.element; + CoordsXYE slowIt = trackElement; + bool moveSlowIt = true; - return cost; -} - -money64 SetOperatingSetting(RideId rideId, GameActions::RideSetSetting setting, uint8_t value) -{ - auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); - auto res = GameActions::Execute(&rideSetSetting, getGameState()); - return res.error == GameActions::Status::ok ? 0 : kMoney64Undefined; -} - -money64 SetOperatingSettingNested(RideId rideId, GameActions::RideSetSetting setting, uint8_t value, CommandFlags flags) -{ - auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); - rideSetSetting.SetFlags(flags); - - auto& gameState = getGameState(); - auto res = flags.has(CommandFlag::apply) ? GameActions::ExecuteNested(&rideSetSetting, gameState) - : GameActions::QueryNested(&rideSetSetting, gameState); - return res.error == GameActions::Status::ok ? 0 : kMoney64Undefined; -} - -/** - * - * rct2: 0x006CB945 - */ -void Ride::validateStations() -{ - const auto& rtd = getRideTypeDescriptor(); - if (rtd.specialType != RtdSpecialType::maze) - { - // find the stations of the ride to begin stepping over track elements from - for (const auto& station : stations) - { - if (station.Start.IsNull()) - continue; - - CoordsXYZ location = station.GetStart(); - uint8_t direction = kInvalidDirection; - - bool specialTrack = false; - TileElement* tileElement = nullptr; - while (true) - { - // search backwards for the previous station TrackElement (only if the first station TrackElement is found) - if (direction != kInvalidDirection) - { - location.x -= CoordsDirectionDelta[direction].x; - location.y -= CoordsDirectionDelta[direction].y; - } - tileElement = MapGetFirstElementAt(location); - if (tileElement == nullptr) - break; - - // find the target TrackElement on the tile it's supposed to appear on - bool trackFound = false; - do - { - if (tileElement->getBaseZ() != location.z) - continue; - if (tileElement->getType() != TileElementType::track) - continue; - if (tileElement->asTrack()->GetRideIndex() != id) - continue; - if (tileElement->asTrack()->GetSequenceIndex() != 0) - continue; - - const auto& ted = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); - // keep searching for a station piece (coaster station, tower ride base, shops, and flat ride base) - if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - continue; - - trackFound = true; - break; - } while (!(tileElement++)->isLastForTile()); - - if (!trackFound) - { - break; - } - // update the StationIndex, get the TrackElement's rotation - tileElement->asTrack()->SetStationIndex(getStationIndex(&station)); - direction = tileElement->getDirection(); - - // In the future this could look at the TED and see if the station has a sequence longer than 1 - // tower ride, flat ride, shop - if (getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation)) - { - // if the track has multiple sequences, stop looking for the next one. - specialTrack = true; - break; - } - } - - // if the track piece is not a tower ride, flat ride, or shop, continue to the next StationIndex - if (!specialTrack) - { - continue; - } - // update all the blocks with StationIndex - const auto& ted = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); - for (uint8_t i = 0; i < ted.sequenceData.numSequences; i++) - { - const auto& block = ted.sequenceData.sequences[i].clearance; - CoordsXYZ blockLocation = location + CoordsXYZ{ CoordsXY{ block.x, block.y }.Rotate(direction), 0 }; - - bool trackFound = false; - tileElement = MapGetFirstElementAt(blockLocation); - if (tileElement == nullptr) - break; - // find the target TrackElement on the tile it's supposed to appear on - do - { - if (blockLocation.z != tileElement->getBaseZ()) - continue; - if (tileElement->getType() != TileElementType::track) - continue; - - const auto& ted2 = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); - if (!ted2.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - continue; - - trackFound = true; - break; - } while (!(tileElement++)->isLastForTile()); - - if (!trackFound) - { - // Critical error! Stop trying to find the next sequence to set StationIndex. - break; - } - - tileElement->asTrack()->SetStationIndex(getStationIndex(&station)); - } - } - } - // determine what entrances and exits exist - sfl::static_vector locations; - for (auto& station : stations) - { - if (!station.Entrance.IsNull()) - { - locations.push_back(station.Entrance); - station.Entrance.SetNull(); - } - - if (!station.Exit.IsNull()) - { - locations.push_back(station.Exit); - station.Exit.SetNull(); - } - } - - auto locationListIter = locations.cbegin(); - for (const TileCoordsXYZD& locationCoords : locations) - { - auto locationList = ++locationListIter; - // determine if there's another ride entrance at this location later in the array - // if there is, skip it. The last ride entrance in the array at the location is not skipped - bool duplicateLocation = false; - while (locationList != locations.cend()) - { - const TileCoordsXYZD& locationCoords2 = *locationList++; - if (locationCoords.x == locationCoords2.x && locationCoords.y == locationCoords2.y - && locationCoords.z == locationCoords2.z) - { - duplicateLocation = true; - break; - } - } - - if (duplicateLocation) - { - // if it's a duplicate continue to the next ride entrance - continue; - } - // if it's not a duplicate location - CoordsXY location = locationCoords.ToCoordsXY(); - - TileElement* tileElement = MapGetFirstElementAt(location); - if (tileElement == nullptr) - continue; do { - if (tileElement->getType() != TileElementType::entrance) - continue; - if (tileElement->baseHeight != locationCoords.z) - continue; - if (tileElement->asEntrance()->GetRideIndex() != id) - continue; - // if it's a park entrance continue to the next tile element - if (tileElement->asEntrance()->GetEntranceType() > ENTRANCE_TYPE_RIDE_EXIT) - continue; + auto trackRemoveAction = GameActions::TrackRemoveAction( + trackElement.element->asTrack()->GetTrackType(), trackElement.element->asTrack()->GetSequenceIndex(), + { trackElement.x, trackElement.y, trackElement.element->getBaseZ(), direction }); + trackRemoveAction.SetFlags(CommandFlag::allowDuringPaused); - // find the station that's connected to this ride entrance - CoordsXY nextLocation = location; - nextLocation.x += CoordsDirectionDelta[tileElement->getDirection()].x; - nextLocation.y += CoordsDirectionDelta[tileElement->getDirection()].y; + auto res = GameActions::Query(&trackRemoveAction, getGameState()); - // if there's no connected station, remove the ride entrance (see below) - bool shouldRemove = true; - TileElement* trackElement = MapGetFirstElementAt(nextLocation); - if (trackElement == nullptr) + cost += res.cost; + + if (!trackBlockGetNext(&trackElement, &trackElement, nullptr, nullptr)) + { + break; + } + + moveSlowIt = !moveSlowIt; + if (moveSlowIt) + { + if (!trackBlockGetNext(&slowIt, &slowIt, nullptr, nullptr) || slowIt.element == trackElement.element) + { + break; + } + } + + direction = trackElement.element->getDirection(); + + } while (trackElement.element != initial_map); + + return cost; + } + + money64 SetOperatingSetting(RideId rideId, GameActions::RideSetSetting setting, uint8_t value) + { + auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); + auto res = GameActions::Execute(&rideSetSetting, getGameState()); + return res.error == GameActions::Status::ok ? 0 : kMoney64Undefined; + } + + money64 SetOperatingSettingNested(RideId rideId, GameActions::RideSetSetting setting, uint8_t value, CommandFlags flags) + { + auto rideSetSetting = GameActions::RideSetSettingAction(rideId, setting, value); + rideSetSetting.SetFlags(flags); + + auto& gameState = getGameState(); + auto res = flags.has(CommandFlag::apply) ? GameActions::ExecuteNested(&rideSetSetting, gameState) + : GameActions::QueryNested(&rideSetSetting, gameState); + return res.error == GameActions::Status::ok ? 0 : kMoney64Undefined; + } + + /** + * + * rct2: 0x006CB945 + */ + void Ride::validateStations() + { + const auto& rtd = getRideTypeDescriptor(); + if (rtd.specialType != RtdSpecialType::maze) + { + // find the stations of the ride to begin stepping over track elements from + for (const auto& station : stations) + { + if (station.Start.IsNull()) + continue; + + CoordsXYZ location = station.GetStart(); + uint8_t direction = kInvalidDirection; + + bool specialTrack = false; + TileElement* tileElement = nullptr; + while (true) + { + // search backwards for the previous station TrackElement (only if the first station TrackElement is found) + if (direction != kInvalidDirection) + { + location.x -= CoordsDirectionDelta[direction].x; + location.y -= CoordsDirectionDelta[direction].y; + } + tileElement = MapGetFirstElementAt(location); + if (tileElement == nullptr) + break; + + // find the target TrackElement on the tile it's supposed to appear on + bool trackFound = false; + do + { + if (tileElement->getBaseZ() != location.z) + continue; + if (tileElement->getType() != TileElementType::track) + continue; + if (tileElement->asTrack()->GetRideIndex() != id) + continue; + if (tileElement->asTrack()->GetSequenceIndex() != 0) + continue; + + const auto& ted = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); + // keep searching for a station piece (coaster station, tower ride base, shops, and flat ride base) + if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + continue; + + trackFound = true; + break; + } while (!(tileElement++)->isLastForTile()); + + if (!trackFound) + { + break; + } + // update the StationIndex, get the TrackElement's rotation + tileElement->asTrack()->SetStationIndex(getStationIndex(&station)); + direction = tileElement->getDirection(); + + // In the future this could look at the TED and see if the station has a sequence longer than 1 + // tower ride, flat ride, shop + if (getRideTypeDescriptor().flags.has(RtdFlag::hasSinglePieceStation)) + { + // if the track has multiple sequences, stop looking for the next one. + specialTrack = true; + break; + } + } + + // if the track piece is not a tower ride, flat ride, or shop, continue to the next StationIndex + if (!specialTrack) + { + continue; + } + // update all the blocks with StationIndex + const auto& ted = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); + for (uint8_t i = 0; i < ted.sequenceData.numSequences; i++) + { + const auto& block = ted.sequenceData.sequences[i].clearance; + CoordsXYZ blockLocation = location + CoordsXYZ{ CoordsXY{ block.x, block.y }.Rotate(direction), 0 }; + + bool trackFound = false; + tileElement = MapGetFirstElementAt(blockLocation); + if (tileElement == nullptr) + break; + // find the target TrackElement on the tile it's supposed to appear on + do + { + if (blockLocation.z != tileElement->getBaseZ()) + continue; + if (tileElement->getType() != TileElementType::track) + continue; + + const auto& ted2 = GetTrackElementDescriptor(tileElement->asTrack()->GetTrackType()); + if (!ted2.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + continue; + + trackFound = true; + break; + } while (!(tileElement++)->isLastForTile()); + + if (!trackFound) + { + // Critical error! Stop trying to find the next sequence to set StationIndex. + break; + } + + tileElement->asTrack()->SetStationIndex(getStationIndex(&station)); + } + } + } + // determine what entrances and exits exist + sfl::static_vector locations; + for (auto& station : stations) + { + if (!station.Entrance.IsNull()) + { + locations.push_back(station.Entrance); + station.Entrance.SetNull(); + } + + if (!station.Exit.IsNull()) + { + locations.push_back(station.Exit); + station.Exit.SetNull(); + } + } + + auto locationListIter = locations.cbegin(); + for (const TileCoordsXYZD& locationCoords : locations) + { + auto locationList = ++locationListIter; + // determine if there's another ride entrance at this location later in the array + // if there is, skip it. The last ride entrance in the array at the location is not skipped + bool duplicateLocation = false; + while (locationList != locations.cend()) + { + const TileCoordsXYZD& locationCoords2 = *locationList++; + if (locationCoords.x == locationCoords2.x && locationCoords.y == locationCoords2.y + && locationCoords.z == locationCoords2.z) + { + duplicateLocation = true; + break; + } + } + + if (duplicateLocation) + { + // if it's a duplicate continue to the next ride entrance + continue; + } + // if it's not a duplicate location + CoordsXY location = locationCoords.ToCoordsXY(); + + TileElement* tileElement = MapGetFirstElementAt(location); + if (tileElement == nullptr) continue; do { - if (trackElement->getType() != TileElementType::track) + if (tileElement->getType() != TileElementType::entrance) continue; - if (trackElement->asTrack()->GetRideIndex() != id) + if (tileElement->baseHeight != locationCoords.z) continue; - if (trackElement->baseHeight != tileElement->baseHeight) + if (tileElement->asEntrance()->GetRideIndex() != id) + continue; + // if it's a park entrance continue to the next tile element + if (tileElement->asEntrance()->GetEntranceType() > ENTRANCE_TYPE_RIDE_EXIT) continue; - auto trackType = trackElement->asTrack()->GetTrackType(); + // find the station that's connected to this ride entrance + CoordsXY nextLocation = location; + nextLocation.x += CoordsDirectionDelta[tileElement->getDirection()].x; + nextLocation.y += CoordsDirectionDelta[tileElement->getDirection()].y; - // get the StationIndex for the station - StationIndex stationId = StationIndex::FromUnderlying(0); - if (trackType != TrackElemType::maze) + // if there's no connected station, remove the ride entrance (see below) + bool shouldRemove = true; + TileElement* trackElement = MapGetFirstElementAt(nextLocation); + if (trackElement == nullptr) + continue; + do { - uint8_t trackSequence = trackElement->asTrack()->GetSequenceIndex(); - - // determine where the ride entrance is relative to the station track - Direction direction = (tileElement->getDirection() - DirectionReverse(trackElement->getDirection())) & 3; - - // if the ride entrance is not on a valid side, remove it - const auto& ted = GetTrackElementDescriptor(trackType); - auto connectionSides = ted.sequenceData.sequences[trackSequence].getEntranceConnectionSides(); - if (!(connectionSides & (1 << direction))) - { + if (trackElement->getType() != TileElementType::track) continue; + if (trackElement->asTrack()->GetRideIndex() != id) + continue; + if (trackElement->baseHeight != tileElement->baseHeight) + continue; + + auto trackType = trackElement->asTrack()->GetTrackType(); + + // get the StationIndex for the station + StationIndex stationId = StationIndex::FromUnderlying(0); + if (trackType != TrackElemType::maze) + { + uint8_t trackSequence = trackElement->asTrack()->GetSequenceIndex(); + + // determine where the ride entrance is relative to the station track + Direction direction = (tileElement->getDirection() - DirectionReverse(trackElement->getDirection())) + & 3; + + // if the ride entrance is not on a valid side, remove it + const auto& ted = GetTrackElementDescriptor(trackType); + auto connectionSides = ted.sequenceData.sequences[trackSequence].getEntranceConnectionSides(); + if (!(connectionSides & (1 << direction))) + { + continue; + } + + stationId = trackElement->asTrack()->GetStationIndex(); } - stationId = trackElement->asTrack()->GetStationIndex(); - } + auto& station = getStation(stationId); + if (tileElement->asEntrance()->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) + { + // if the location is already set for this station, big problem! + if (!station.Exit.IsNull()) + break; + // set the station's exit location to this one + CoordsXYZD loc = { location, station.GetBaseZ(), tileElement->getDirection() }; + station.Exit = TileCoordsXYZD{ loc }; + } + else + { + // if the location is already set for this station, big problem! + if (!station.Entrance.IsNull()) + break; + // set the station's entrance location to this one + CoordsXYZD loc = { location, station.GetBaseZ(), tileElement->getDirection() }; + station.Entrance = TileCoordsXYZD{ loc }; + } + // set the entrance's StationIndex as this station + tileElement->asEntrance()->SetStationIndex(stationId); + shouldRemove = false; + } while (!(trackElement++)->isLastForTile()); - auto& station = getStation(stationId); - if (tileElement->asEntrance()->GetEntranceType() == ENTRANCE_TYPE_RIDE_EXIT) + // remove the ride entrance and clean up if necessary + if (shouldRemove) { - // if the location is already set for this station, big problem! - if (!station.Exit.IsNull()) - break; - // set the station's exit location to this one - CoordsXYZD loc = { location, station.GetBaseZ(), tileElement->getDirection() }; - station.Exit = TileCoordsXYZD{ loc }; + FootpathQueueChainReset(); + MazeEntranceHedgeReplacement({ location, tileElement }); + FootpathRemoveEdgesAt(location, tileElement); + FootpathUpdateQueueChains(); + MapInvalidateTileFull(location); + TileElementRemove(tileElement); + tileElement--; } - else - { - // if the location is already set for this station, big problem! - if (!station.Entrance.IsNull()) - break; - // set the station's entrance location to this one - CoordsXYZD loc = { location, station.GetBaseZ(), tileElement->getDirection() }; - station.Entrance = TileCoordsXYZD{ loc }; - } - // set the entrance's StationIndex as this station - tileElement->asEntrance()->SetStationIndex(stationId); - shouldRemove = false; - } while (!(trackElement++)->isLastForTile()); + } while (!(tileElement++)->isLastForTile()); + } + } - // remove the ride entrance and clean up if necessary - if (shouldRemove) + bool RideSelectBackwardsFromFront() + { + auto ride = GetRide(_currentRideIndex); + if (ride != nullptr) + { + RideConstructionInvalidateCurrentTrack(); + TrackBeginEnd trackBeginEnd; + if (trackBlockGetPreviousFromZero(_currentTrackBegin, *ride, _currentTrackPieceDirection, &trackBeginEnd)) { - FootpathQueueChainReset(); - MazeEntranceHedgeReplacement({ location, tileElement }); - FootpathRemoveEdgesAt(location, tileElement); - FootpathUpdateQueueChains(); - MapInvalidateTileFull(location); - TileElementRemove(tileElement); - tileElement--; + _rideConstructionState = RideConstructionState::selected; + _currentTrackBegin.x = trackBeginEnd.begin_x; + _currentTrackBegin.y = trackBeginEnd.begin_y; + _currentTrackBegin.z = trackBeginEnd.begin_z; + _currentTrackPieceDirection = trackBeginEnd.begin_direction; + _currentTrackPieceType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + return true; } - } while (!(tileElement++)->isLastForTile()); - } -} - -bool RideSelectBackwardsFromFront() -{ - auto ride = GetRide(_currentRideIndex); - if (ride != nullptr) - { - RideConstructionInvalidateCurrentTrack(); - TrackBeginEnd trackBeginEnd; - if (trackBlockGetPreviousFromZero(_currentTrackBegin, *ride, _currentTrackPieceDirection, &trackBeginEnd)) - { - _rideConstructionState = RideConstructionState::selected; - _currentTrackBegin.x = trackBeginEnd.begin_x; - _currentTrackBegin.y = trackBeginEnd.begin_y; - _currentTrackBegin.z = trackBeginEnd.begin_z; - _currentTrackPieceDirection = trackBeginEnd.begin_direction; - _currentTrackPieceType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - return true; } + return false; } - return false; -} -bool RideSelectForwardsFromBack() -{ - auto ride = GetRide(_currentRideIndex); - if (ride != nullptr) + bool RideSelectForwardsFromBack() { - RideConstructionInvalidateCurrentTrack(); - - int32_t z = _currentTrackBegin.z; - int32_t direction = DirectionReverse(_currentTrackPieceDirection); - CoordsXYE next_track; - if (trackBlockGetNextFromZero(_currentTrackBegin, *ride, direction, &next_track, &z, &direction, false)) + auto ride = GetRide(_currentRideIndex); + if (ride != nullptr) { - _rideConstructionState = RideConstructionState::selected; - _currentTrackBegin.x = next_track.x; - _currentTrackBegin.y = next_track.y; - _currentTrackBegin.z = z; - _currentTrackPieceDirection = next_track.element->getDirection(); - _currentTrackPieceType = next_track.element->asTrack()->GetTrackType(); - _currentTrackSelectionFlags.clearAll(); - return true; - } - } - return false; -} + RideConstructionInvalidateCurrentTrack(); -/** - * - * rct2: 0x006B58EF - */ -ResultWithMessage RideAreAllPossibleEntrancesAndExitsBuilt(const Ride& ride) -{ - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + int32_t z = _currentTrackBegin.z; + int32_t direction = DirectionReverse(_currentTrackPieceDirection); + CoordsXYE next_track; + if (trackBlockGetNextFromZero(_currentTrackBegin, *ride, direction, &next_track, &z, &direction, false)) + { + _rideConstructionState = RideConstructionState::selected; + _currentTrackBegin.x = next_track.x; + _currentTrackBegin.y = next_track.y; + _currentTrackBegin.z = z; + _currentTrackPieceDirection = next_track.element->getDirection(); + _currentTrackPieceType = next_track.element->asTrack()->GetTrackType(); + _currentTrackSelectionFlags.clearAll(); + return true; + } + } + return false; + } + + /** + * + * rct2: 0x006B58EF + */ + ResultWithMessage RideAreAllPossibleEntrancesAndExitsBuilt(const Ride& ride) + { + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::isShopOrFacility)) + return { true }; + + for (auto& station : ride.getStations()) + { + if (station.Start.IsNull()) + { + continue; + } + if (station.Entrance.IsNull()) + { + return { false, STR_ENTRANCE_NOT_YET_BUILT }; + } + if (station.Exit.IsNull()) + { + return { false, STR_EXIT_NOT_YET_BUILT }; + } + } return { true }; - - for (auto& station : ride.getStations()) - { - if (station.Start.IsNull()) - { - continue; - } - if (station.Entrance.IsNull()) - { - return { false, STR_ENTRANCE_NOT_YET_BUILT }; - } - if (station.Exit.IsNull()) - { - return { false, STR_EXIT_NOT_YET_BUILT }; - } - } - return { true }; -} - -TrackDrawerDescriptor getCurrentTrackDrawerDescriptor(const RideTypeDescriptor& rtd) -{ - const bool isInverted = _currentTrackAlternative.has(AlternativeTrackFlag::inverted); - return getTrackDrawerDescriptor(rtd, isInverted); -} - -TrackDrawerEntry getCurrentTrackDrawerEntry(const RideTypeDescriptor& rtd) -{ - const bool isInverted = _currentTrackAlternative.has(AlternativeTrackFlag::inverted); - const bool isCovered = _currentTrackAlternative.has(AlternativeTrackFlag::alternativePieces); - return getTrackDrawerEntry(rtd, isInverted, isCovered); -} - -TrackElemType GetTrackTypeFromCurve( - TrackCurve curve, bool startsDiagonal, TrackPitch startSlope, TrackPitch endSlope, TrackRoll startBank, TrackRoll endBank) -{ - for (const auto& trackDescriptor : kNextSelectedPiece) - { - if (trackDescriptor.trackCurve != curve) - continue; - if (trackDescriptor.startsDiagonally != startsDiagonal) - continue; - if (trackDescriptor.slopeStart != startSlope) - continue; - if (trackDescriptor.slopeEnd != endSlope) - continue; - if (trackDescriptor.rollStart != startBank) - continue; - if (trackDescriptor.rollEnd != endBank) - continue; - - return trackDescriptor.trackElement; } - return TrackElemType::none; -} + TrackDrawerDescriptor getCurrentTrackDrawerDescriptor(const RideTypeDescriptor& rtd) + { + const bool isInverted = _currentTrackAlternative.has(AlternativeTrackFlag::inverted); + return getTrackDrawerDescriptor(rtd, isInverted); + } + + TrackDrawerEntry getCurrentTrackDrawerEntry(const RideTypeDescriptor& rtd) + { + const bool isInverted = _currentTrackAlternative.has(AlternativeTrackFlag::inverted); + const bool isCovered = _currentTrackAlternative.has(AlternativeTrackFlag::alternativePieces); + return getTrackDrawerEntry(rtd, isInverted, isCovered); + } + + TrackElemType GetTrackTypeFromCurve( + TrackCurve curve, bool startsDiagonal, TrackPitch startSlope, TrackPitch endSlope, TrackRoll startBank, + TrackRoll endBank) + { + for (const auto& trackDescriptor : kNextSelectedPiece) + { + if (trackDescriptor.trackCurve != curve) + continue; + if (trackDescriptor.startsDiagonally != startsDiagonal) + continue; + if (trackDescriptor.slopeStart != startSlope) + continue; + if (trackDescriptor.slopeEnd != endSlope) + continue; + if (trackDescriptor.rollStart != startBank) + continue; + if (trackDescriptor.rollEnd != endBank) + continue; + + return trackDescriptor.trackElement; + } + + return TrackElemType::none; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideConstruction.h b/src/openrct2/ride/RideConstruction.h index b2ea90f806..86faf64efa 100644 --- a/src/openrct2/ride/RideConstruction.h +++ b/src/openrct2/ride/RideConstruction.h @@ -17,9 +17,25 @@ #include #include +struct CoordsXYE; +struct CoordsXYZ; +struct CoordsXYZD; + +namespace OpenRCT2::GameActions +{ + enum class RideSetSetting : uint8_t; +} + +enum class RideColourScheme : uint8_t; + namespace OpenRCT2 { + struct Ride; + struct RideTypeDescriptor; + struct TrackDrawerDescriptor; + struct TrackDrawerEntry; struct TileElement; + enum class TrackElemType : uint16_t; namespace TrackMetadata @@ -29,49 +45,30 @@ namespace OpenRCT2 enum class TrackRoll : uint8_t; struct TypeOrCurve; } // namespace TrackMetadata -} // namespace OpenRCT2 -namespace OpenRCT2::GameActions -{ - enum class RideSetSetting : uint8_t; -} + enum class TrackElementSetFlag : uint8_t + { + highlightOff, + highlightOn, + colourScheme, + cableLiftOn, + cableLiftOff, + seatRotation, + brakeClosed, + brakeBoosterSpeed, + }; + using TrackElementSetFlags = FlagHolder; -struct CoordsXYE; -struct CoordsXYZ; -struct CoordsXYZD; + enum class TrackSelectionFlag : uint8_t + { + arrow, + track, + entranceOrExit, + recheck, + trackPlaceActionQueued, + }; + using TrackSelectionFlags = FlagHolder; -struct Ride; -struct RideTypeDescriptor; -struct TrackDrawerDescriptor; -struct TrackDrawerEntry; - -enum class RideColourScheme : uint8_t; - -enum class TrackElementSetFlag : uint8_t -{ - highlightOff, - highlightOn, - colourScheme, - cableLiftOn, - cableLiftOff, - seatRotation, - brakeClosed, - brakeBoosterSpeed, -}; -using TrackElementSetFlags = FlagHolder; - -enum class TrackSelectionFlag : uint8_t -{ - arrow, - track, - entranceOrExit, - recheck, - trackPlaceActionQueued, -}; -using TrackSelectionFlags = FlagHolder; - -namespace OpenRCT2 -{ enum class RideConstructionState : uint8_t { state0, @@ -98,73 +95,72 @@ namespace OpenRCT2 inverted, }; using SelectedLiftAndInverted = FlagHolder; + + extern money64 _currentTrackPrice; + + extern TrackMetadata::TypeOrCurve _currentlySelectedTrack; + extern RideConstructionState _rideConstructionState; + extern RideId _currentRideIndex; + + extern CoordsXYZ _currentTrackBegin; + + extern uint8_t _currentTrackPieceDirection; + extern TrackElemType _currentTrackPieceType; + extern TrackSelectionFlags _currentTrackSelectionFlags; + extern uint32_t _rideConstructionNextArrowPulse; + extern TrackMetadata::TrackPitch _currentTrackPitchEnd; + extern TrackMetadata::TrackRoll _currentTrackRollEnd; + extern bool _currentTrackHasLiftHill; + extern SelectedAlternative _currentTrackAlternative; + extern TrackElemType _selectedTrackType; + + extern TrackMetadata::TrackRoll _previousTrackRollEnd; + extern TrackMetadata::TrackPitch _previousTrackPitchEnd; + + extern CoordsXYZ _previousTrackPiece; + + extern uint8_t _currentBrakeSpeed; + extern RideColourScheme _currentColourScheme; + extern uint8_t _currentSeatRotationAngle; + + extern CoordsXYZD _unkF440C5; + + extern uint8_t gRideEntranceExitPlaceType; + extern RideId gRideEntranceExitPlaceRideIndex; + extern StationIndex gRideEntranceExitPlaceStationIndex; + extern RideConstructionState gRideEntranceExitPlacePreviousRideConstructionState; + extern uint8_t gRideEntranceExitPlaceDirection; + + void RideEntranceExitPlaceProvisionalGhost(); + void RideEntranceExitRemoveGhost(); + + void RideConstructionRemoveGhosts(); + + void RideConstructionInvalidateCurrentTrack(); + + void RideConstructionSetDefaultNextPiece(); + + void RideSelectNextSection(); + void RideSelectPreviousSection(); + + bool RideModify(const CoordsXYE& input); + + money64 SetOperatingSetting(RideId rideId, GameActions::RideSetSetting setting, uint8_t value); + money64 SetOperatingSettingNested( + RideId rideId, GameActions::RideSetSetting setting, uint8_t value, GameActions::CommandFlags flags); + + bool RideSelectBackwardsFromFront(); + bool RideSelectForwardsFromBack(); + + void RideConstructionStart(Ride& ride); + + TrackDrawerDescriptor getCurrentTrackDrawerDescriptor(const RideTypeDescriptor& rtd); + TrackDrawerEntry getCurrentTrackDrawerEntry(const RideTypeDescriptor& rtd); + TrackElemType GetTrackTypeFromCurve( + TrackMetadata::TrackCurve curve, bool startsDiagonal, TrackMetadata::TrackPitch startSlope, + TrackMetadata::TrackPitch endSlope, TrackMetadata::TrackRoll startBank, TrackMetadata::TrackRoll endBank); + + std::optional GetTrackElementOriginAndApplyChanges( + const CoordsXYZD& location, TrackElemType type, uint16_t extra_params, TileElement** output_element, + TrackElementSetFlags flags); } // namespace OpenRCT2 - -extern money64 _currentTrackPrice; - -extern OpenRCT2::TrackMetadata::TypeOrCurve _currentlySelectedTrack; -extern OpenRCT2::RideConstructionState _rideConstructionState; -extern RideId _currentRideIndex; - -extern CoordsXYZ _currentTrackBegin; - -extern uint8_t _currentTrackPieceDirection; -extern OpenRCT2::TrackElemType _currentTrackPieceType; -extern TrackSelectionFlags _currentTrackSelectionFlags; -extern uint32_t _rideConstructionNextArrowPulse; -extern OpenRCT2::TrackMetadata::TrackPitch _currentTrackPitchEnd; -extern OpenRCT2::TrackMetadata::TrackRoll _currentTrackRollEnd; -extern bool _currentTrackHasLiftHill; -extern OpenRCT2::SelectedAlternative _currentTrackAlternative; -extern OpenRCT2::TrackElemType _selectedTrackType; - -extern OpenRCT2::TrackMetadata::TrackRoll _previousTrackRollEnd; -extern OpenRCT2::TrackMetadata::TrackPitch _previousTrackPitchEnd; - -extern CoordsXYZ _previousTrackPiece; - -extern uint8_t _currentBrakeSpeed; -extern RideColourScheme _currentColourScheme; -extern uint8_t _currentSeatRotationAngle; - -extern CoordsXYZD _unkF440C5; - -extern uint8_t gRideEntranceExitPlaceType; -extern RideId gRideEntranceExitPlaceRideIndex; -extern StationIndex gRideEntranceExitPlaceStationIndex; -extern OpenRCT2::RideConstructionState gRideEntranceExitPlacePreviousRideConstructionState; -extern uint8_t gRideEntranceExitPlaceDirection; - -void RideEntranceExitPlaceProvisionalGhost(); -void RideEntranceExitRemoveGhost(); - -void RideConstructionRemoveGhosts(); - -void RideConstructionInvalidateCurrentTrack(); - -void RideConstructionSetDefaultNextPiece(); - -void RideSelectNextSection(); -void RideSelectPreviousSection(); - -bool RideModify(const CoordsXYE& input); - -money64 SetOperatingSetting(RideId rideId, OpenRCT2::GameActions::RideSetSetting setting, uint8_t value); -money64 SetOperatingSettingNested( - RideId rideId, OpenRCT2::GameActions::RideSetSetting setting, uint8_t value, OpenRCT2::GameActions::CommandFlags flags); - -bool RideSelectBackwardsFromFront(); -bool RideSelectForwardsFromBack(); - -void RideConstructionStart(Ride& ride); - -TrackDrawerDescriptor getCurrentTrackDrawerDescriptor(const RideTypeDescriptor& rtd); -TrackDrawerEntry getCurrentTrackDrawerEntry(const RideTypeDescriptor& rtd); -OpenRCT2::TrackElemType GetTrackTypeFromCurve( - OpenRCT2::TrackMetadata::TrackCurve curve, bool startsDiagonal, OpenRCT2::TrackMetadata::TrackPitch startSlope, - OpenRCT2::TrackMetadata::TrackPitch endSlope, OpenRCT2::TrackMetadata::TrackRoll startBank, - OpenRCT2::TrackMetadata::TrackRoll endBank); - -std::optional GetTrackElementOriginAndApplyChanges( - const CoordsXYZD& location, OpenRCT2::TrackElemType type, uint16_t extra_params, OpenRCT2::TileElement** output_element, - TrackElementSetFlags flags); diff --git a/src/openrct2/ride/RideData.cpp b/src/openrct2/ride/RideData.cpp index 6baec10bfd..a5e410cbd4 100644 --- a/src/openrct2/ride/RideData.cpp +++ b/src/openrct2/ride/RideData.cpp @@ -118,338 +118,342 @@ #include "rtd/water/SplashBoats.h" #include "rtd/water/SubmarineRide.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Entity::Yaw; +#include -// clang-format off - -const CarEntry kCableLiftVehicle = { - .TabRotationMask = 31, - .spacing = 0, - .car_mass = 0, - .tab_height = 0, - .num_seats = 0, - .spriteWidth = 0, - .spriteHeightNegative = 0, - .spriteHeightPositive = 0, - .animation = CarEntryAnimation::none, - .flags = {}, - .base_num_frames = 1, - .base_image_id = 29110, - .SpriteGroups = { - /* SpriteGroupType::slopeFlat */ { 29110, SpritePrecision::sprites32}, - /* SpriteGroupType::slopes12 */ { 29142, SpritePrecision::sprites4}, - /* SpriteGroupType::slopes25 */ { 29150, SpritePrecision::sprites32}, - /* SpriteGroupType::slopes42 */ { 29214, SpritePrecision::sprites8}, - /* SpriteGroupType::slopes60 */ { 29230, SpritePrecision::sprites32}, - /* SpriteGroupType::slopes75 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes90 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopesLoop */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopeInverted */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes8 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes16 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes50 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::flatBanked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::flatBanked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::flatBanked67 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::flatBanked90 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::inlineTwists */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes12Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes8Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes25Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes8Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes16Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes16Banked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes25Banked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes12Banked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes25Banked67 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes25Banked90 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes25InlineTwists */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes42Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes42Banked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes42Banked67 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes42Banked90 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes60Banked22 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes60Banked45 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes60Banked67 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::slopes60Banked90 */ { 0, SpritePrecision::none}, - /* SpriteGroupType::corkscrews */ { 0, SpritePrecision::none}, - /* SpriteGroupType::restraintAnimation */ { 0, SpritePrecision::none}, - /* SpriteGroupType::curvedLiftHillUp */ { 0, SpritePrecision::none}, - /* SpriteGroupType::curvedLiftHillDown */ { 0, SpritePrecision::none}, - }, - .NumCarImages = 0, - .no_seating_rows = 0, - .spinning_inertia = 0, - .spinning_friction = 255, - .friction_sound_id = Audio::SoundId::liftClassic, - .ReversedCarIndex = 0, - .soundRange = SoundRange::screamsMisc, - .double_sound_frequency = 0, - .powered_acceleration = 0, - .powered_max_speed = 0, - .PaintStyle = 0, - .effect_visual = 1, - .draw_order = 14, - .num_vertical_frames_override = 0, - .peep_loading_waypoint_segments = 0, - .AnimationSpeed = 0, - .AnimationFrames = 0, - .SteamEffect = { - .Longitudinal = 0, - .Vertical = 0, - }, - .spinningNumFrames = 0, -}; - -/* rct2: 0x009A0AA0 */ -const uint16_t kRideFilmLength[3] = { - 5000, // MOUSE_TAILS - 6000, // STORM_CHASERS - 7000, // SPACE_RAIDERS -}; - -const StringId kRideModeNames[] = { - STR_RIDE_MODE_NORMAL, - STR_RIDE_MODE_CONTINUOUS_CIRCUIT, - STR_RIDE_MODE_REVERSE_INCLINE_LAUNCHED_SHUTTLE, - STR_RIDE_MODE_POWERED_LAUNCH_PASSTHROUGH, - STR_RIDE_MODE_SHUTTLE, - STR_RIDE_MODE_BOAT_HIRE, - STR_RIDE_MODE_UPWARD_LAUNCH, - STR_RIDE_MODE_ROTATING_LIFT, - STR_RIDE_MODE_STATION_TO_STATION, - STR_RIDE_MODE_SINGLE_RIDE_PER_ADMISSION, - STR_RIDE_MODE_UNLIMITED_RIDES_PER_ADMISSION, - STR_RIDE_MODE_MAZE, - STR_RIDE_MODE_RACE, - STR_RIDE_MODE_DODGEMS, - STR_RIDE_MODE_SWING, - STR_RIDE_MODE_SHOP_STALL, - STR_RIDE_MODE_ROTATION, - STR_RIDE_MODE_FORWARD_ROTATION, - STR_RIDE_MODE_BACKWARD_ROTATION, - STR_RIDE_MODE_FILM_AVENGING_AVIATORS, - STR_RIDE_MODE_3D_FILM_MOUSE_TAILS, - STR_RIDE_MODE_SPACE_RINGS, - STR_RIDE_MODE_BEGINNERS, - STR_RIDE_MODE_LIM_POWERED_LAUNCH, - STR_RIDE_MODE_FILM_THRILL_RIDERS, - STR_RIDE_MODE_3D_FILM_STORM_CHASERS, - STR_RIDE_MODE_3D_FILM_SPACE_RAIDERS, - STR_RIDE_MODE_INTENSE, - STR_RIDE_MODE_BERSERK, - STR_RIDE_MODE_HAUNTED_HOUSE, - STR_RIDE_MODE_CIRCUS_SHOW, - STR_RIDE_MODE_DOWNWARD_LAUNCH, - STR_RIDE_MODE_CROOKED_HOUSE, - STR_RIDE_MODE_FREEFALL_DROP, - STR_RIDE_MODE_CONTINUOUS_CIRCUIT_BLOCK_SECTIONED, - STR_RIDE_MODE_POWERED_LAUNCH, - STR_RIDE_MODE_POWERED_LAUNCH_BLOCK_SECTIONED_MODE, -}; -// clang-format on - -constexpr RideTypeDescriptor kRideTypeDescriptors[RIDE_TYPE_COUNT] = { - /* RIDE_TYPE_SPIRAL_ROLLER_COASTER */ SpiralRollerCoasterRTD, - /* RIDE_TYPE_STAND_UP_ROLLER_COASTER */ StandUpRollerCoasterRTD, - /* RIDE_TYPE_SUSPENDED_SWINGING_COASTER */ SuspendedSwingingCoasterRTD, - /* RIDE_TYPE_INVERTED_ROLLER_COASTER */ InvertedRollerCoasterRTD, - /* RIDE_TYPE_JUNIOR_ROLLER_COASTER */ JuniorRollerCoasterRTD, - /* RIDE_TYPE_MINIATURE_RAILWAY */ MiniatureRailwayRTD, - /* RIDE_TYPE_MONORAIL */ MonorailRTD, - /* RIDE_TYPE_MINI_SUSPENDED_COASTER */ MiniSuspendedCoasterRTD, - /* RIDE_TYPE_BOAT_HIRE */ BoatHireRTD, - /* RIDE_TYPE_WOODEN_WILD_MOUSE */ WoodenWildMouseRTD, - /* RIDE_TYPE_STEEPLECHASE */ SteeplechaseRTD, - /* RIDE_TYPE_CAR_RIDE */ CarRideRTD, - /* RIDE_TYPE_LAUNCHED_FREEFALL */ LaunchedFreefallRTD, - /* RIDE_TYPE_BOBSLEIGH_COASTER */ BobsleighCoasterRTD, - /* RIDE_TYPE_OBSERVATION_TOWER */ ObservationTowerRTD, - /* RIDE_TYPE_LOOPING_ROLLER_COASTER */ LoopingRollerCoasterRTD, - /* RIDE_TYPE_DINGHY_SLIDE */ DinghySlideRTD, - /* RIDE_TYPE_MINE_TRAIN_COASTER */ MineTrainCoasterRTD, - /* RIDE_TYPE_CHAIRLIFT */ ChairliftRTD, - /* RIDE_TYPE_CORKSCREW_ROLLER_COASTER */ CorkscrewRollerCoasterRTD, - /* RIDE_TYPE_MAZE */ MazeRTD, - /* RIDE_TYPE_SPIRAL_SLIDE */ SpiralSlideRTD, - /* RIDE_TYPE_GO_KARTS */ GoKartsRTD, - /* RIDE_TYPE_LOG_FLUME */ LogFlumeRTD, - /* RIDE_TYPE_RIVER_RAPIDS */ RiverRapidsRTD, - /* RIDE_TYPE_DODGEMS */ DodgemsRTD, - /* RIDE_TYPE_SWINGING_SHIP */ SwingingShipRTD, - /* RIDE_TYPE_SWINGING_INVERTER_SHIP */ SwingingInverterShipRTD, - /* RIDE_TYPE_FOOD_STALL */ FoodStallRTD, - /* RIDE_TYPE_1D */ kDummyRTD, - /* RIDE_TYPE_DRINK_STALL */ DrinkStallRTD, - /* RIDE_TYPE_1F */ kDummyRTD, - /* RIDE_TYPE_SHOP */ ShopRTD, - /* RIDE_TYPE_MERRY_GO_ROUND */ MerryGoRoundRTD, - /* RIDE_TYPE_22 */ kDummyRTD, - /* RIDE_TYPE_INFORMATION_KIOSK */ InformationKioskRTD, - /* RIDE_TYPE_TOILETS */ ToiletsRTD, - /* RIDE_TYPE_FERRIS_WHEEL */ FerrisWheelRTD, - /* RIDE_TYPE_MOTION_SIMULATOR */ MotionSimulatorRTD, - /* RIDE_TYPE_3D_CINEMA */ CinemaRTD, - /* RIDE_TYPE_TOP_SPIN */ TopSpinRTD, - /* RIDE_TYPE_SPACE_RINGS */ SpaceRingsRTD, - /* RIDE_TYPE_REVERSE_FREEFALL_COASTER */ ReverseFreefallCoasterRTD, - /* RIDE_TYPE_LIFT */ LiftRTD, - /* RIDE_TYPE_VERTICAL_DROP_ROLLER_COASTER */ VerticalDropCoasterRTD, - /* RIDE_TYPE_CASH_MACHINE */ CashMachineRTD, - /* RIDE_TYPE_TWIST */ TwistRTD, - /* RIDE_TYPE_HAUNTED_HOUSE */ HauntedHouseRTD, - /* RIDE_TYPE_FIRST_AID */ FirstAidRTD, - /* RIDE_TYPE_CIRCUS */ CircusRTD, - /* RIDE_TYPE_GHOST_TRAIN */ GhostTrainRTD, - /* RIDE_TYPE_TWISTER_ROLLER_COASTER */ TwisterRollerCoasterRTD, - /* RIDE_TYPE_WOODEN_ROLLER_COASTER */ WoodenRollerCoasterRTD, - /* RIDE_TYPE_SIDE_FRICTION_ROLLER_COASTER */ SideFrictionRollerCoasterRTD, - /* RIDE_TYPE_STEEL_WILD_MOUSE */ SteelWildMouseRTD, - /* RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER */ MultiDimensionRollerCoasterRTD, - /* RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER_ALT */ MultiDimensionRollerCoasterAltRTD, - /* RIDE_TYPE_FLYING_ROLLER_COASTER */ FlyingRollerCoasterRTD, - /* RIDE_TYPE_FLYING_ROLLER_COASTER_ALT */ FlyingRollerCoasterAltRTD, - /* RIDE_TYPE_VIRGINIA_REEL */ VirginiaReelRTD, - /* RIDE_TYPE_SPLASH_BOATS */ SplashBoatsRTD, - /* RIDE_TYPE_MINI_HELICOPTERS */ MiniHelicoptersRTD, - /* RIDE_TYPE_LAY_DOWN_ROLLER_COASTER */ LayDownRollerCoasterRTD, - /* RIDE_TYPE_SUSPENDED_MONORAIL */ SuspendedMonorailRTD, - /* RIDE_TYPE_LAY_DOWN_ROLLER_COASTER_ALT */ LayDownRollerCoasterAltRTD, - /* RIDE_TYPE_REVERSER_ROLLER_COASTER */ ReverserRollerCoasterRTD, - /* RIDE_TYPE_HEARTLINE_TWISTER_COASTER */ HeartlineTwisterCoasterRTD, - /* RIDE_TYPE_MINI_GOLF */ MiniGolfRTD, - /* RIDE_TYPE_GIGA_COASTER */ GigaCoasterRTD, - /* RIDE_TYPE_ROTO_DROP */ RotoDropRTD, - /* RIDE_TYPE_FLYING_SAUCERS */ FlyingSaucersRTD, - /* RIDE_TYPE_CROOKED_HOUSE */ CrookedHouseRTD, - /* RIDE_TYPE_MONORAIL_CYCLES */ MonorailCyclesRTD, - /* RIDE_TYPE_COMPACT_INVERTED_COASTER */ CompactInvertedCoasterRTD, - /* RIDE_TYPE_WATER_COASTER */ WaterCoasterRTD, - /* RIDE_TYPE_AIR_POWERED_VERTICAL_COASTER */ AirPoweredVerticalCoasterRTD, - /* RIDE_TYPE_INVERTED_HAIRPIN_COASTER */ InvertedHairpinCoasterRTD, - /* RIDE_TYPE_MAGIC_CARPET */ MagicCarpetRTD, - /* RIDE_TYPE_SUBMARINE_RIDE */ SubmarineRideRTD, - /* RIDE_TYPE_RIVER_RAFTS */ RiverRaftsRTD, - /* RIDE_TYPE_50 */ kDummyRTD, - /* RIDE_TYPE_ENTERPRISE */ EnterpriseRTD, - /* RIDE_TYPE_52 */ kDummyRTD, - /* RIDE_TYPE_53 */ kDummyRTD, - /* RIDE_TYPE_54 */ kDummyRTD, - /* RIDE_TYPE_55 */ kDummyRTD, - /* RIDE_TYPE_INVERTED_IMPULSE_COASTER */ InvertedImpulseCoasterRTD, - /* RIDE_TYPE_MINI_ROLLER_COASTER */ MiniRollerCoasterRTD, - /* RIDE_TYPE_MINE_RIDE */ MineRideRTD, - /* RIDE_TYPE_59 */ kDummyRTD, - /* RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER */ LIMLaunchedRollerCoasterRTD, - /* RIDE_TYPE_HYPERCOASTER, */ HypercoasterRTD, - /* RIDE_TYPE_HYPER_TWISTER, */ HyperTwisterRTD, - /* RIDE_TYPE_MONSTER_TRUCKS, */ MonsterTrucksRTD, - /* RIDE_TYPE_SPINNING_WILD_MOUSE, */ SpinningWildMouseRTD, - /* RIDE_TYPE_CLASSIC_MINI_ROLLER_COASTER, */ ClassicMiniRollerCoasterRTD, - /* RIDE_TYPE_HYBRID_COASTER */ HybridCoasterRTD, - /* RIDE_TYPE_SINGLE_RAIL_ROLLER_COASTER */ SingleRailRollerCoasterRTD, - /* RIDE_TYPE_ALPINE_COASTER */ AlpineCoasterRTD, - /* RIDE_TYPE_CLASSIC_WOODEN_ROLLER_COASTER */ ClassicWoodenRollerCoasterRTD, - /* RIDE_TYPE_CLASSIC_STAND_UP_ROLLER_COASTER */ ClassicStandUpRollerCoasterRTD, - /* RIDE_TYPE_LSM_LAUNCHED_ROLLER_COASTER */ LSMLaunchedRollerCoasterRTD, - /* RIDE_TYPE_CLASSIC_WOODEN_TWISTER_ROLLER_COASTER */ ClassicWoodenTwisterRollerCoasterRTD, -}; - -bool RideTypeDescriptor::SupportsTrackGroup(const TrackGroup trackGroup) const +namespace OpenRCT2 { - return TrackPaintFunctions.Regular.SupportsTrackGroup(trackGroup); -} + using namespace OpenRCT2::Entity::Yaw; -ResearchCategory RideTypeDescriptor::GetResearchCategory() const -{ - switch (Category) + // clang-format off + + const CarEntry kCableLiftVehicle = { + .TabRotationMask = 31, + .spacing = 0, + .car_mass = 0, + .tab_height = 0, + .num_seats = 0, + .spriteWidth = 0, + .spriteHeightNegative = 0, + .spriteHeightPositive = 0, + .animation = CarEntryAnimation::none, + .flags = {}, + .base_num_frames = 1, + .base_image_id = 29110, + .SpriteGroups = { + /* SpriteGroupType::slopeFlat */ { 29110, SpritePrecision::sprites32}, + /* SpriteGroupType::slopes12 */ { 29142, SpritePrecision::sprites4}, + /* SpriteGroupType::slopes25 */ { 29150, SpritePrecision::sprites32}, + /* SpriteGroupType::slopes42 */ { 29214, SpritePrecision::sprites8}, + /* SpriteGroupType::slopes60 */ { 29230, SpritePrecision::sprites32}, + /* SpriteGroupType::slopes75 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes90 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopesLoop */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopeInverted */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes8 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes16 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes50 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::flatBanked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::flatBanked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::flatBanked67 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::flatBanked90 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::inlineTwists */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes12Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes8Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes25Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes8Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes16Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes16Banked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes25Banked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes12Banked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes25Banked67 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes25Banked90 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes25InlineTwists */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes42Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes42Banked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes42Banked67 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes42Banked90 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes60Banked22 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes60Banked45 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes60Banked67 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::slopes60Banked90 */ { 0, SpritePrecision::none}, + /* SpriteGroupType::corkscrews */ { 0, SpritePrecision::none}, + /* SpriteGroupType::restraintAnimation */ { 0, SpritePrecision::none}, + /* SpriteGroupType::curvedLiftHillUp */ { 0, SpritePrecision::none}, + /* SpriteGroupType::curvedLiftHillDown */ { 0, SpritePrecision::none}, + }, + .NumCarImages = 0, + .no_seating_rows = 0, + .spinning_inertia = 0, + .spinning_friction = 255, + .friction_sound_id = Audio::SoundId::liftClassic, + .ReversedCarIndex = 0, + .soundRange = SoundRange::screamsMisc, + .double_sound_frequency = 0, + .powered_acceleration = 0, + .powered_max_speed = 0, + .PaintStyle = 0, + .effect_visual = 1, + .draw_order = 14, + .num_vertical_frames_override = 0, + .peep_loading_waypoint_segments = 0, + .AnimationSpeed = 0, + .AnimationFrames = 0, + .SteamEffect = { + .Longitudinal = 0, + .Vertical = 0, + }, + .spinningNumFrames = 0, + }; + + /* rct2: 0x009A0AA0 */ + const uint16_t kRideFilmLength[3] = { + 5000, // MOUSE_TAILS + 6000, // STORM_CHASERS + 7000, // SPACE_RAIDERS + }; + + const StringId kRideModeNames[] = { + STR_RIDE_MODE_NORMAL, + STR_RIDE_MODE_CONTINUOUS_CIRCUIT, + STR_RIDE_MODE_REVERSE_INCLINE_LAUNCHED_SHUTTLE, + STR_RIDE_MODE_POWERED_LAUNCH_PASSTHROUGH, + STR_RIDE_MODE_SHUTTLE, + STR_RIDE_MODE_BOAT_HIRE, + STR_RIDE_MODE_UPWARD_LAUNCH, + STR_RIDE_MODE_ROTATING_LIFT, + STR_RIDE_MODE_STATION_TO_STATION, + STR_RIDE_MODE_SINGLE_RIDE_PER_ADMISSION, + STR_RIDE_MODE_UNLIMITED_RIDES_PER_ADMISSION, + STR_RIDE_MODE_MAZE, + STR_RIDE_MODE_RACE, + STR_RIDE_MODE_DODGEMS, + STR_RIDE_MODE_SWING, + STR_RIDE_MODE_SHOP_STALL, + STR_RIDE_MODE_ROTATION, + STR_RIDE_MODE_FORWARD_ROTATION, + STR_RIDE_MODE_BACKWARD_ROTATION, + STR_RIDE_MODE_FILM_AVENGING_AVIATORS, + STR_RIDE_MODE_3D_FILM_MOUSE_TAILS, + STR_RIDE_MODE_SPACE_RINGS, + STR_RIDE_MODE_BEGINNERS, + STR_RIDE_MODE_LIM_POWERED_LAUNCH, + STR_RIDE_MODE_FILM_THRILL_RIDERS, + STR_RIDE_MODE_3D_FILM_STORM_CHASERS, + STR_RIDE_MODE_3D_FILM_SPACE_RAIDERS, + STR_RIDE_MODE_INTENSE, + STR_RIDE_MODE_BERSERK, + STR_RIDE_MODE_HAUNTED_HOUSE, + STR_RIDE_MODE_CIRCUS_SHOW, + STR_RIDE_MODE_DOWNWARD_LAUNCH, + STR_RIDE_MODE_CROOKED_HOUSE, + STR_RIDE_MODE_FREEFALL_DROP, + STR_RIDE_MODE_CONTINUOUS_CIRCUIT_BLOCK_SECTIONED, + STR_RIDE_MODE_POWERED_LAUNCH, + STR_RIDE_MODE_POWERED_LAUNCH_BLOCK_SECTIONED_MODE, + }; + // clang-format on + + constexpr RideTypeDescriptor kRideTypeDescriptors[RIDE_TYPE_COUNT] = { + /* RIDE_TYPE_SPIRAL_ROLLER_COASTER */ SpiralRollerCoasterRTD, + /* RIDE_TYPE_STAND_UP_ROLLER_COASTER */ StandUpRollerCoasterRTD, + /* RIDE_TYPE_SUSPENDED_SWINGING_COASTER */ SuspendedSwingingCoasterRTD, + /* RIDE_TYPE_INVERTED_ROLLER_COASTER */ InvertedRollerCoasterRTD, + /* RIDE_TYPE_JUNIOR_ROLLER_COASTER */ JuniorRollerCoasterRTD, + /* RIDE_TYPE_MINIATURE_RAILWAY */ MiniatureRailwayRTD, + /* RIDE_TYPE_MONORAIL */ MonorailRTD, + /* RIDE_TYPE_MINI_SUSPENDED_COASTER */ MiniSuspendedCoasterRTD, + /* RIDE_TYPE_BOAT_HIRE */ BoatHireRTD, + /* RIDE_TYPE_WOODEN_WILD_MOUSE */ WoodenWildMouseRTD, + /* RIDE_TYPE_STEEPLECHASE */ SteeplechaseRTD, + /* RIDE_TYPE_CAR_RIDE */ CarRideRTD, + /* RIDE_TYPE_LAUNCHED_FREEFALL */ LaunchedFreefallRTD, + /* RIDE_TYPE_BOBSLEIGH_COASTER */ BobsleighCoasterRTD, + /* RIDE_TYPE_OBSERVATION_TOWER */ ObservationTowerRTD, + /* RIDE_TYPE_LOOPING_ROLLER_COASTER */ LoopingRollerCoasterRTD, + /* RIDE_TYPE_DINGHY_SLIDE */ DinghySlideRTD, + /* RIDE_TYPE_MINE_TRAIN_COASTER */ MineTrainCoasterRTD, + /* RIDE_TYPE_CHAIRLIFT */ ChairliftRTD, + /* RIDE_TYPE_CORKSCREW_ROLLER_COASTER */ CorkscrewRollerCoasterRTD, + /* RIDE_TYPE_MAZE */ MazeRTD, + /* RIDE_TYPE_SPIRAL_SLIDE */ SpiralSlideRTD, + /* RIDE_TYPE_GO_KARTS */ GoKartsRTD, + /* RIDE_TYPE_LOG_FLUME */ LogFlumeRTD, + /* RIDE_TYPE_RIVER_RAPIDS */ RiverRapidsRTD, + /* RIDE_TYPE_DODGEMS */ DodgemsRTD, + /* RIDE_TYPE_SWINGING_SHIP */ SwingingShipRTD, + /* RIDE_TYPE_SWINGING_INVERTER_SHIP */ SwingingInverterShipRTD, + /* RIDE_TYPE_FOOD_STALL */ FoodStallRTD, + /* RIDE_TYPE_1D */ kDummyRTD, + /* RIDE_TYPE_DRINK_STALL */ DrinkStallRTD, + /* RIDE_TYPE_1F */ kDummyRTD, + /* RIDE_TYPE_SHOP */ ShopRTD, + /* RIDE_TYPE_MERRY_GO_ROUND */ MerryGoRoundRTD, + /* RIDE_TYPE_22 */ kDummyRTD, + /* RIDE_TYPE_INFORMATION_KIOSK */ InformationKioskRTD, + /* RIDE_TYPE_TOILETS */ ToiletsRTD, + /* RIDE_TYPE_FERRIS_WHEEL */ FerrisWheelRTD, + /* RIDE_TYPE_MOTION_SIMULATOR */ MotionSimulatorRTD, + /* RIDE_TYPE_3D_CINEMA */ CinemaRTD, + /* RIDE_TYPE_TOP_SPIN */ TopSpinRTD, + /* RIDE_TYPE_SPACE_RINGS */ SpaceRingsRTD, + /* RIDE_TYPE_REVERSE_FREEFALL_COASTER */ ReverseFreefallCoasterRTD, + /* RIDE_TYPE_LIFT */ LiftRTD, + /* RIDE_TYPE_VERTICAL_DROP_ROLLER_COASTER */ VerticalDropCoasterRTD, + /* RIDE_TYPE_CASH_MACHINE */ CashMachineRTD, + /* RIDE_TYPE_TWIST */ TwistRTD, + /* RIDE_TYPE_HAUNTED_HOUSE */ HauntedHouseRTD, + /* RIDE_TYPE_FIRST_AID */ FirstAidRTD, + /* RIDE_TYPE_CIRCUS */ CircusRTD, + /* RIDE_TYPE_GHOST_TRAIN */ GhostTrainRTD, + /* RIDE_TYPE_TWISTER_ROLLER_COASTER */ TwisterRollerCoasterRTD, + /* RIDE_TYPE_WOODEN_ROLLER_COASTER */ WoodenRollerCoasterRTD, + /* RIDE_TYPE_SIDE_FRICTION_ROLLER_COASTER */ SideFrictionRollerCoasterRTD, + /* RIDE_TYPE_STEEL_WILD_MOUSE */ SteelWildMouseRTD, + /* RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER */ MultiDimensionRollerCoasterRTD, + /* RIDE_TYPE_MULTI_DIMENSION_ROLLER_COASTER_ALT */ MultiDimensionRollerCoasterAltRTD, + /* RIDE_TYPE_FLYING_ROLLER_COASTER */ FlyingRollerCoasterRTD, + /* RIDE_TYPE_FLYING_ROLLER_COASTER_ALT */ FlyingRollerCoasterAltRTD, + /* RIDE_TYPE_VIRGINIA_REEL */ VirginiaReelRTD, + /* RIDE_TYPE_SPLASH_BOATS */ SplashBoatsRTD, + /* RIDE_TYPE_MINI_HELICOPTERS */ MiniHelicoptersRTD, + /* RIDE_TYPE_LAY_DOWN_ROLLER_COASTER */ LayDownRollerCoasterRTD, + /* RIDE_TYPE_SUSPENDED_MONORAIL */ SuspendedMonorailRTD, + /* RIDE_TYPE_LAY_DOWN_ROLLER_COASTER_ALT */ LayDownRollerCoasterAltRTD, + /* RIDE_TYPE_REVERSER_ROLLER_COASTER */ ReverserRollerCoasterRTD, + /* RIDE_TYPE_HEARTLINE_TWISTER_COASTER */ HeartlineTwisterCoasterRTD, + /* RIDE_TYPE_MINI_GOLF */ MiniGolfRTD, + /* RIDE_TYPE_GIGA_COASTER */ GigaCoasterRTD, + /* RIDE_TYPE_ROTO_DROP */ RotoDropRTD, + /* RIDE_TYPE_FLYING_SAUCERS */ FlyingSaucersRTD, + /* RIDE_TYPE_CROOKED_HOUSE */ CrookedHouseRTD, + /* RIDE_TYPE_MONORAIL_CYCLES */ MonorailCyclesRTD, + /* RIDE_TYPE_COMPACT_INVERTED_COASTER */ CompactInvertedCoasterRTD, + /* RIDE_TYPE_WATER_COASTER */ WaterCoasterRTD, + /* RIDE_TYPE_AIR_POWERED_VERTICAL_COASTER */ AirPoweredVerticalCoasterRTD, + /* RIDE_TYPE_INVERTED_HAIRPIN_COASTER */ InvertedHairpinCoasterRTD, + /* RIDE_TYPE_MAGIC_CARPET */ MagicCarpetRTD, + /* RIDE_TYPE_SUBMARINE_RIDE */ SubmarineRideRTD, + /* RIDE_TYPE_RIVER_RAFTS */ RiverRaftsRTD, + /* RIDE_TYPE_50 */ kDummyRTD, + /* RIDE_TYPE_ENTERPRISE */ EnterpriseRTD, + /* RIDE_TYPE_52 */ kDummyRTD, + /* RIDE_TYPE_53 */ kDummyRTD, + /* RIDE_TYPE_54 */ kDummyRTD, + /* RIDE_TYPE_55 */ kDummyRTD, + /* RIDE_TYPE_INVERTED_IMPULSE_COASTER */ InvertedImpulseCoasterRTD, + /* RIDE_TYPE_MINI_ROLLER_COASTER */ MiniRollerCoasterRTD, + /* RIDE_TYPE_MINE_RIDE */ MineRideRTD, + /* RIDE_TYPE_59 */ kDummyRTD, + /* RIDE_TYPE_LIM_LAUNCHED_ROLLER_COASTER */ LIMLaunchedRollerCoasterRTD, + /* RIDE_TYPE_HYPERCOASTER, */ HypercoasterRTD, + /* RIDE_TYPE_HYPER_TWISTER, */ HyperTwisterRTD, + /* RIDE_TYPE_MONSTER_TRUCKS, */ MonsterTrucksRTD, + /* RIDE_TYPE_SPINNING_WILD_MOUSE, */ SpinningWildMouseRTD, + /* RIDE_TYPE_CLASSIC_MINI_ROLLER_COASTER, */ ClassicMiniRollerCoasterRTD, + /* RIDE_TYPE_HYBRID_COASTER */ HybridCoasterRTD, + /* RIDE_TYPE_SINGLE_RAIL_ROLLER_COASTER */ SingleRailRollerCoasterRTD, + /* RIDE_TYPE_ALPINE_COASTER */ AlpineCoasterRTD, + /* RIDE_TYPE_CLASSIC_WOODEN_ROLLER_COASTER */ ClassicWoodenRollerCoasterRTD, + /* RIDE_TYPE_CLASSIC_STAND_UP_ROLLER_COASTER */ ClassicStandUpRollerCoasterRTD, + /* RIDE_TYPE_LSM_LAUNCHED_ROLLER_COASTER */ LSMLaunchedRollerCoasterRTD, + /* RIDE_TYPE_CLASSIC_WOODEN_TWISTER_ROLLER_COASTER */ ClassicWoodenTwisterRollerCoasterRTD, + }; + + bool RideTypeDescriptor::SupportsTrackGroup(const TrackGroup trackGroup) const { - case RideCategory::transport: - return ResearchCategory::transport; - case RideCategory::gentle: - return ResearchCategory::gentle; - case RideCategory::rollerCoaster: - return ResearchCategory::rollercoaster; - case RideCategory::thrill: - return ResearchCategory::thrill; - case RideCategory::water: - return ResearchCategory::water; - case RideCategory::shop: - return ResearchCategory::shop; - case RideCategory::none: - break; - } - LOG_ERROR("Cannot get Research Category of invalid RideCategory"); - return ResearchCategory::transport; -} - -bool RideTypeDescriptor::SupportsRideMode(RideMode rideMode) const -{ - return RideModes & EnumToFlag(rideMode); -} - -static RideTrackGroups _enabledRideGroups = {}; -static RideTrackGroups _disabledRideGroups = {}; - -bool IsTrackEnabled(TrackGroup trackGroup) -{ - return _enabledRideGroups.get(EnumValue(trackGroup)); -} - -void UpdateEnabledRideGroups(TrackDrawerDescriptor trackDrawerDescriptor) -{ - trackDrawerDescriptor.Regular.GetAvailableTrackGroups(_enabledRideGroups); - - if (!getGameState().cheats.enableAllDrawableTrackPieces) - { - _enabledRideGroups &= ~_disabledRideGroups; - } -} - -void UpdateDisabledRideGroups(const RideTrackGroups& res) -{ - _disabledRideGroups = res; -} - -void TrackDrawerEntry::GetAvailableTrackGroups(RideTrackGroups& res) const -{ - res = enabledTrackGroups; - if (getGameState().cheats.enableAllDrawableTrackPieces) - res |= extraTrackGroups; -} - -bool TrackDrawerEntry::SupportsTrackGroup(const TrackGroup trackGroup) const -{ - return enabledTrackGroups.get(EnumValue(trackGroup)) - || (getGameState().cheats.enableAllDrawableTrackPieces && extraTrackGroups.get(EnumValue(trackGroup))); -} - -bool TrackDrawerDescriptor::HasCoveredPieces() const -{ - return Covered.enabledTrackGroups.count() > 0; -} - -TrackDrawerDescriptor getTrackDrawerDescriptor(const RideTypeDescriptor& rtd, bool isInverted) -{ - return isInverted ? rtd.InvertedTrackPaintFunctions : rtd.TrackPaintFunctions; -} - -TrackDrawerEntry getTrackDrawerEntry(const RideTypeDescriptor& rtd, bool isInverted, bool isCovered) -{ - auto descriptor = getTrackDrawerDescriptor(rtd, isInverted); - - if (isCovered) - { - return descriptor.Covered; + return TrackPaintFunctions.Regular.SupportsTrackGroup(trackGroup); } - return descriptor.Regular; -} + ResearchCategory RideTypeDescriptor::GetResearchCategory() const + { + switch (Category) + { + case RideCategory::transport: + return ResearchCategory::transport; + case RideCategory::gentle: + return ResearchCategory::gentle; + case RideCategory::rollerCoaster: + return ResearchCategory::rollercoaster; + case RideCategory::thrill: + return ResearchCategory::thrill; + case RideCategory::water: + return ResearchCategory::water; + case RideCategory::shop: + return ResearchCategory::shop; + case RideCategory::none: + break; + } + LOG_ERROR("Cannot get Research Category of invalid RideCategory"); + return ResearchCategory::transport; + } -int32_t RideTypeDescriptor::GetUnifiedBoosterSpeed(int32_t relativeSpeed) const -{ - // BoosterSpeedFactor has valid values of 1, 2, 4 representing a 1/2, 1, and 2 multiplier of legacy speed to unified - // speed. - return relativeSpeed * LegacyBoosterSettings.BoosterSpeedFactor / 2; -} + bool RideTypeDescriptor::SupportsRideMode(RideMode rideMode) const + { + return RideModes & EnumToFlag(rideMode); + } + + static RideTrackGroups _enabledRideGroups = {}; + static RideTrackGroups _disabledRideGroups = {}; + + bool IsTrackEnabled(TrackGroup trackGroup) + { + return _enabledRideGroups.get(EnumValue(trackGroup)); + } + + void UpdateEnabledRideGroups(TrackDrawerDescriptor trackDrawerDescriptor) + { + trackDrawerDescriptor.Regular.GetAvailableTrackGroups(_enabledRideGroups); + + if (!getGameState().cheats.enableAllDrawableTrackPieces) + { + _enabledRideGroups &= ~_disabledRideGroups; + } + } + + void UpdateDisabledRideGroups(const RideTrackGroups& res) + { + _disabledRideGroups = res; + } + + void TrackDrawerEntry::GetAvailableTrackGroups(RideTrackGroups& res) const + { + res = enabledTrackGroups; + if (getGameState().cheats.enableAllDrawableTrackPieces) + res |= extraTrackGroups; + } + + bool TrackDrawerEntry::SupportsTrackGroup(const TrackGroup trackGroup) const + { + return enabledTrackGroups.get(EnumValue(trackGroup)) + || (getGameState().cheats.enableAllDrawableTrackPieces && extraTrackGroups.get(EnumValue(trackGroup))); + } + + bool TrackDrawerDescriptor::HasCoveredPieces() const + { + return Covered.enabledTrackGroups.count() > 0; + } + + TrackDrawerDescriptor getTrackDrawerDescriptor(const RideTypeDescriptor& rtd, bool isInverted) + { + return isInverted ? rtd.InvertedTrackPaintFunctions : rtd.TrackPaintFunctions; + } + + TrackDrawerEntry getTrackDrawerEntry(const RideTypeDescriptor& rtd, bool isInverted, bool isCovered) + { + auto descriptor = getTrackDrawerDescriptor(rtd, isInverted); + + if (isCovered) + { + return descriptor.Covered; + } + + return descriptor.Regular; + } + + int32_t RideTypeDescriptor::GetUnifiedBoosterSpeed(int32_t relativeSpeed) const + { + // BoosterSpeedFactor has valid values of 1, 2, 4 representing a 1/2, 1, and 2 multiplier of legacy speed to unified + // speed. + return relativeSpeed * LegacyBoosterSettings.BoosterSpeedFactor / 2; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideData.h b/src/openrct2/ride/RideData.h index abbcbfb99c..edab594d5f 100644 --- a/src/openrct2/ride/RideData.h +++ b/src/openrct2/ride/RideData.h @@ -36,667 +36,672 @@ enum class ResearchCategory : uint8_t; -constexpr uint8_t kDefaultFoodStallHeight = 8 * kCoordsZStep; -constexpr uint8_t kDefaultDrinksStallHeight = 8 * kCoordsZStep; -constexpr uint8_t kDefaultShopHeight = 8 * kCoordsZStep; -constexpr uint8_t kDefaultToiletHeight = 4 * kCoordsZStep; -constexpr uint8_t kDefaultInformationKioskHeight = 6 * kCoordsZStep; -constexpr uint8_t kDefaultFirstAidHeight = 6 * kCoordsZStep; -constexpr uint8_t kDefaultCashMachineHeight = 8 * kCoordsZStep; - -constexpr TrackColourPresetList kDefaultFlatRideColourPreset = TRACK_COLOUR_PRESETS( - { OpenRCT2::Drawing::Colour::brightRed, OpenRCT2::Drawing::Colour::lightBlue, OpenRCT2::Drawing::Colour::yellow }); -constexpr TrackColourPresetList kDefaultStallColourPreset = TRACK_COLOUR_PRESETS( - { OpenRCT2::Drawing::Colour::brightRed, OpenRCT2::Drawing::Colour::brightRed, OpenRCT2::Drawing::Colour::brightRed }); - -struct RideComponentName +namespace OpenRCT2 { - StringId singular; - StringId plural; - StringId capitalised; - StringId capitalised_plural; - StringId count; - StringId count_plural; - StringId number; -}; + constexpr uint8_t kDefaultFoodStallHeight = 8 * kCoordsZStep; + constexpr uint8_t kDefaultDrinksStallHeight = 8 * kCoordsZStep; + constexpr uint8_t kDefaultShopHeight = 8 * kCoordsZStep; + constexpr uint8_t kDefaultToiletHeight = 4 * kCoordsZStep; + constexpr uint8_t kDefaultInformationKioskHeight = 6 * kCoordsZStep; + constexpr uint8_t kDefaultFirstAidHeight = 6 * kCoordsZStep; + constexpr uint8_t kDefaultCashMachineHeight = 8 * kCoordsZStep; -enum class RideComponentType -{ - train, - boat, - track, - dockingPlatform, - station, - car, - building, - structure, - ship, - cabin, - wheel, - ring, - player, - course, - count -}; + constexpr TrackColourPresetList kDefaultFlatRideColourPreset = TRACK_COLOUR_PRESETS( + { Drawing::Colour::brightRed, Drawing::Colour::lightBlue, Drawing::Colour::yellow }); + constexpr TrackColourPresetList kDefaultStallColourPreset = TRACK_COLOUR_PRESETS( + { Drawing::Colour::brightRed, Drawing::Colour::brightRed, Drawing::Colour::brightRed }); -enum class RideColourKey : uint8_t -{ - ride, - food, - drink, - shop, - infoKiosk, - firstAid, - cashMachine, - toilets -}; - -enum class TrackDesignCreateMode : uint_fast8_t -{ - standard, - maze -}; - -enum class RatingsCalculationType : uint8_t -{ - normal, - flatRide, - stall, -}; - -enum class RatingsModifierType : uint8_t -{ - noModifier, - // General Rating Bonuses - bonusLength, - bonusSynchronisation, - bonusTrainLength, - bonusMaxSpeed, - bonusAverageSpeed, - bonusDuration, - bonusGForces, - bonusTurns, - bonusDrops, - bonusSheltered, - bonusProximity, - bonusScenery, - bonusRotations, - bonusOperationOption, - bonusReversedTrains, - // Ride-specific Rating Bonuses - bonusGoKartRace, - bonusTowerRide, - bonusRotoDrop, - bonusMazeSize, - bonusBoatHireNoCircuit, - bonusSlideUnlimitedRides, - bonusMotionSimulatorMode, - bonus3DCinemaMode, - bonusTopSpinMode, - // Number of reversals BONUS for reverser coaster - bonusReversals, - // Number of hole BONUS for mini golf - bonusHoles, - // Number of cars bonus for dodgems/flying saucers - bonusNumTrains, - // Bonus for launched freefall in downward launch mode - bonusDownwardLaunch, - // Bonus with further mode-dependent logic for LF - bonusLaunchedFreefallSpecial, - // General Rating Requirements - requirementLength, - requirementDropHeight, - requirementNumDrops, - requirementMaxSpeed, - requirementNegativeGs, - requirementLateralGs, - requirementInversions, - requirementUnsheltered, - // Number of reversals REQUIREMENT for reverser coaster - requirementReversals, - // Number of hole REQUIREMENT for mini golf - requirementHoles, - // 2 Station requirement for Chairlift - requirementStations, - // Water section requirement for Water Coaster - requirementSplashdown, - penaltyLateralGs, -}; - -struct RideNameConvention -{ - RideComponentType vehicle; - RideComponentType structure; - RideComponentType station; -}; - -struct RideBuildCost -{ - money64 TrackPrice; // Cost of a single straight piece of track - money64 SupportPrice; - uint8_t PriceEstimateMultiplier; -}; - -struct RideHeights -{ - uint8_t MaxHeight; - uint8_t ClearanceHeight; - int8_t VehicleZOffset; - uint8_t PlatformHeight; -}; - -struct RideLiftData -{ - OpenRCT2::Audio::SoundId sound_id; - uint8_t minimum_speed; - uint8_t maximum_speed; -}; - -struct RideColourPreview -{ - uint32_t Track; - uint32_t Supports; -}; - -struct RideOperatingSettings -{ - uint8_t MinValue; - uint8_t MaxValue; - uint8_t OperatingSettingMultiplier = 1; // Used for the Ride window, cosmetic only. -}; - -struct RideTrackSpeedSettings -{ - int8_t BrakesMaxSpeed = 30; - int8_t BoosterMaxSpeed = 30; -}; - -struct RideBoosterSettings -{ - uint8_t PoweredLiftAcceleration = 0; - uint8_t BoosterAcceleration = 0; - uint8_t AccelerationFactor = 12; // the amount to right-shift the launch speed for powered launch from a station -}; - -struct RideLegacyBoosterSettings -// These values that must be kept for backwards compatibility. New ride types should set the acceleration values equal to -// BoosterSettings' and leave BoosterSpeedFactor at default. -{ - uint8_t PoweredLiftAcceleration = 0; // PoweredLiftAcceleration value before unified-speed update - uint8_t BoosterAcceleration = 0; // BoosterAcceleration value before unified-speed update - int8_t BoosterSpeedFactor = 2; // Multiplier representing how much to multiply booster speed by, scaled to 2x the final - // multiplier. -}; - -struct RatingsModifier -{ - RatingsModifierType type; - int32_t threshold; - int32_t excitement; - int32_t intensity; - int32_t nausea; -}; - -constexpr int8_t kDynamicRideShelterRating = -1; - -struct RideRatingsDescriptor -{ - RatingsCalculationType Type; - OpenRCT2::RideRating::Tuple BaseRatings; - uint8_t Unreliability; - // Used for rides with a set sheltered 8ths value (kDynamicRideShelterRating = normal calculation) - int8_t RideShelter; - bool RelaxRequirementsIfInversions; - RatingsModifier Modifiers[32]; -}; - -struct UpkeepCostsDescriptor -{ - /** - * Data about ride running costs. This is widely adjusted by the upkeep - * function, so values that don't make much sense here (a roller coaster having - * cheaper upkeep than a car ride) are fixed later on. - * - * Data generation script: https://gist.github.com/kevinburke/6bcf4a8fcc95faad7bac - */ - money64 BaseCost; - /** rct2: 0x0097E3AC */ - uint8_t TrackLengthMultiplier; - money64 CostPerTrackPiece; - /** rct2: 0x0097E3B4 */ - money64 CostPerTrain; - /** rct2: 0x0097E3B6 */ - money64 CostPerCar; - /** rct2: 0x0097E3B8 */ - money64 CostPerStation; -}; - -using RideTrackGroups = OpenRCT2::BitSet; -using UpdateRideApproachVehicleWaypointsFunction = void (*)(OpenRCT2::Guest&, const CoordsXY&, int16_t&); -using RideMusicUpdateFunction = void (*)(Ride&); -using PeepUpdateRideLeaveEntranceFunc = void (*)(OpenRCT2::Guest&, Ride&, CoordsXYZD&); -using StartRideMusicFunction = void (*)(const OpenRCT2::RideAudio::ViewportRideMusicInstance&); -using LightFXAddLightsMagicVehicleFunction = void (*)(const Vehicle* vehicle); -using RideLocationFunction = CoordsXY (*)(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); -using RideUpdateFunction = void (*)(Ride& ride); -using RideUpdateMeasurementsSpecialElementsFunc = void (*)(Ride& ride, OpenRCT2::TrackElemType trackType); -using MusicTrackOffsetLengthFunc = std::pair (*)(const Ride& ride); -using SpecialElementRatingAdjustmentFunc = void (*)(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); - -using UpdateRotatingFunction = void (*)(Vehicle& vehicle); -enum class RideConstructionWindowContext : uint8_t -{ - standard, - maze, -}; - -struct TrackDrawerEntry -{ - TrackStyle trackStyle = TrackStyle::null; - SupportType supportType{}; - /** rct2: 0x0097C468 (0 - 31) and 0x0097C5D4 (32 - 63) */ - RideTrackGroups enabledTrackGroups{}; - // Pieces that this ride type _can_ draw, but are disabled because their vehicles lack the relevant sprites, - // or because they are not realistic for the ride type (e.g. LIM boosters in Mini Roller Coasters). - RideTrackGroups extraTrackGroups{}; - - ImageIndex icon = kImageIndexUndefined; - StringId tooltip = kStringIdNone; - - void GetAvailableTrackGroups(RideTrackGroups& res) const; - bool SupportsTrackGroup(OpenRCT2::TrackGroup trackGroup) const; -}; - -struct TrackDrawerDescriptor -{ - TrackDrawerEntry Regular{}; - TrackDrawerEntry Covered{}; - - constexpr TrackDrawerDescriptor() + struct RideComponentName { - } + StringId singular; + StringId plural; + StringId capitalised; + StringId capitalised_plural; + StringId count; + StringId count_plural; + StringId number; + }; - constexpr TrackDrawerDescriptor(TrackDrawerEntry function) - : Regular(function) + enum class RideComponentType { - } + train, + boat, + track, + dockingPlatform, + station, + car, + building, + structure, + ship, + cabin, + wheel, + ring, + player, + course, + count + }; - constexpr TrackDrawerDescriptor(TrackDrawerEntry entryRegular, TrackDrawerEntry entryCovered) - : Regular(entryRegular) - , Covered(entryCovered) + enum class RideColourKey : uint8_t { - } + ride, + food, + drink, + shop, + infoKiosk, + firstAid, + cashMachine, + toilets + }; - bool HasCoveredPieces() const; -}; - -enum class RtdFlag : uint8_t -{ - hasTrackColourMain, - hasTrackColourAdditional, - hasTrackColourSupports, - - // Set by flat rides, tower rides and shops/stalls. - hasSinglePieceStation, - - hasLeaveWhenAnotherVehicleArrivesAtStation, - canSynchroniseWithAdjacentStations, - - // Used only by boat Hire and submarine ride - trackMustBeOnWater, - - hasGForces, - - // Used by rides that can't have gaps, like those with a vertical tower, - // such as the observation tower. - cannotHaveGaps, - - hasDataLogging, - hasDrops, - - noTestMode, - - // Set on rides with two varieties, like the u and o shapes of the dinghy slide - // and the dry and submerged track of the water coaster. - hasCoveredPieces, - - // Used only by maze, spiral slide and shops - noVehicles, - - hasLoadOptions, - hasLsmBehaviourOnFlat, - - // Set by flat rides where the vehicle is integral to the structure, like - // Merry-go-round and swinging ships. (Contrast with rides like dodgems.) - vehicleIsIntegral, - - isShopOrFacility, - - // If set, wall scenery can not share a tile with the ride's track - noWallsAroundTrack, - - isFlatRide, - - // Whether or not guests will go on the ride again if they liked it - // (this is usually applied to everything apart from transport rides). - guestsWillRideAgain, - - // Used by Toilets and First Aid to mark that guest should go - // inside the building (rather than 'buying' at the counter) - guestsShouldGoInsideFacility, - - // Guests are "IN" (ride) rather than "ON" (ride) - describeAsInside, - - sellsFood, - sellsDrinks, - - // Whether or not vehicle colours can be set - hasVehicleColours, - - checkForStalling, - hasTrack, - - // Only set by lift - allowExtraTowerBases, - - // Only set by reverser coaster - layeredVehiclePreview, - - supportsMultipleColourSchemes, - allowDoorsOnTrack, - hasMusicByDefault, - allowMusic, - - // Used by the Flying RC, Lay-down RC, Multi-dimension RC - hasInvertedVariant, - - checkGForces, - hasEntranceAndExit, - allowMoreVehiclesThanStationFits, - hasAirTime, - singleSession, - allowMultipleCircuits, - allowCableLiftHill, - showInTrackDesigner, - isTransportRide, - interestingToLookAt, - slightlyInterestingToLookAt, - - // This is only set on the Flying RC and its alternative type. - startConstructionInverted, - - listVehiclesSeparately, - supportsLevelCrossings, - isSuspended, - hasLandscapeDoors, - upInclineRequiresLift, - guestsCanUseUmbrella, - hasOneStation, - hasSeatRotation, - allowReversedTrains, - - requireExplicitListingInMusicObjects, - - hasRoofOverWholeRide, - - runningSpeedAffectsReliability, - poweredLaunchAffectsReliability, - reverseInclineLaunchAffectsReliability, - - isDummyType, -}; -using RtdFlags = FlagHolder; - -/** - * Some rides are so different from others that they need some special code. - * This replaces direct ride type checks. - * - * Note: only add to this list if behaviour cannot sufficiently be altered using flags. - */ -enum class RtdSpecialType -{ - none, - maze, - miniGolf, - spiralSlide, - toilet, - cashMachine, - firstAid, - enterprise, - motionSimulator, - spaceRings, - boatHire, -}; - -// Set on ride types that have a main colour, additional colour and support colour. -constexpr RtdFlags kRtdFlagsHasThreeColours = { RtdFlag::hasTrackColourMain, RtdFlag::hasTrackColourAdditional, - RtdFlag::hasTrackColourSupports }; -// Set on _all_ roller coaster ride types, including the _ALT types used for constructing upside down. -constexpr RtdFlags kRtdFlagsCommonCoaster = { RtdFlag::hasGForces, - RtdFlag::hasDataLogging, - RtdFlag::hasDrops, - RtdFlag::hasLoadOptions, - RtdFlag::guestsWillRideAgain, - RtdFlag::hasVehicleColours, - RtdFlag::checkForStalling, - RtdFlag::hasTrack, - RtdFlag::supportsMultipleColourSchemes, - RtdFlag::allowMusic, - RtdFlag::interestingToLookAt, - RtdFlag::canSynchroniseWithAdjacentStations }; -// Set on all roller coaster ride types, excluding the _ALT types used for constructing upside down. -constexpr RtdFlags kRtdFlagsCommonCoasterNonAlt = { RtdFlag::showInTrackDesigner, RtdFlag::hasAirTime, - RtdFlag::hasEntranceAndExit }; - -struct RideTypeDescriptor -{ - RideCategory Category{}; - /** rct2: 0x0097CC68 */ - OpenRCT2::TrackElemType StartTrackPiece{}; - TrackDrawerDescriptor TrackPaintFunctions{}; - TrackDrawerDescriptor InvertedTrackPaintFunctions{}; - RtdFlags flags{}; - /** rct2: 0x0097C8AC */ - uint64_t RideModes{}; - RideMode DefaultMode{}; - /** rct2: 0x0097CF40 */ - RideOperatingSettings OperatingSettings{}; - RideTrackSpeedSettings TrackSpeedSettings{}; - RideBoosterSettings BoosterSettings{}; - RideLegacyBoosterSettings LegacyBoosterSettings{}; - RideNaming Naming{}; - RideNameConvention NameConvention{}; - FlagHolder availableBreakdowns{}; - /** rct2: 0x0097D218 */ - RideHeights Heights{}; - uint8_t MaxMass{}; - /** rct2: 0x0097D7C8, 0x0097D7C9, 0x0097D7CA */ - RideLiftData LiftData{}; - // rct2: 0x0097CD1E - OpenRCT2::RideRating::Tuple RatingsMultipliers{}; - UpkeepCostsDescriptor UpkeepCosts{}; - // rct2: 0x0097DD78 - RideBuildCost BuildCosts{}; - money64 DefaultPrices[OpenRCT2::RCT2::ObjectLimits::kMaxShopItemsPerRideEntry]{}; - std::string_view DefaultMusic{}; - /** rct2: 0x0097D7CB */ - ShopItemIndex PhotoItem{}; - /** rct2: 0x0097D21E */ - uint8_t BonusValue{}; - TrackColourPresetList ColourPresets{}; - RideColourPreview ColourPreview{}; - RideColourKey ColourKey{}; - - // json name lookup - std::string_view Name{}; - - RideRatingsDescriptor RatingsData{}; - - UpdateRotatingFunction UpdateRotating = UpdateRotatingDefault; - - LightFXAddLightsMagicVehicleFunction LightFXAddLightsMagicVehicle = nullptr; - StartRideMusicFunction StartRideMusic = OpenRCT2::RideAudio::DefaultStartRideMusicChannel; - - TrackDesignCreateMode DesignCreateMode = TrackDesignCreateMode::standard; - - RideMusicUpdateFunction MusicUpdateFunction = DefaultMusicUpdate; - RideClassification Classification = RideClassification::ride; - - PeepUpdateRideLeaveEntranceFunc UpdateLeaveEntrance = OpenRCT2::PeepUpdateRideLeaveEntranceDefault; - SpecialElementRatingAdjustmentFunc SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default; - - RideLocationFunction GetGuestWaypointLocation = OpenRCT2::GetGuestWaypointLocationDefault; - - RideConstructionWindowContext ConstructionWindowContext = RideConstructionWindowContext::standard; - RideUpdateFunction RideUpdate = nullptr; - - RideUpdateMeasurementsSpecialElementsFunc UpdateMeasurementsSpecialElements = RideUpdateMeasurementsSpecialElements_Default; - - MusicTrackOffsetLengthFunc MusicTrackOffsetLength = OpenRCT2::RideAudio::RideMusicGetTrackOffsetLength_Default; - - UpdateRideApproachVehicleWaypointsFunction UpdateRideApproachVehicleWaypoints = OpenRCT2:: - updateRideApproachVehicleWaypointsDefault; - RtdSpecialType specialType = RtdSpecialType::none; - - /** @deprecated */ - bool SupportsTrackGroup(OpenRCT2::TrackGroup trackGroup) const; - ResearchCategory GetResearchCategory() const; - bool SupportsRideMode(RideMode rideMode) const; - /** - * Converts booster speed from the ride type's speed regime (Junior, Default, Giga) to to the unified values used by the - * vehicle. See https://github.com/OpenRCT2/OpenRCT2/discussions/23119 for more information about unified speed. - */ - int32_t GetUnifiedBoosterSpeed(int32_t relativeSpeed) const; -}; - -extern const RideTypeDescriptor kRideTypeDescriptors[RIDE_TYPE_COUNT]; - -// clang-format off -constexpr RideComponentName kRideComponentNames[] = -{ - { STR_RIDE_COMPONENT_TRAIN, STR_RIDE_COMPONENT_TRAIN_PLURAL, STR_RIDE_COMPONENT_TRAIN_CAPITALISED, STR_RIDE_COMPONENT_TRAIN_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_TRAIN_COUNT, STR_RIDE_COMPONENT_TRAIN_COUNT_PLURAL, STR_RIDE_COMPONENT_TRAIN_NO }, - { STR_RIDE_COMPONENT_BOAT, STR_RIDE_COMPONENT_BOAT_PLURAL, STR_RIDE_COMPONENT_BOAT_CAPITALISED, STR_RIDE_COMPONENT_BOAT_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_BOAT_COUNT, STR_RIDE_COMPONENT_BOAT_COUNT_PLURAL, STR_RIDE_COMPONENT_BOAT_NO }, - { STR_RIDE_COMPONENT_TRACK, STR_RIDE_COMPONENT_TRACK_PLURAL, STR_RIDE_COMPONENT_TRACK_CAPITALISED, STR_RIDE_COMPONENT_TRACK_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_TRACK_COUNT, STR_RIDE_COMPONENT_TRACK_COUNT_PLURAL, STR_RIDE_COMPONENT_TRACK_NO }, - { STR_RIDE_COMPONENT_DOCKING_PLATFORM, STR_RIDE_COMPONENT_DOCKING_PLATFORM_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_CAPITALISED, STR_RIDE_COMPONENT_DOCKING_PLATFORM_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_COUNT, STR_RIDE_COMPONENT_DOCKING_PLATFORM_COUNT_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_NO }, - { STR_RIDE_COMPONENT_STATION, STR_RIDE_COMPONENT_STATION_PLURAL, STR_RIDE_COMPONENT_STATION_CAPITALISED, STR_RIDE_COMPONENT_STATION_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_STATION_COUNT, STR_RIDE_COMPONENT_STATION_COUNT_PLURAL, STR_RIDE_COMPONENT_STATION_NO }, - { STR_RIDE_COMPONENT_CAR, STR_RIDE_COMPONENT_CAR_PLURAL, STR_RIDE_COMPONENT_CAR_CAPITALISED, STR_RIDE_COMPONENT_CAR_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_CAR_COUNT, STR_RIDE_COMPONENT_CAR_COUNT_PLURAL, STR_RIDE_COMPONENT_CAR_NO }, - { STR_RIDE_COMPONENT_BUILDING, STR_RIDE_COMPONENT_BUILDING_PLURAL, STR_RIDE_COMPONENT_BUILDING_CAPITALISED, STR_RIDE_COMPONENT_BUILDING_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_BUILDING_COUNT, STR_RIDE_COMPONENT_BUILDING_COUNT_PLURAL, STR_RIDE_COMPONENT_BUILDING_NO }, - { STR_RIDE_COMPONENT_STRUCTURE, STR_RIDE_COMPONENT_STRUCTURE_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_CAPITALISED, STR_RIDE_COMPONENT_STRUCTURE_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_COUNT, STR_RIDE_COMPONENT_STRUCTURE_COUNT_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_NO }, - { STR_RIDE_COMPONENT_SHIP, STR_RIDE_COMPONENT_SHIP_PLURAL, STR_RIDE_COMPONENT_SHIP_CAPITALISED, STR_RIDE_COMPONENT_SHIP_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_SHIP_COUNT, STR_RIDE_COMPONENT_SHIP_COUNT_PLURAL, STR_RIDE_COMPONENT_SHIP_NO }, - { STR_RIDE_COMPONENT_CABIN, STR_RIDE_COMPONENT_CABIN_PLURAL, STR_RIDE_COMPONENT_CABIN_CAPITALISED, STR_RIDE_COMPONENT_CABIN_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_CABIN_COUNT, STR_RIDE_COMPONENT_CABIN_COUNT_PLURAL, STR_RIDE_COMPONENT_CABIN_NO }, - { STR_RIDE_COMPONENT_WHEEL, STR_RIDE_COMPONENT_WHEEL_PLURAL, STR_RIDE_COMPONENT_WHEEL_CAPITALISED, STR_RIDE_COMPONENT_WHEEL_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_WHEEL_COUNT, STR_RIDE_COMPONENT_WHEEL_COUNT_PLURAL, STR_RIDE_COMPONENT_WHEEL_NO }, - { STR_RIDE_COMPONENT_RING, STR_RIDE_COMPONENT_RING_PLURAL, STR_RIDE_COMPONENT_RING_CAPITALISED, STR_RIDE_COMPONENT_RING_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_RING_COUNT, STR_RIDE_COMPONENT_RING_COUNT_PLURAL, STR_RIDE_COMPONENT_RING_NO }, - { STR_RIDE_COMPONENT_PLAYER, STR_RIDE_COMPONENT_PLAYER_PLURAL, STR_RIDE_COMPONENT_PLAYER_CAPITALISED, STR_RIDE_COMPONENT_PLAYER_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_PLAYER_COUNT, STR_RIDE_COMPONENT_PLAYER_COUNT_PLURAL, STR_RIDE_COMPONENT_PLAYER_NO }, - { STR_RIDE_COMPONENT_COURSE, STR_RIDE_COMPONENT_COURSE_PLURAL, STR_RIDE_COMPONENT_COURSE_CAPITALISED, STR_RIDE_COMPONENT_COURSE_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_COURSE_COUNT, STR_RIDE_COMPONENT_COURSE_COUNT_PLURAL, STR_RIDE_COMPONENT_COURSE_NO }, -}; -// clang-format on - -constexpr std::string_view kMusicObjectDodgems = "rct2.music.dodgems"; -constexpr std::string_view kMusicObjectEgyptian = "rct2.music.egyptian"; -constexpr std::string_view kMusicObjectFairground = "rct2.music.fairground"; -constexpr std::string_view kMusicObjectGentle = "rct2.music.gentle"; -constexpr std::string_view kMusicObjectHorror = "rct2.music.horror"; -constexpr std::string_view kMusicObjectPirate = "rct2.music.pirate"; -constexpr std::string_view kMusicObjectRock1 = "rct2.music.rock1"; -constexpr std::string_view kMusicObjectRock2 = "rct2.music.rock2"; -constexpr std::string_view kMusicObjectRock3 = "rct2.music.rock3"; -constexpr std::string_view kMusicObjectSummer = "rct2.music.summer"; -constexpr std::string_view kMusicObjectTechno = "rct2.music.techno"; -constexpr std::string_view kMusicObjectWater = "rct2.music.water"; -constexpr std::string_view kMusicObjectWildWest = "rct2.music.wildwest"; -constexpr std::string_view kMusicObjectModern = "rct2.music.modern"; - -constexpr const RideComponentName& GetRideComponentName(const RideComponentType type) -{ - return kRideComponentNames[EnumValue(type)]; -} - -constexpr uint64_t kAllRideModesAvailable = EnumsToFlags( - RideMode::continuousCircuit, RideMode::continuousCircuitBlockSectioned, RideMode::reverseInclineLaunchedShuttle, - RideMode::poweredLaunchPassthrough, RideMode::shuttle, RideMode::normal, RideMode::boatHire, RideMode::upwardLaunch, - RideMode::rotatingLift, RideMode::stationToStation, RideMode::singleRidePerAdmission, RideMode::unlimitedRidesPerAdmission, - RideMode::maze, RideMode::race, RideMode::dodgems, RideMode::swing, RideMode::shopStall, RideMode::rotation, - RideMode::forwardRotation, RideMode::backwardRotation, RideMode::filmAvengingAviators, RideMode::mouseTails3DFilm, - RideMode::spaceRings, RideMode::beginners, RideMode::limPoweredLaunch, RideMode::filmThrillRiders, - RideMode::stormChasers3DFilm, RideMode::spaceRaiders3DFilm, RideMode::intense, RideMode::berserk, RideMode::hauntedHouse, - RideMode::circus, RideMode::downwardLaunch, RideMode::crookedHouse, RideMode::freefallDrop, RideMode::poweredLaunch, - RideMode::poweredLaunchBlockSectioned); - -extern const CarEntry kCableLiftVehicle; - -extern const uint16_t kRideFilmLength[3]; - -extern const StringId kRideModeNames[EnumValue(RideMode::count)]; - -// clang-format off -constexpr RideTypeDescriptor kDummyRTD = -{ - .Category = RideCategory::none, - .StartTrackPiece = OpenRCT2::TrackElemType::endStation, - .TrackPaintFunctions = {}, - .InvertedTrackPaintFunctions = {}, - .flags = { RtdFlag::isDummyType }, - .RideModes = EnumsToFlags(RideMode::continuousCircuit), - .DefaultMode = RideMode::continuousCircuit, - .OperatingSettings = {}, - .TrackSpeedSettings = {}, - .BoosterSettings = {}, - .LegacyBoosterSettings = {}, - .Naming = { STR_UNKNOWN_RIDE, STR_RIDE_DESCRIPTION_UNKNOWN }, - .NameConvention = { RideComponentType::train, RideComponentType::track, RideComponentType::station }, - .availableBreakdowns = {}, - .Heights = { 12, 64, 0, 0, }, - .MaxMass = 255, - .LiftData = { OpenRCT2::Audio::SoundId::null, 5, 5 }, - .RatingsMultipliers = { 0, 0, 0 }, - .UpkeepCosts = { 50, 1, 0, 0, 0, 0 }, - .BuildCosts = { 0.00_GBP, 0.00_GBP, 1 }, - .DefaultPrices = { 20, 20 }, - .DefaultMusic = kMusicObjectGentle, - .PhotoItem = ShopItem::photo, - .BonusValue = 0, - .ColourPresets = kDefaultFlatRideColourPreset, - .ColourPreview = { kImageIndexUndefined, kImageIndexUndefined }, - .ColourKey = RideColourKey::ride, - .Name = "invalid", - .RatingsData = + enum class TrackDesignCreateMode : uint_fast8_t { - RatingsCalculationType::flatRide, - { OpenRCT2::RideRating::make(1, 00), OpenRCT2::RideRating::make(1, 00), OpenRCT2::RideRating::make(1, 00) }, - 1, - -1, - false, + standard, + maze + }; + + enum class RatingsCalculationType : uint8_t + { + normal, + flatRide, + stall, + }; + + enum class RatingsModifierType : uint8_t + { + noModifier, + // General Rating Bonuses + bonusLength, + bonusSynchronisation, + bonusTrainLength, + bonusMaxSpeed, + bonusAverageSpeed, + bonusDuration, + bonusGForces, + bonusTurns, + bonusDrops, + bonusSheltered, + bonusProximity, + bonusScenery, + bonusRotations, + bonusOperationOption, + bonusReversedTrains, + // Ride-specific Rating Bonuses + bonusGoKartRace, + bonusTowerRide, + bonusRotoDrop, + bonusMazeSize, + bonusBoatHireNoCircuit, + bonusSlideUnlimitedRides, + bonusMotionSimulatorMode, + bonus3DCinemaMode, + bonusTopSpinMode, + // Number of reversals BONUS for reverser coaster + bonusReversals, + // Number of hole BONUS for mini golf + bonusHoles, + // Number of cars bonus for dodgems/flying saucers + bonusNumTrains, + // Bonus for launched freefall in downward launch mode + bonusDownwardLaunch, + // Bonus with further mode-dependent logic for LF + bonusLaunchedFreefallSpecial, + // General Rating Requirements + requirementLength, + requirementDropHeight, + requirementNumDrops, + requirementMaxSpeed, + requirementNegativeGs, + requirementLateralGs, + requirementInversions, + requirementUnsheltered, + // Number of reversals REQUIREMENT for reverser coaster + requirementReversals, + // Number of hole REQUIREMENT for mini golf + requirementHoles, + // 2 Station requirement for Chairlift + requirementStations, + // Water section requirement for Water Coaster + requirementSplashdown, + penaltyLateralGs, + }; + + struct RideNameConvention + { + RideComponentType vehicle; + RideComponentType structure; + RideComponentType station; + }; + + struct RideBuildCost + { + money64 TrackPrice; // Cost of a single straight piece of track + money64 SupportPrice; + uint8_t PriceEstimateMultiplier; + }; + + struct RideHeights + { + uint8_t MaxHeight; + uint8_t ClearanceHeight; + int8_t VehicleZOffset; + uint8_t PlatformHeight; + }; + + struct RideLiftData + { + Audio::SoundId sound_id; + uint8_t minimum_speed; + uint8_t maximum_speed; + }; + + struct RideColourPreview + { + uint32_t Track; + uint32_t Supports; + }; + + struct RideOperatingSettings + { + uint8_t MinValue; + uint8_t MaxValue; + uint8_t OperatingSettingMultiplier = 1; // Used for the Ride window, cosmetic only. + }; + + struct RideTrackSpeedSettings + { + int8_t BrakesMaxSpeed = 30; + int8_t BoosterMaxSpeed = 30; + }; + + struct RideBoosterSettings + { + uint8_t PoweredLiftAcceleration = 0; + uint8_t BoosterAcceleration = 0; + uint8_t AccelerationFactor = 12; // the amount to right-shift the launch speed for powered launch from a station + }; + + struct RideLegacyBoosterSettings + // These values that must be kept for backwards compatibility. New ride types should set the acceleration values equal to + // BoosterSettings' and leave BoosterSpeedFactor at default. + { + uint8_t PoweredLiftAcceleration = 0; // PoweredLiftAcceleration value before unified-speed update + uint8_t BoosterAcceleration = 0; // BoosterAcceleration value before unified-speed update + int8_t BoosterSpeedFactor = 2; // Multiplier representing how much to multiply booster speed by, scaled to 2x the final + // multiplier. + }; + + struct RatingsModifier + { + RatingsModifierType type; + int32_t threshold; + int32_t excitement; + int32_t intensity; + int32_t nausea; + }; + + constexpr int8_t kDynamicRideShelterRating = -1; + + struct RideRatingsDescriptor + { + RatingsCalculationType Type; + RideRating::Tuple BaseRatings; + uint8_t Unreliability; + // Used for rides with a set sheltered 8ths value (kDynamicRideShelterRating = normal calculation) + int8_t RideShelter; + bool RelaxRequirementsIfInversions; + RatingsModifier Modifiers[32]; + }; + + struct UpkeepCostsDescriptor + { + /** + * Data about ride running costs. This is widely adjusted by the upkeep + * function, so values that don't make much sense here (a roller coaster having + * cheaper upkeep than a car ride) are fixed later on. + * + * Data generation script: https://gist.github.com/kevinburke/6bcf4a8fcc95faad7bac + */ + money64 BaseCost; + /** rct2: 0x0097E3AC */ + uint8_t TrackLengthMultiplier; + money64 CostPerTrackPiece; + /** rct2: 0x0097E3B4 */ + money64 CostPerTrain; + /** rct2: 0x0097E3B6 */ + money64 CostPerCar; + /** rct2: 0x0097E3B8 */ + money64 CostPerStation; + }; + + using RideTrackGroups = BitSet; + using UpdateRideApproachVehicleWaypointsFunction = void (*)(Guest&, const CoordsXY&, int16_t&); + using RideMusicUpdateFunction = void (*)(Ride&); + using PeepUpdateRideLeaveEntranceFunc = void (*)(Guest&, Ride&, CoordsXYZD&); + using StartRideMusicFunction = void (*)(const RideAudio::ViewportRideMusicInstance&); + using LightFXAddLightsMagicVehicleFunction = void (*)(const Vehicle* vehicle); + using RideLocationFunction = CoordsXY (*)(const Vehicle& vehicle, const Ride& ride, const StationIndex& CurrentRideStation); + using RideUpdateFunction = void (*)(Ride& ride); + using RideUpdateMeasurementsSpecialElementsFunc = void (*)(Ride& ride, TrackElemType trackType); + using MusicTrackOffsetLengthFunc = std::pair (*)(const Ride& ride); + using SpecialElementRatingAdjustmentFunc = void (*)( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); + + using UpdateRotatingFunction = void (*)(Vehicle& vehicle); + enum class RideConstructionWindowContext : uint8_t + { + standard, + maze, + }; + + struct TrackDrawerEntry + { + TrackStyle trackStyle = TrackStyle::null; + SupportType supportType{}; + /** rct2: 0x0097C468 (0 - 31) and 0x0097C5D4 (32 - 63) */ + RideTrackGroups enabledTrackGroups{}; + // Pieces that this ride type _can_ draw, but are disabled because their vehicles lack the relevant sprites, + // or because they are not realistic for the ride type (e.g. LIM boosters in Mini Roller Coasters). + RideTrackGroups extraTrackGroups{}; + + ImageIndex icon = kImageIndexUndefined; + StringId tooltip = kStringIdNone; + + void GetAvailableTrackGroups(RideTrackGroups& res) const; + bool SupportsTrackGroup(TrackGroup trackGroup) const; + }; + + struct TrackDrawerDescriptor + { + TrackDrawerEntry Regular{}; + TrackDrawerEntry Covered{}; + + constexpr TrackDrawerDescriptor() { - { RatingsModifierType::noModifier, 0, 0, 0, 0 }, + } + + constexpr TrackDrawerDescriptor(TrackDrawerEntry function) + : Regular(function) + { + } + + constexpr TrackDrawerDescriptor(TrackDrawerEntry entryRegular, TrackDrawerEntry entryCovered) + : Regular(entryRegular) + , Covered(entryCovered) + { + } + + bool HasCoveredPieces() const; + }; + + enum class RtdFlag : uint8_t + { + hasTrackColourMain, + hasTrackColourAdditional, + hasTrackColourSupports, + + // Set by flat rides, tower rides and shops/stalls. + hasSinglePieceStation, + + hasLeaveWhenAnotherVehicleArrivesAtStation, + canSynchroniseWithAdjacentStations, + + // Used only by boat Hire and submarine ride + trackMustBeOnWater, + + hasGForces, + + // Used by rides that can't have gaps, like those with a vertical tower, + // such as the observation tower. + cannotHaveGaps, + + hasDataLogging, + hasDrops, + + noTestMode, + + // Set on rides with two varieties, like the u and o shapes of the dinghy slide + // and the dry and submerged track of the water coaster. + hasCoveredPieces, + + // Used only by maze, spiral slide and shops + noVehicles, + + hasLoadOptions, + hasLsmBehaviourOnFlat, + + // Set by flat rides where the vehicle is integral to the structure, like + // Merry-go-round and swinging ships. (Contrast with rides like dodgems.) + vehicleIsIntegral, + + isShopOrFacility, + + // If set, wall scenery can not share a tile with the ride's track + noWallsAroundTrack, + + isFlatRide, + + // Whether or not guests will go on the ride again if they liked it + // (this is usually applied to everything apart from transport rides). + guestsWillRideAgain, + + // Used by Toilets and First Aid to mark that guest should go + // inside the building (rather than 'buying' at the counter) + guestsShouldGoInsideFacility, + + // Guests are "IN" (ride) rather than "ON" (ride) + describeAsInside, + + sellsFood, + sellsDrinks, + + // Whether or not vehicle colours can be set + hasVehicleColours, + + checkForStalling, + hasTrack, + + // Only set by lift + allowExtraTowerBases, + + // Only set by reverser coaster + layeredVehiclePreview, + + supportsMultipleColourSchemes, + allowDoorsOnTrack, + hasMusicByDefault, + allowMusic, + + // Used by the Flying RC, Lay-down RC, Multi-dimension RC + hasInvertedVariant, + + checkGForces, + hasEntranceAndExit, + allowMoreVehiclesThanStationFits, + hasAirTime, + singleSession, + allowMultipleCircuits, + allowCableLiftHill, + showInTrackDesigner, + isTransportRide, + interestingToLookAt, + slightlyInterestingToLookAt, + + // This is only set on the Flying RC and its alternative type. + startConstructionInverted, + + listVehiclesSeparately, + supportsLevelCrossings, + isSuspended, + hasLandscapeDoors, + upInclineRequiresLift, + guestsCanUseUmbrella, + hasOneStation, + hasSeatRotation, + allowReversedTrains, + + requireExplicitListingInMusicObjects, + + hasRoofOverWholeRide, + + runningSpeedAffectsReliability, + poweredLaunchAffectsReliability, + reverseInclineLaunchAffectsReliability, + + isDummyType, + }; + using RtdFlags = FlagHolder; + + /** + * Some rides are so different from others that they need some special code. + * This replaces direct ride type checks. + * + * Note: only add to this list if behaviour cannot sufficiently be altered using flags. + */ + enum class RtdSpecialType + { + none, + maze, + miniGolf, + spiralSlide, + toilet, + cashMachine, + firstAid, + enterprise, + motionSimulator, + spaceRings, + boatHire, + }; + + // Set on ride types that have a main colour, additional colour and support colour. + constexpr RtdFlags kRtdFlagsHasThreeColours = { RtdFlag::hasTrackColourMain, RtdFlag::hasTrackColourAdditional, + RtdFlag::hasTrackColourSupports }; + // Set on _all_ roller coaster ride types, including the _ALT types used for constructing upside down. + constexpr RtdFlags kRtdFlagsCommonCoaster = { RtdFlag::hasGForces, + RtdFlag::hasDataLogging, + RtdFlag::hasDrops, + RtdFlag::hasLoadOptions, + RtdFlag::guestsWillRideAgain, + RtdFlag::hasVehicleColours, + RtdFlag::checkForStalling, + RtdFlag::hasTrack, + RtdFlag::supportsMultipleColourSchemes, + RtdFlag::allowMusic, + RtdFlag::interestingToLookAt, + RtdFlag::canSynchroniseWithAdjacentStations }; + // Set on all roller coaster ride types, excluding the _ALT types used for constructing upside down. + constexpr RtdFlags kRtdFlagsCommonCoasterNonAlt = { RtdFlag::showInTrackDesigner, RtdFlag::hasAirTime, + RtdFlag::hasEntranceAndExit }; + + struct RideTypeDescriptor + { + RideCategory Category{}; + /** rct2: 0x0097CC68 */ + TrackElemType StartTrackPiece{}; + TrackDrawerDescriptor TrackPaintFunctions{}; + TrackDrawerDescriptor InvertedTrackPaintFunctions{}; + RtdFlags flags{}; + /** rct2: 0x0097C8AC */ + uint64_t RideModes{}; + RideMode DefaultMode{}; + /** rct2: 0x0097CF40 */ + RideOperatingSettings OperatingSettings{}; + RideTrackSpeedSettings TrackSpeedSettings{}; + RideBoosterSettings BoosterSettings{}; + RideLegacyBoosterSettings LegacyBoosterSettings{}; + RideNaming Naming{}; + RideNameConvention NameConvention{}; + FlagHolder availableBreakdowns{}; + /** rct2: 0x0097D218 */ + RideHeights Heights{}; + uint8_t MaxMass{}; + /** rct2: 0x0097D7C8, 0x0097D7C9, 0x0097D7CA */ + RideLiftData LiftData{}; + // rct2: 0x0097CD1E + RideRating::Tuple RatingsMultipliers{}; + UpkeepCostsDescriptor UpkeepCosts{}; + // rct2: 0x0097DD78 + RideBuildCost BuildCosts{}; + money64 DefaultPrices[RCT2::ObjectLimits::kMaxShopItemsPerRideEntry]{}; + std::string_view DefaultMusic{}; + /** rct2: 0x0097D7CB */ + ShopItemIndex PhotoItem{}; + /** rct2: 0x0097D21E */ + uint8_t BonusValue{}; + TrackColourPresetList ColourPresets{}; + RideColourPreview ColourPreview{}; + RideColourKey ColourKey{}; + + // json name lookup + std::string_view Name{}; + + RideRatingsDescriptor RatingsData{}; + + UpdateRotatingFunction UpdateRotating = UpdateRotatingDefault; + + LightFXAddLightsMagicVehicleFunction LightFXAddLightsMagicVehicle = nullptr; + StartRideMusicFunction StartRideMusic = RideAudio::DefaultStartRideMusicChannel; + + TrackDesignCreateMode DesignCreateMode = TrackDesignCreateMode::standard; + + RideMusicUpdateFunction MusicUpdateFunction = DefaultMusicUpdate; + RideClassification Classification = RideClassification::ride; + + PeepUpdateRideLeaveEntranceFunc UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault; + SpecialElementRatingAdjustmentFunc SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default; + + RideLocationFunction GetGuestWaypointLocation = GetGuestWaypointLocationDefault; + + RideConstructionWindowContext ConstructionWindowContext = RideConstructionWindowContext::standard; + RideUpdateFunction RideUpdate = nullptr; + + RideUpdateMeasurementsSpecialElementsFunc UpdateMeasurementsSpecialElements + = RideUpdateMeasurementsSpecialElements_Default; + + MusicTrackOffsetLengthFunc MusicTrackOffsetLength = RideAudio::RideMusicGetTrackOffsetLength_Default; + + UpdateRideApproachVehicleWaypointsFunction UpdateRideApproachVehicleWaypoints + = updateRideApproachVehicleWaypointsDefault; + RtdSpecialType specialType = RtdSpecialType::none; + + /** @deprecated */ + bool SupportsTrackGroup(TrackGroup trackGroup) const; + ResearchCategory GetResearchCategory() const; + bool SupportsRideMode(RideMode rideMode) const; + /** + * Converts booster speed from the ride type's speed regime (Junior, Default, Giga) to to the unified values used by the + * vehicle. See https://github.com/OpenRCT2/OpenRCT2/discussions/23119 for more information about unified speed. + */ + int32_t GetUnifiedBoosterSpeed(int32_t relativeSpeed) const; + }; + + extern const RideTypeDescriptor kRideTypeDescriptors[RIDE_TYPE_COUNT]; + + // clang-format off + constexpr RideComponentName kRideComponentNames[] = + { + { STR_RIDE_COMPONENT_TRAIN, STR_RIDE_COMPONENT_TRAIN_PLURAL, STR_RIDE_COMPONENT_TRAIN_CAPITALISED, STR_RIDE_COMPONENT_TRAIN_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_TRAIN_COUNT, STR_RIDE_COMPONENT_TRAIN_COUNT_PLURAL, STR_RIDE_COMPONENT_TRAIN_NO }, + { STR_RIDE_COMPONENT_BOAT, STR_RIDE_COMPONENT_BOAT_PLURAL, STR_RIDE_COMPONENT_BOAT_CAPITALISED, STR_RIDE_COMPONENT_BOAT_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_BOAT_COUNT, STR_RIDE_COMPONENT_BOAT_COUNT_PLURAL, STR_RIDE_COMPONENT_BOAT_NO }, + { STR_RIDE_COMPONENT_TRACK, STR_RIDE_COMPONENT_TRACK_PLURAL, STR_RIDE_COMPONENT_TRACK_CAPITALISED, STR_RIDE_COMPONENT_TRACK_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_TRACK_COUNT, STR_RIDE_COMPONENT_TRACK_COUNT_PLURAL, STR_RIDE_COMPONENT_TRACK_NO }, + { STR_RIDE_COMPONENT_DOCKING_PLATFORM, STR_RIDE_COMPONENT_DOCKING_PLATFORM_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_CAPITALISED, STR_RIDE_COMPONENT_DOCKING_PLATFORM_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_COUNT, STR_RIDE_COMPONENT_DOCKING_PLATFORM_COUNT_PLURAL, STR_RIDE_COMPONENT_DOCKING_PLATFORM_NO }, + { STR_RIDE_COMPONENT_STATION, STR_RIDE_COMPONENT_STATION_PLURAL, STR_RIDE_COMPONENT_STATION_CAPITALISED, STR_RIDE_COMPONENT_STATION_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_STATION_COUNT, STR_RIDE_COMPONENT_STATION_COUNT_PLURAL, STR_RIDE_COMPONENT_STATION_NO }, + { STR_RIDE_COMPONENT_CAR, STR_RIDE_COMPONENT_CAR_PLURAL, STR_RIDE_COMPONENT_CAR_CAPITALISED, STR_RIDE_COMPONENT_CAR_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_CAR_COUNT, STR_RIDE_COMPONENT_CAR_COUNT_PLURAL, STR_RIDE_COMPONENT_CAR_NO }, + { STR_RIDE_COMPONENT_BUILDING, STR_RIDE_COMPONENT_BUILDING_PLURAL, STR_RIDE_COMPONENT_BUILDING_CAPITALISED, STR_RIDE_COMPONENT_BUILDING_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_BUILDING_COUNT, STR_RIDE_COMPONENT_BUILDING_COUNT_PLURAL, STR_RIDE_COMPONENT_BUILDING_NO }, + { STR_RIDE_COMPONENT_STRUCTURE, STR_RIDE_COMPONENT_STRUCTURE_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_CAPITALISED, STR_RIDE_COMPONENT_STRUCTURE_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_COUNT, STR_RIDE_COMPONENT_STRUCTURE_COUNT_PLURAL, STR_RIDE_COMPONENT_STRUCTURE_NO }, + { STR_RIDE_COMPONENT_SHIP, STR_RIDE_COMPONENT_SHIP_PLURAL, STR_RIDE_COMPONENT_SHIP_CAPITALISED, STR_RIDE_COMPONENT_SHIP_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_SHIP_COUNT, STR_RIDE_COMPONENT_SHIP_COUNT_PLURAL, STR_RIDE_COMPONENT_SHIP_NO }, + { STR_RIDE_COMPONENT_CABIN, STR_RIDE_COMPONENT_CABIN_PLURAL, STR_RIDE_COMPONENT_CABIN_CAPITALISED, STR_RIDE_COMPONENT_CABIN_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_CABIN_COUNT, STR_RIDE_COMPONENT_CABIN_COUNT_PLURAL, STR_RIDE_COMPONENT_CABIN_NO }, + { STR_RIDE_COMPONENT_WHEEL, STR_RIDE_COMPONENT_WHEEL_PLURAL, STR_RIDE_COMPONENT_WHEEL_CAPITALISED, STR_RIDE_COMPONENT_WHEEL_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_WHEEL_COUNT, STR_RIDE_COMPONENT_WHEEL_COUNT_PLURAL, STR_RIDE_COMPONENT_WHEEL_NO }, + { STR_RIDE_COMPONENT_RING, STR_RIDE_COMPONENT_RING_PLURAL, STR_RIDE_COMPONENT_RING_CAPITALISED, STR_RIDE_COMPONENT_RING_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_RING_COUNT, STR_RIDE_COMPONENT_RING_COUNT_PLURAL, STR_RIDE_COMPONENT_RING_NO }, + { STR_RIDE_COMPONENT_PLAYER, STR_RIDE_COMPONENT_PLAYER_PLURAL, STR_RIDE_COMPONENT_PLAYER_CAPITALISED, STR_RIDE_COMPONENT_PLAYER_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_PLAYER_COUNT, STR_RIDE_COMPONENT_PLAYER_COUNT_PLURAL, STR_RIDE_COMPONENT_PLAYER_NO }, + { STR_RIDE_COMPONENT_COURSE, STR_RIDE_COMPONENT_COURSE_PLURAL, STR_RIDE_COMPONENT_COURSE_CAPITALISED, STR_RIDE_COMPONENT_COURSE_CAPITALISED_PLURAL, STR_RIDE_COMPONENT_COURSE_COUNT, STR_RIDE_COMPONENT_COURSE_COUNT_PLURAL, STR_RIDE_COMPONENT_COURSE_NO }, + }; + // clang-format on + + constexpr std::string_view kMusicObjectDodgems = "rct2.music.dodgems"; + constexpr std::string_view kMusicObjectEgyptian = "rct2.music.egyptian"; + constexpr std::string_view kMusicObjectFairground = "rct2.music.fairground"; + constexpr std::string_view kMusicObjectGentle = "rct2.music.gentle"; + constexpr std::string_view kMusicObjectHorror = "rct2.music.horror"; + constexpr std::string_view kMusicObjectPirate = "rct2.music.pirate"; + constexpr std::string_view kMusicObjectRock1 = "rct2.music.rock1"; + constexpr std::string_view kMusicObjectRock2 = "rct2.music.rock2"; + constexpr std::string_view kMusicObjectRock3 = "rct2.music.rock3"; + constexpr std::string_view kMusicObjectSummer = "rct2.music.summer"; + constexpr std::string_view kMusicObjectTechno = "rct2.music.techno"; + constexpr std::string_view kMusicObjectWater = "rct2.music.water"; + constexpr std::string_view kMusicObjectWildWest = "rct2.music.wildwest"; + constexpr std::string_view kMusicObjectModern = "rct2.music.modern"; + + constexpr const RideComponentName& GetRideComponentName(const RideComponentType type) + { + return kRideComponentNames[EnumValue(type)]; + } + + constexpr uint64_t kAllRideModesAvailable = EnumsToFlags( + RideMode::continuousCircuit, RideMode::continuousCircuitBlockSectioned, RideMode::reverseInclineLaunchedShuttle, + RideMode::poweredLaunchPassthrough, RideMode::shuttle, RideMode::normal, RideMode::boatHire, RideMode::upwardLaunch, + RideMode::rotatingLift, RideMode::stationToStation, RideMode::singleRidePerAdmission, + RideMode::unlimitedRidesPerAdmission, RideMode::maze, RideMode::race, RideMode::dodgems, RideMode::swing, + RideMode::shopStall, RideMode::rotation, RideMode::forwardRotation, RideMode::backwardRotation, + RideMode::filmAvengingAviators, RideMode::mouseTails3DFilm, RideMode::spaceRings, RideMode::beginners, + RideMode::limPoweredLaunch, RideMode::filmThrillRiders, RideMode::stormChasers3DFilm, RideMode::spaceRaiders3DFilm, + RideMode::intense, RideMode::berserk, RideMode::hauntedHouse, RideMode::circus, RideMode::downwardLaunch, + RideMode::crookedHouse, RideMode::freefallDrop, RideMode::poweredLaunch, RideMode::poweredLaunchBlockSectioned); + + extern const CarEntry kCableLiftVehicle; + + extern const uint16_t kRideFilmLength[3]; + + extern const StringId kRideModeNames[EnumValue(RideMode::count)]; + + // clang-format off + constexpr RideTypeDescriptor kDummyRTD = + { + .Category = RideCategory::none, + .StartTrackPiece = TrackElemType::endStation, + .TrackPaintFunctions = {}, + .InvertedTrackPaintFunctions = {}, + .flags = { RtdFlag::isDummyType }, + .RideModes = EnumsToFlags(RideMode::continuousCircuit), + .DefaultMode = RideMode::continuousCircuit, + .OperatingSettings = {}, + .TrackSpeedSettings = {}, + .BoosterSettings = {}, + .LegacyBoosterSettings = {}, + .Naming = { STR_UNKNOWN_RIDE, STR_RIDE_DESCRIPTION_UNKNOWN }, + .NameConvention = { RideComponentType::train, RideComponentType::track, RideComponentType::station }, + .availableBreakdowns = {}, + .Heights = { 12, 64, 0, 0, }, + .MaxMass = 255, + .LiftData = { Audio::SoundId::null, 5, 5 }, + .RatingsMultipliers = { 0, 0, 0 }, + .UpkeepCosts = { 50, 1, 0, 0, 0, 0 }, + .BuildCosts = { 0.00_GBP, 0.00_GBP, 1 }, + .DefaultPrices = { 20, 20 }, + .DefaultMusic = kMusicObjectGentle, + .PhotoItem = ShopItem::photo, + .BonusValue = 0, + .ColourPresets = kDefaultFlatRideColourPreset, + .ColourPreview = { kImageIndexUndefined, kImageIndexUndefined }, + .ColourKey = RideColourKey::ride, + .Name = "invalid", + .RatingsData = + { + RatingsCalculationType::flatRide, + { RideRating::make(1, 00), RideRating::make(1, 00), RideRating::make(1, 00) }, + 1, + -1, + false, + { + { RatingsModifierType::noModifier, 0, 0, 0, 0 }, + }, }, - }, - .UpdateRotating = UpdateRotatingDefault, - .LightFXAddLightsMagicVehicle = nullptr, - .StartRideMusic = OpenRCT2::RideAudio::DefaultStartRideMusicChannel, - .DesignCreateMode = TrackDesignCreateMode::standard, - .MusicUpdateFunction = DefaultMusicUpdate, - .Classification = RideClassification::ride, - .UpdateLeaveEntrance = OpenRCT2::PeepUpdateRideLeaveEntranceDefault, -}; -// clang-format on + .UpdateRotating = UpdateRotatingDefault, + .LightFXAddLightsMagicVehicle = nullptr, + .StartRideMusic = RideAudio::DefaultStartRideMusicChannel, + .DesignCreateMode = TrackDesignCreateMode::standard, + .MusicUpdateFunction = DefaultMusicUpdate, + .Classification = RideClassification::ride, + .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, + }; + // clang-format on -constexpr const RideTypeDescriptor& GetRideTypeDescriptor(ride_type_t rideType) -{ - if (rideType >= std::size(kRideTypeDescriptors)) - return kDummyRTD; + constexpr const RideTypeDescriptor& GetRideTypeDescriptor(ride_type_t rideType) + { + if (rideType >= std::size(kRideTypeDescriptors)) + return kDummyRTD; - return kRideTypeDescriptors[rideType]; -} + return kRideTypeDescriptors[rideType]; + } -constexpr bool RideTypeIsValid(ride_type_t rideType) -{ - return rideType < std::size(kRideTypeDescriptors); -} + constexpr bool RideTypeIsValid(ride_type_t rideType) + { + return rideType < std::size(kRideTypeDescriptors); + } -bool IsTrackEnabled(OpenRCT2::TrackGroup trackGroup); -void UpdateEnabledRideGroups(TrackDrawerDescriptor trackDrawerDescriptor); -void UpdateDisabledRideGroups(const RideTrackGroups& res); + bool IsTrackEnabled(TrackGroup trackGroup); + void UpdateEnabledRideGroups(TrackDrawerDescriptor trackDrawerDescriptor); + void UpdateDisabledRideGroups(const RideTrackGroups& res); -TrackDrawerDescriptor getTrackDrawerDescriptor(const RideTypeDescriptor& rtd, bool isInverted); -TrackDrawerEntry getTrackDrawerEntry(const RideTypeDescriptor& rtd, bool isInverted = false, bool isCovered = false); + TrackDrawerDescriptor getTrackDrawerDescriptor(const RideTypeDescriptor& rtd, bool isInverted); + TrackDrawerEntry getTrackDrawerEntry(const RideTypeDescriptor& rtd, bool isInverted = false, bool isCovered = false); +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideEntry.h b/src/openrct2/ride/RideEntry.h index b818fe4979..86129bc46a 100644 --- a/src/openrct2/ride/RideEntry.h +++ b/src/openrct2/ride/RideEntry.h @@ -137,4 +137,7 @@ struct RideObjectEntry } }; -RideNaming GetRideNaming(ride_type_t rideType, const RideObjectEntry* rideEntry); +namespace OpenRCT2 +{ + RideNaming GetRideNaming(ride_type_t rideType, const RideObjectEntry* rideEntry); +} diff --git a/src/openrct2/ride/RideRatings.cpp b/src/openrct2/ride/RideRatings.cpp index ecd3327b02..4ccf89478a 100644 --- a/src/openrct2/ride/RideRatings.cpp +++ b/src/openrct2/ride/RideRatings.cpp @@ -31,2235 +31,2248 @@ #include -using namespace OpenRCT2; -using namespace OpenRCT2::Scripting; -using namespace OpenRCT2::TrackMetadata; - -enum +namespace OpenRCT2 { - RIDE_RATINGS_STATE_FIND_NEXT_RIDE, - RIDE_RATINGS_STATE_INITIALISE, - RIDE_RATINGS_STATE_2, - RIDE_RATINGS_STATE_CALCULATE, - RIDE_RATINGS_STATE_4, - RIDE_RATINGS_STATE_5 -}; + using namespace OpenRCT2::Scripting; + using namespace OpenRCT2::TrackMetadata; -enum -{ - RIDE_RATING_STATION_FLAG_NO_ENTRANCE = 1 << 0 -}; - -enum -{ - PROXIMITY_WATER_OVER, // 0x0138B596 - PROXIMITY_WATER_TOUCH, // 0x0138B598 - PROXIMITY_WATER_LOW, // 0x0138B59A - PROXIMITY_WATER_HIGH, // 0x0138B59C - PROXIMITY_SURFACE_TOUCH, // 0x0138B59E - PROXIMITY_QUEUE_PATH_OVER, // 0x0138B5A0 - PROXIMITY_QUEUE_PATH_TOUCH_ABOVE, // 0x0138B5A2 - PROXIMITY_QUEUE_PATH_TOUCH_UNDER, // 0x0138B5A4 - PROXIMITY_PATH_TOUCH_ABOVE, // 0x0138B5A6 - PROXIMITY_PATH_TOUCH_UNDER, // 0x0138B5A8 - PROXIMITY_OWN_TRACK_TOUCH_ABOVE, // 0x0138B5AA - PROXIMITY_OWN_TRACK_CLOSE_ABOVE, // 0x0138B5AC - PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW, // 0x0138B5AE - PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE, // 0x0138B5B0 - PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE, // 0x0138B5B2 - PROXIMITY_SCENERY_SIDE_BELOW, // 0x0138B5B4 - PROXIMITY_SCENERY_SIDE_ABOVE, // 0x0138B5B6 - PROXIMITY_OWN_STATION_TOUCH_ABOVE, // 0x0138B5B8 - PROXIMITY_OWN_STATION_CLOSE_ABOVE, // 0x0138B5BA - PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP, // 0x0138B5BC - PROXIMITY_PATH_THROUGH_VERTICAL_LOOP, // 0x0138B5BE - PROXIMITY_INTERSECTING_VERTICAL_LOOP, // 0x0138B5C0 - PROXIMITY_THROUGH_VERTICAL_LOOP, // 0x0138B5C2 - PROXIMITY_PATH_SIDE_CLOSE, // 0x0138B5C4 - PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE, // 0x0138B5C6 - PROXIMITY_SURFACE_SIDE_CLOSE, // 0x0138B5C8 - PROXIMITY_COUNT -}; - -struct ShelteredEights -{ - uint8_t TrackShelteredEighths; - uint8_t TotalShelteredEighths; -}; - -// Amount of updates allowed per updating state on the current tick. -// The total amount would be MaxRideRatingSubSteps * RideRating::kMaxUpdateStates which -// would be currently 80, this is the worst case of sub-steps and may break out earlier. -static constexpr size_t MaxRideRatingUpdateSubSteps = 20; - -static void ride_ratings_update_state(RideRating::UpdateState& state); -static void ride_ratings_update_state_0(RideRating::UpdateState& state); -static void ride_ratings_update_state_1(RideRating::UpdateState& state); -static void ride_ratings_update_state_2(RideRating::UpdateState& state); -static void ride_ratings_update_state_3(RideRating::UpdateState& state); -static void ride_ratings_update_state_4(RideRating::UpdateState& state); -static void ride_ratings_update_state_5(RideRating::UpdateState& state); -static void ride_ratings_begin_proximity_loop(RideRating::UpdateState& state); -static void RideRatingsCalculate(RideRating::UpdateState& state, Ride& ride); -static void RideRatingsCalculateValue(Ride& ride); -static void ride_ratings_score_close_proximity(RideRating::UpdateState& state, TileElement* inputTileElement); -static void RideRatingsAdd(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea); - -static ShelteredEights GetNumOfShelteredEighths(const Ride& ride); -static money64 RideComputeUpkeep(RideRating::UpdateState& state, const Ride& ride); -static void SetUnreliabilityFactor(Ride& ride); - -static void RideRatingsApplyAdjustments(const Ride& ride, RideRating::Tuple& ratings); -static void RideRatingsApplyIntensityPenalty(RideRating::Tuple& ratings); - -static void RideRatingsApplyBonusLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusSynchronisation(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusTrainLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusAverageSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusDuration(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusGForces(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusTurns(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusSheltered(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusRotations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusOperationOption(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusReversedTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusGoKartRace(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusTowerRide(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusRotoDrop(RideRating::Tuple& ratings, const Ride& ride); -static void RideRatingsApplyBonusMazeSize(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusBoatHireNoCircuit(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusSlideUnlimitedRides(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusMotionSimulatorMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonus3DCinemaMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusTopSpinMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusReversals( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); -static void RideRatingsApplyBonusHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusNumTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusDownwardLaunch(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyBonusLaunchedFreefallSpecial( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); -static void RideRatingsApplyBonusProximity( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); -static void RideRatingsApplyBonusScenery(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementDropHeight(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementNumDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementNegativeGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementInversions(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementUnsheltered( - RideRating::Tuple& ratings, const Ride& ride, uint8_t shelteredEighths, RatingsModifier modifier); -static void RideRatingsApplyRequirementReversals( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); -static void RideRatingsApplyRequirementHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementStations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyRequirementSplashdown(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); -static void RideRatingsApplyPenaltyLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); - -void RideRating::ResetUpdateStates() -{ - UpdateState nullState{}; - nullState.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - - auto& updateStates = getGameState().rideRatingUpdateStates; - std::fill(updateStates.begin(), updateStates.end(), nullState); -} - -/** - * This is a small hack function to keep calling the ride rating processor until - * the given ride's ratings have been calculated. Whatever is currently being - * processed will be overwritten. - * Only purpose of this function currently is for testing. - */ -void RideRating::UpdateRide(const Ride& ride) -{ - if (ride.status != RideStatus::closed) + enum { - UpdateState state; - state.CurrentRide = ride.id; - state.State = RIDE_RATINGS_STATE_INITIALISE; - while (state.State != RIDE_RATINGS_STATE_FIND_NEXT_RIDE) + RIDE_RATINGS_STATE_FIND_NEXT_RIDE, + RIDE_RATINGS_STATE_INITIALISE, + RIDE_RATINGS_STATE_2, + RIDE_RATINGS_STATE_CALCULATE, + RIDE_RATINGS_STATE_4, + RIDE_RATINGS_STATE_5 + }; + + enum + { + RIDE_RATING_STATION_FLAG_NO_ENTRANCE = 1 << 0 + }; + + enum + { + PROXIMITY_WATER_OVER, // 0x0138B596 + PROXIMITY_WATER_TOUCH, // 0x0138B598 + PROXIMITY_WATER_LOW, // 0x0138B59A + PROXIMITY_WATER_HIGH, // 0x0138B59C + PROXIMITY_SURFACE_TOUCH, // 0x0138B59E + PROXIMITY_QUEUE_PATH_OVER, // 0x0138B5A0 + PROXIMITY_QUEUE_PATH_TOUCH_ABOVE, // 0x0138B5A2 + PROXIMITY_QUEUE_PATH_TOUCH_UNDER, // 0x0138B5A4 + PROXIMITY_PATH_TOUCH_ABOVE, // 0x0138B5A6 + PROXIMITY_PATH_TOUCH_UNDER, // 0x0138B5A8 + PROXIMITY_OWN_TRACK_TOUCH_ABOVE, // 0x0138B5AA + PROXIMITY_OWN_TRACK_CLOSE_ABOVE, // 0x0138B5AC + PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW, // 0x0138B5AE + PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE, // 0x0138B5B0 + PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE, // 0x0138B5B2 + PROXIMITY_SCENERY_SIDE_BELOW, // 0x0138B5B4 + PROXIMITY_SCENERY_SIDE_ABOVE, // 0x0138B5B6 + PROXIMITY_OWN_STATION_TOUCH_ABOVE, // 0x0138B5B8 + PROXIMITY_OWN_STATION_CLOSE_ABOVE, // 0x0138B5BA + PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP, // 0x0138B5BC + PROXIMITY_PATH_THROUGH_VERTICAL_LOOP, // 0x0138B5BE + PROXIMITY_INTERSECTING_VERTICAL_LOOP, // 0x0138B5C0 + PROXIMITY_THROUGH_VERTICAL_LOOP, // 0x0138B5C2 + PROXIMITY_PATH_SIDE_CLOSE, // 0x0138B5C4 + PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE, // 0x0138B5C6 + PROXIMITY_SURFACE_SIDE_CLOSE, // 0x0138B5C8 + PROXIMITY_COUNT + }; + + struct ShelteredEights + { + uint8_t TrackShelteredEighths; + uint8_t TotalShelteredEighths; + }; + + // Amount of updates allowed per updating state on the current tick. + // The total amount would be MaxRideRatingSubSteps * RideRating::kMaxUpdateStates which + // would be currently 80, this is the worst case of sub-steps and may break out earlier. + static constexpr size_t MaxRideRatingUpdateSubSteps = 20; + + static void ride_ratings_update_state(RideRating::UpdateState& state); + static void ride_ratings_update_state_0(RideRating::UpdateState& state); + static void ride_ratings_update_state_1(RideRating::UpdateState& state); + static void ride_ratings_update_state_2(RideRating::UpdateState& state); + static void ride_ratings_update_state_3(RideRating::UpdateState& state); + static void ride_ratings_update_state_4(RideRating::UpdateState& state); + static void ride_ratings_update_state_5(RideRating::UpdateState& state); + static void ride_ratings_begin_proximity_loop(RideRating::UpdateState& state); + static void RideRatingsCalculate(RideRating::UpdateState& state, Ride& ride); + static void RideRatingsCalculateValue(Ride& ride); + static void ride_ratings_score_close_proximity(RideRating::UpdateState& state, TileElement* inputTileElement); + static void RideRatingsAdd(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea); + + static ShelteredEights GetNumOfShelteredEighths(const Ride& ride); + static money64 RideComputeUpkeep(RideRating::UpdateState& state, const Ride& ride); + static void SetUnreliabilityFactor(Ride& ride); + + static void RideRatingsApplyAdjustments(const Ride& ride, RideRating::Tuple& ratings); + static void RideRatingsApplyIntensityPenalty(RideRating::Tuple& ratings); + + static void RideRatingsApplyBonusLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusSynchronisation(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusTrainLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusAverageSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusDuration(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusGForces(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusTurns(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusSheltered(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusRotations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusOperationOption(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusReversedTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusGoKartRace(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusTowerRide(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusRotoDrop(RideRating::Tuple& ratings, const Ride& ride); + static void RideRatingsApplyBonusMazeSize(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusBoatHireNoCircuit(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusSlideUnlimitedRides( + RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusMotionSimulatorMode( + RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonus3DCinemaMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusTopSpinMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusReversals( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); + static void RideRatingsApplyBonusHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusNumTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusDownwardLaunch(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyBonusLaunchedFreefallSpecial( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); + static void RideRatingsApplyBonusProximity( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); + static void RideRatingsApplyBonusScenery(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementDropHeight(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementNumDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementNegativeGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementInversions(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementUnsheltered( + RideRating::Tuple& ratings, const Ride& ride, uint8_t shelteredEighths, RatingsModifier modifier); + static void RideRatingsApplyRequirementReversals( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier); + static void RideRatingsApplyRequirementHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementStations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyRequirementSplashdown(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + static void RideRatingsApplyPenaltyLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier); + + void RideRating::ResetUpdateStates() + { + UpdateState nullState{}; + nullState.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + + auto& updateStates = getGameState().rideRatingUpdateStates; + std::fill(updateStates.begin(), updateStates.end(), nullState); + } + + /** + * This is a small hack function to keep calling the ride rating processor until + * the given ride's ratings have been calculated. Whatever is currently being + * processed will be overwritten. + * Only purpose of this function currently is for testing. + */ + void RideRating::UpdateRide(const Ride& ride) + { + if (ride.status != RideStatus::closed) { - ride_ratings_update_state(state); + UpdateState state; + state.CurrentRide = ride.id; + state.State = RIDE_RATINGS_STATE_INITIALISE; + while (state.State != RIDE_RATINGS_STATE_FIND_NEXT_RIDE) + { + ride_ratings_update_state(state); + } } } -} -/** - * - * rct2: 0x006B5A2A - */ -void RideRating::UpdateAll() -{ - PROFILED_FUNCTION(); - - if (gLegacyScene == LegacyScene::scenarioEditor) - return; - - for (auto& updateState : getGameState().rideRatingUpdateStates) + /** + * + * rct2: 0x006B5A2A + */ + void RideRating::UpdateAll() { - for (size_t i = 0; i < MaxRideRatingUpdateSubSteps; ++i) - { - ride_ratings_update_state(updateState); + PROFILED_FUNCTION(); - // We need to abort the loop if the state machine requested to find the next ride. - if (updateState.State == RIDE_RATINGS_STATE_FIND_NEXT_RIDE) + if (gLegacyScene == LegacyScene::scenarioEditor) + return; + + for (auto& updateState : getGameState().rideRatingUpdateStates) + { + for (size_t i = 0; i < MaxRideRatingUpdateSubSteps; ++i) + { + ride_ratings_update_state(updateState); + + // We need to abort the loop if the state machine requested to find the next ride. + if (updateState.State == RIDE_RATINGS_STATE_FIND_NEXT_RIDE) + break; + } + } + } + + static void ride_ratings_update_state(RideRating::UpdateState& state) + { + switch (state.State) + { + case RIDE_RATINGS_STATE_FIND_NEXT_RIDE: + ride_ratings_update_state_0(state); + break; + case RIDE_RATINGS_STATE_INITIALISE: + ride_ratings_update_state_1(state); + break; + case RIDE_RATINGS_STATE_2: + ride_ratings_update_state_2(state); + break; + case RIDE_RATINGS_STATE_CALCULATE: + ride_ratings_update_state_3(state); + break; + case RIDE_RATINGS_STATE_4: + ride_ratings_update_state_4(state); + break; + case RIDE_RATINGS_STATE_5: + ride_ratings_update_state_5(state); break; } } -} -static void ride_ratings_update_state(RideRating::UpdateState& state) -{ - switch (state.State) + static bool RideRatingIsUpdatingRide(RideId id) { - case RIDE_RATINGS_STATE_FIND_NEXT_RIDE: - ride_ratings_update_state_0(state); - break; - case RIDE_RATINGS_STATE_INITIALISE: - ride_ratings_update_state_1(state); - break; - case RIDE_RATINGS_STATE_2: - ride_ratings_update_state_2(state); - break; - case RIDE_RATINGS_STATE_CALCULATE: - ride_ratings_update_state_3(state); - break; - case RIDE_RATINGS_STATE_4: - ride_ratings_update_state_4(state); - break; - case RIDE_RATINGS_STATE_5: - ride_ratings_update_state_5(state); - break; - } -} - -static bool RideRatingIsUpdatingRide(RideId id) -{ - const auto& updateStates = getGameState().rideRatingUpdateStates; - return std::any_of(updateStates.begin(), updateStates.end(), [id](auto& state) { - return state.CurrentRide == id && state.State != RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - }); -} - -static bool ShouldSkipRatingCalculation(const Ride& ride) -{ - // Skip rides that are closed. - if (ride.status == RideStatus::closed) - { - return true; + const auto& updateStates = getGameState().rideRatingUpdateStates; + return std::any_of(updateStates.begin(), updateStates.end(), [id](auto& state) { + return state.CurrentRide == id && state.State != RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + }); } - // Skip anything that is already updating. - if (RideRatingIsUpdatingRide(ride.id)) + static bool ShouldSkipRatingCalculation(const Ride& ride) { - return true; - } - - // Skip rides that have a fixed rating. - if (ride.flags.has(RideFlag::fixedRatings)) - { - return true; - } - - return false; -} - -static RideId GetNextRideToUpdate(RideId currentRide) -{ - auto& gameState = getGameState(); - auto rm = RideManager(gameState); - if (rm.size() == 0) - { - return RideId::GetNull(); - } - - auto it = rm.get(currentRide); - if (it == rm.end()) - { - // Start at the beginning, ride is missing. - it = rm.begin(); - } - else - { - it = std::next(it); - } - - // Filter out rides to avoid wasting a tick to find the next ride. - while (it != rm.end() && ShouldSkipRatingCalculation(*it)) - { - it++; - } - - // If we reached the end of the list we start over, - // in case the next ride doesn't pass the filter function it will - // look for the next matching ride in the next tick. - if (it == rm.end()) - it = rm.begin(); - - return (*it).id; -} - -/** - * - * rct2: 0x006B5A5C - */ -static void ride_ratings_update_state_0(RideRating::UpdateState& state) -{ - // It is possible that the current ride being calculated has - // been removed or due to import invalid. For both, reset - // ratings and start check at the start - if (GetRide(state.CurrentRide) == nullptr) - { - state.CurrentRide = {}; - } - - const auto nextRideId = GetNextRideToUpdate(state.CurrentRide); - const auto* nextRide = GetRide(nextRideId); - if (nextRide != nullptr && !ShouldSkipRatingCalculation(*nextRide)) - { - Guard::Assert(!RideRatingIsUpdatingRide(nextRideId)); - state.State = RIDE_RATINGS_STATE_INITIALISE; - } - state.CurrentRide = nextRideId; -} - -/** - * - * rct2: 0x006B5A94 - */ -static void ride_ratings_update_state_1(RideRating::UpdateState& state) -{ - state.ProximityTotal = 0; - for (int32_t i = 0; i < PROXIMITY_COUNT; i++) - { - state.ProximityScores[i] = 0; - } - state.AmountOfBrakes = 0; - state.amountOfBoosters = 0; - state.AmountOfReversers = 0; - state.State = RIDE_RATINGS_STATE_2; - state.StationFlags = 0; - ride_ratings_begin_proximity_loop(state); -} - -/** - * - * rct2: 0x006B5C66 - */ -static void ride_ratings_update_state_2(RideRating::UpdateState& state) -{ - const RideId rideIndex = state.CurrentRide; - auto ride = GetRide(rideIndex); - if (ride == nullptr || ride->status == RideStatus::closed || ride->type >= RIDE_TYPE_COUNT) - { - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; - } - - auto loc = state.Proximity; - TrackElemType trackType = state.ProximityTrackType; - - TileElement* tileElement = MapGetFirstElementAt(loc); - if (tileElement == nullptr) - { - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; - } - do - { - if (tileElement->isGhost()) - continue; - if (tileElement->getType() != TileElementType::track) - continue; - if (tileElement->getBaseZ() != loc.z) - continue; - if (tileElement->asTrack()->GetRideIndex() != ride->id) + // Skip rides that are closed. + if (ride.status == RideStatus::closed) { - // Only check that the track belongs to the same ride if ride does not have buildable track - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) - continue; + return true; } - if (trackType == TrackElemType::none - || (tileElement->asTrack()->GetSequenceIndex() == 0 && trackType == tileElement->asTrack()->GetTrackType())) + // Skip anything that is already updating. + if (RideRatingIsUpdatingRide(ride.id)) { - if (trackType == TrackElemType::endStation) + return true; + } + + // Skip rides that have a fixed rating. + if (ride.flags.has(RideFlag::fixedRatings)) + { + return true; + } + + return false; + } + + static RideId GetNextRideToUpdate(RideId currentRide) + { + auto& gameState = getGameState(); + auto rm = RideManager(gameState); + if (rm.size() == 0) + { + return RideId::GetNull(); + } + + auto it = rm.get(currentRide); + if (it == rm.end()) + { + // Start at the beginning, ride is missing. + it = rm.begin(); + } + else + { + it = std::next(it); + } + + // Filter out rides to avoid wasting a tick to find the next ride. + while (it != rm.end() && ShouldSkipRatingCalculation(*it)) + { + it++; + } + + // If we reached the end of the list we start over, + // in case the next ride doesn't pass the filter function it will + // look for the next matching ride in the next tick. + if (it == rm.end()) + it = rm.begin(); + + return (*it).id; + } + + /** + * + * rct2: 0x006B5A5C + */ + static void ride_ratings_update_state_0(RideRating::UpdateState& state) + { + // It is possible that the current ride being calculated has + // been removed or due to import invalid. For both, reset + // ratings and start check at the start + if (GetRide(state.CurrentRide) == nullptr) + { + state.CurrentRide = {}; + } + + const auto nextRideId = GetNextRideToUpdate(state.CurrentRide); + const auto* nextRide = GetRide(nextRideId); + if (nextRide != nullptr && !ShouldSkipRatingCalculation(*nextRide)) + { + Guard::Assert(!RideRatingIsUpdatingRide(nextRideId)); + state.State = RIDE_RATINGS_STATE_INITIALISE; + } + state.CurrentRide = nextRideId; + } + + /** + * + * rct2: 0x006B5A94 + */ + static void ride_ratings_update_state_1(RideRating::UpdateState& state) + { + state.ProximityTotal = 0; + for (int32_t i = 0; i < PROXIMITY_COUNT; i++) + { + state.ProximityScores[i] = 0; + } + state.AmountOfBrakes = 0; + state.amountOfBoosters = 0; + state.AmountOfReversers = 0; + state.State = RIDE_RATINGS_STATE_2; + state.StationFlags = 0; + ride_ratings_begin_proximity_loop(state); + } + + /** + * + * rct2: 0x006B5C66 + */ + static void ride_ratings_update_state_2(RideRating::UpdateState& state) + { + const RideId rideIndex = state.CurrentRide; + auto ride = GetRide(rideIndex); + if (ride == nullptr || ride->status == RideStatus::closed || ride->type >= RIDE_TYPE_COUNT) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + + auto loc = state.Proximity; + TrackElemType trackType = state.ProximityTrackType; + + TileElement* tileElement = MapGetFirstElementAt(loc); + if (tileElement == nullptr) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + do + { + if (tileElement->isGhost()) + continue; + if (tileElement->getType() != TileElementType::track) + continue; + if (tileElement->getBaseZ() != loc.z) + continue; + if (tileElement->asTrack()->GetRideIndex() != ride->id) + { + // Only check that the track belongs to the same ride if ride does not have buildable track + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + continue; + } + + if (trackType == TrackElemType::none + || (tileElement->asTrack()->GetSequenceIndex() == 0 && trackType == tileElement->asTrack()->GetTrackType())) + { + if (trackType == TrackElemType::endStation) + { + auto entranceIndex = tileElement->asTrack()->GetStationIndex(); + state.StationFlags &= ~RIDE_RATING_STATION_FLAG_NO_ENTRANCE; + if (ride->getStation(entranceIndex).Entrance.IsNull()) + { + state.StationFlags |= RIDE_RATING_STATION_FLAG_NO_ENTRANCE; + } + } + + ride_ratings_score_close_proximity(state, tileElement); + + CoordsXYE trackElement = { state.Proximity, tileElement }; + CoordsXYE nextTrackElement; + if (!trackBlockGetNext(&trackElement, &nextTrackElement, nullptr, nullptr)) + { + state.State = RIDE_RATINGS_STATE_4; + return; + } + + loc = { nextTrackElement, nextTrackElement.element->getBaseZ() }; + tileElement = nextTrackElement.element; + if (loc == state.ProximityStart) + { + state.State = RIDE_RATINGS_STATE_CALCULATE; + return; + } + state.Proximity = loc; + state.ProximityTrackType = tileElement->asTrack()->GetTrackType(); + return; + } + } while (!(tileElement++)->isLastForTile()); + + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + } + + /** + * + * rct2: 0x006B5E4D + */ + static void ride_ratings_update_state_3(RideRating::UpdateState& state) + { + auto ride = GetRide(state.CurrentRide); + if (ride == nullptr || ride->status == RideStatus::closed) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + + RideRatingsCalculate(state, *ride); + RideRatingsCalculateValue(*ride); + + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + } + + /** + * + * rct2: 0x006B5BAB + */ + static void ride_ratings_update_state_4(RideRating::UpdateState& state) + { + state.State = RIDE_RATINGS_STATE_5; + ride_ratings_begin_proximity_loop(state); + } + + /** + * + * rct2: 0x006B5D72 + */ + static void ride_ratings_update_state_5(RideRating::UpdateState& state) + { + auto ride = GetRide(state.CurrentRide); + if (ride == nullptr || ride->status == RideStatus::closed) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + + auto loc = state.Proximity; + TrackElemType trackType = state.ProximityTrackType; + + TileElement* tileElement = MapGetFirstElementAt(loc); + if (tileElement == nullptr) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + do + { + if (tileElement->isGhost()) + continue; + if (tileElement->getType() != TileElementType::track) + continue; + if (tileElement->getBaseZ() != loc.z) + continue; + if (tileElement->asTrack()->GetRideIndex() != ride->id) + { + // Only check that the track belongs to the same ride if ride does not have buildable track + if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + continue; + } + + if (trackType == TrackElemType::none || trackType == tileElement->asTrack()->GetTrackType()) + { + ride_ratings_score_close_proximity(state, tileElement); + + TrackBeginEnd trackBeginEnd; + if (!trackBlockGetPrevious({ state.Proximity, tileElement }, &trackBeginEnd)) + { + state.State = RIDE_RATINGS_STATE_CALCULATE; + return; + } + + loc.x = trackBeginEnd.begin_x; + loc.y = trackBeginEnd.begin_y; + loc.z = trackBeginEnd.begin_z; + if (loc == state.ProximityStart) + { + state.State = RIDE_RATINGS_STATE_CALCULATE; + return; + } + state.Proximity = loc; + state.ProximityTrackType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); + return; + } + } while (!(tileElement++)->isLastForTile()); + + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + } + + /** + * + * rct2: 0x006B5BB2 + */ + static void ride_ratings_begin_proximity_loop(RideRating::UpdateState& state) + { + auto ride = GetRide(state.CurrentRide); + if (ride == nullptr || ride->status == RideStatus::closed) + { + state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; + return; + } + + const auto& rtd = ride->getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + { + state.State = RIDE_RATINGS_STATE_CALCULATE; + return; + } + + for (auto& station : ride->getStations()) + { + if (!station.Start.IsNull()) { - auto entranceIndex = tileElement->asTrack()->GetStationIndex(); state.StationFlags &= ~RIDE_RATING_STATION_FLAG_NO_ENTRANCE; - if (ride->getStation(entranceIndex).Entrance.IsNull()) + if (station.Entrance.IsNull()) { state.StationFlags |= RIDE_RATING_STATION_FLAG_NO_ENTRANCE; } - } - ride_ratings_score_close_proximity(state, tileElement); - - CoordsXYE trackElement = { state.Proximity, tileElement }; - CoordsXYE nextTrackElement; - if (!trackBlockGetNext(&trackElement, &nextTrackElement, nullptr, nullptr)) - { - state.State = RIDE_RATINGS_STATE_4; + auto location = station.GetStart(); + state.Proximity = location; + state.ProximityTrackType = TrackElemType::none; + state.ProximityStart = location; return; } - - loc = { nextTrackElement, nextTrackElement.element->getBaseZ() }; - tileElement = nextTrackElement.element; - if (loc == state.ProximityStart) - { - state.State = RIDE_RATINGS_STATE_CALCULATE; - return; - } - state.Proximity = loc; - state.ProximityTrackType = tileElement->asTrack()->GetTrackType(); - return; } - } while (!(tileElement++)->isLastForTile()); - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; -} - -/** - * - * rct2: 0x006B5E4D - */ -static void ride_ratings_update_state_3(RideRating::UpdateState& state) -{ - auto ride = GetRide(state.CurrentRide); - if (ride == nullptr || ride->status == RideStatus::closed) - { state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; } - RideRatingsCalculate(state, *ride); - RideRatingsCalculateValue(*ride); - - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; -} - -/** - * - * rct2: 0x006B5BAB - */ -static void ride_ratings_update_state_4(RideRating::UpdateState& state) -{ - state.State = RIDE_RATINGS_STATE_5; - ride_ratings_begin_proximity_loop(state); -} - -/** - * - * rct2: 0x006B5D72 - */ -static void ride_ratings_update_state_5(RideRating::UpdateState& state) -{ - auto ride = GetRide(state.CurrentRide); - if (ride == nullptr || ride->status == RideStatus::closed) + static void proximity_score_increment(RideRating::UpdateState& state, int32_t type) { - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; + state.ProximityScores[type]++; } - auto loc = state.Proximity; - TrackElemType trackType = state.ProximityTrackType; + /** + * + * rct2: 0x006B6207 + */ + static void ride_ratings_score_close_proximity_in_direction( + RideRating::UpdateState& state, TileElement* inputTileElement, int32_t direction) + { + auto scorePos = CoordsXY{ CoordsXY{ state.Proximity } + CoordsDirectionDelta[direction] }; + if (!MapIsLocationValid(scorePos)) + return; - TileElement* tileElement = MapGetFirstElementAt(loc); - if (tileElement == nullptr) - { - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; - } - do - { - if (tileElement->isGhost()) - continue; - if (tileElement->getType() != TileElementType::track) - continue; - if (tileElement->getBaseZ() != loc.z) - continue; - if (tileElement->asTrack()->GetRideIndex() != ride->id) + TileElement* tileElement = MapGetFirstElementAt(scorePos); + if (tileElement == nullptr) + return; + do { - // Only check that the track belongs to the same ride if ride does not have buildable track - if (!ride->getRideTypeDescriptor().flags.has(RtdFlag::hasTrack)) + if (tileElement->isGhost()) continue; - } - if (trackType == TrackElemType::none || trackType == tileElement->asTrack()->GetTrackType()) - { - ride_ratings_score_close_proximity(state, tileElement); - - TrackBeginEnd trackBeginEnd; - if (!trackBlockGetPrevious({ state.Proximity, tileElement }, &trackBeginEnd)) + switch (tileElement->getType()) { - state.State = RIDE_RATINGS_STATE_CALCULATE; - return; - } - - loc.x = trackBeginEnd.begin_x; - loc.y = trackBeginEnd.begin_y; - loc.z = trackBeginEnd.begin_z; - if (loc == state.ProximityStart) - { - state.State = RIDE_RATINGS_STATE_CALCULATE; - return; - } - state.Proximity = loc; - state.ProximityTrackType = trackBeginEnd.begin_element->asTrack()->GetTrackType(); - return; - } - } while (!(tileElement++)->isLastForTile()); - - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; -} - -/** - * - * rct2: 0x006B5BB2 - */ -static void ride_ratings_begin_proximity_loop(RideRating::UpdateState& state) -{ - auto ride = GetRide(state.CurrentRide); - if (ride == nullptr || ride->status == RideStatus::closed) - { - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; - return; - } - - const auto& rtd = ride->getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - { - state.State = RIDE_RATINGS_STATE_CALCULATE; - return; - } - - for (auto& station : ride->getStations()) - { - if (!station.Start.IsNull()) - { - state.StationFlags &= ~RIDE_RATING_STATION_FLAG_NO_ENTRANCE; - if (station.Entrance.IsNull()) - { - state.StationFlags |= RIDE_RATING_STATION_FLAG_NO_ENTRANCE; - } - - auto location = station.GetStart(); - state.Proximity = location; - state.ProximityTrackType = TrackElemType::none; - state.ProximityStart = location; - return; - } - } - - state.State = RIDE_RATINGS_STATE_FIND_NEXT_RIDE; -} - -static void proximity_score_increment(RideRating::UpdateState& state, int32_t type) -{ - state.ProximityScores[type]++; -} - -/** - * - * rct2: 0x006B6207 - */ -static void ride_ratings_score_close_proximity_in_direction( - RideRating::UpdateState& state, TileElement* inputTileElement, int32_t direction) -{ - auto scorePos = CoordsXY{ CoordsXY{ state.Proximity } + CoordsDirectionDelta[direction] }; - if (!MapIsLocationValid(scorePos)) - return; - - TileElement* tileElement = MapGetFirstElementAt(scorePos); - if (tileElement == nullptr) - return; - do - { - if (tileElement->isGhost()) - continue; - - switch (tileElement->getType()) - { - case TileElementType::surface: - if (state.ProximityBaseHeight <= inputTileElement->baseHeight) - { - if (inputTileElement->clearanceHeight <= tileElement->baseHeight) + case TileElementType::surface: + if (state.ProximityBaseHeight <= inputTileElement->baseHeight) { - proximity_score_increment(state, PROXIMITY_SURFACE_SIDE_CLOSE); + if (inputTileElement->clearanceHeight <= tileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_SURFACE_SIDE_CLOSE); + } } - } - break; - case TileElementType::path: - if (abs(inputTileElement->getBaseZ() - tileElement->getBaseZ()) <= 2 * kCoordsZStep) - { - proximity_score_increment(state, PROXIMITY_PATH_SIDE_CLOSE); - } - break; - case TileElementType::track: - if (inputTileElement->asTrack()->GetRideIndex() != tileElement->asTrack()->GetRideIndex()) - { + break; + case TileElementType::path: if (abs(inputTileElement->getBaseZ() - tileElement->getBaseZ()) <= 2 * kCoordsZStep) { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE); + proximity_score_increment(state, PROXIMITY_PATH_SIDE_CLOSE); } - } - break; - case TileElementType::smallScenery: - case TileElementType::largeScenery: - if (tileElement->getBaseZ() < inputTileElement->getClearanceZ()) - { - if (inputTileElement->getBaseZ() > tileElement->getClearanceZ()) + break; + case TileElementType::track: + if (inputTileElement->asTrack()->GetRideIndex() != tileElement->asTrack()->GetRideIndex()) { - proximity_score_increment(state, PROXIMITY_SCENERY_SIDE_ABOVE); + if (abs(inputTileElement->getBaseZ() - tileElement->getBaseZ()) <= 2 * kCoordsZStep) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE); + } } - else + break; + case TileElementType::smallScenery: + case TileElementType::largeScenery: + if (tileElement->getBaseZ() < inputTileElement->getClearanceZ()) { - proximity_score_increment(state, PROXIMITY_SCENERY_SIDE_BELOW); + if (inputTileElement->getBaseZ() > tileElement->getClearanceZ()) + { + proximity_score_increment(state, PROXIMITY_SCENERY_SIDE_ABOVE); + } + else + { + proximity_score_increment(state, PROXIMITY_SCENERY_SIDE_BELOW); + } } - } - break; - default: - break; - } - } while (!(tileElement++)->isLastForTile()); -} - -static void ride_ratings_score_close_proximity_loops_helper(RideRating::UpdateState& state, const CoordsXYE& coordsElement) -{ - TileElement* tileElement = MapGetFirstElementAt(coordsElement); - if (tileElement == nullptr) - return; - do - { - if (tileElement->isGhost()) - continue; - - auto type = tileElement->getType(); - if (type == TileElementType::path) - { - int32_t zDiff = static_cast(tileElement->baseHeight) - - static_cast(coordsElement.element->baseHeight); - if (zDiff >= 0 && zDiff <= 16) - { - proximity_score_increment(state, PROXIMITY_PATH_THROUGH_VERTICAL_LOOP); + break; + default: + break; } - } - else if (type == TileElementType::track) + } while (!(tileElement++)->isLastForTile()); + } + + static void ride_ratings_score_close_proximity_loops_helper(RideRating::UpdateState& state, const CoordsXYE& coordsElement) + { + TileElement* tileElement = MapGetFirstElementAt(coordsElement); + if (tileElement == nullptr) + return; + do { - bool elementsAreAt90DegAngle = ((tileElement->getDirection() ^ coordsElement.element->getDirection()) & 1) != 0; - if (elementsAreAt90DegAngle) + if (tileElement->isGhost()) + continue; + + auto type = tileElement->getType(); + if (type == TileElementType::path) { int32_t zDiff = static_cast(tileElement->baseHeight) - static_cast(coordsElement.element->baseHeight); if (zDiff >= 0 && zDiff <= 16) { - proximity_score_increment(state, PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP); - if (tileElement->asTrack()->GetTrackType() == TrackElemType::leftVerticalLoop - || tileElement->asTrack()->GetTrackType() == TrackElemType::rightVerticalLoop) + proximity_score_increment(state, PROXIMITY_PATH_THROUGH_VERTICAL_LOOP); + } + } + else if (type == TileElementType::track) + { + bool elementsAreAt90DegAngle = ((tileElement->getDirection() ^ coordsElement.element->getDirection()) & 1) != 0; + if (elementsAreAt90DegAngle) + { + int32_t zDiff = static_cast(tileElement->baseHeight) + - static_cast(coordsElement.element->baseHeight); + if (zDiff >= 0 && zDiff <= 16) { - proximity_score_increment(state, PROXIMITY_INTERSECTING_VERTICAL_LOOP); + proximity_score_increment(state, PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP); + if (tileElement->asTrack()->GetTrackType() == TrackElemType::leftVerticalLoop + || tileElement->asTrack()->GetTrackType() == TrackElemType::rightVerticalLoop) + { + proximity_score_increment(state, PROXIMITY_INTERSECTING_VERTICAL_LOOP); + } } } } - } - } while (!(tileElement++)->isLastForTile()); -} - -/** - * - * rct2: 0x006B62DA - */ -static void ride_ratings_score_close_proximity_loops(RideRating::UpdateState& state, TileElement* inputTileElement) -{ - auto trackType = inputTileElement->asTrack()->GetTrackType(); - if (trackType == TrackElemType::leftVerticalLoop || trackType == TrackElemType::rightVerticalLoop) - { - ride_ratings_score_close_proximity_loops_helper(state, { state.Proximity, inputTileElement }); - - int32_t direction = inputTileElement->getDirection(); - ride_ratings_score_close_proximity_loops_helper( - state, { CoordsXY{ state.Proximity } + CoordsDirectionDelta[direction], inputTileElement }); - } -} - -/** - * - * rct2: 0x006B5F9D - */ -static void ride_ratings_score_close_proximity(RideRating::UpdateState& state, TileElement* inputTileElement) -{ - if (state.StationFlags & RIDE_RATING_STATION_FLAG_NO_ENTRANCE) - { - return; + } while (!(tileElement++)->isLastForTile()); } - state.ProximityTotal++; - TileElement* tileElement = MapGetFirstElementAt(state.Proximity); - if (tileElement == nullptr) - return; - do + /** + * + * rct2: 0x006B62DA + */ + static void ride_ratings_score_close_proximity_loops(RideRating::UpdateState& state, TileElement* inputTileElement) { - if (tileElement->isGhost()) - continue; - - int32_t waterHeight; - switch (tileElement->getType()) + auto trackType = inputTileElement->asTrack()->GetTrackType(); + if (trackType == TrackElemType::leftVerticalLoop || trackType == TrackElemType::rightVerticalLoop) { - case TileElementType::surface: - state.ProximityBaseHeight = tileElement->baseHeight; - if (tileElement->getBaseZ() == state.Proximity.z) - { - proximity_score_increment(state, PROXIMITY_SURFACE_TOUCH); - } - waterHeight = tileElement->asSurface()->GetWaterHeight(); - if (waterHeight != 0) - { - auto z = waterHeight; - if (z <= state.Proximity.z) + ride_ratings_score_close_proximity_loops_helper(state, { state.Proximity, inputTileElement }); + + int32_t direction = inputTileElement->getDirection(); + ride_ratings_score_close_proximity_loops_helper( + state, { CoordsXY{ state.Proximity } + CoordsDirectionDelta[direction], inputTileElement }); + } + } + + /** + * + * rct2: 0x006B5F9D + */ + static void ride_ratings_score_close_proximity(RideRating::UpdateState& state, TileElement* inputTileElement) + { + if (state.StationFlags & RIDE_RATING_STATION_FLAG_NO_ENTRANCE) + { + return; + } + + state.ProximityTotal++; + TileElement* tileElement = MapGetFirstElementAt(state.Proximity); + if (tileElement == nullptr) + return; + do + { + if (tileElement->isGhost()) + continue; + + int32_t waterHeight; + switch (tileElement->getType()) + { + case TileElementType::surface: + state.ProximityBaseHeight = tileElement->baseHeight; + if (tileElement->getBaseZ() == state.Proximity.z) { - proximity_score_increment(state, PROXIMITY_WATER_OVER); - if (z == state.Proximity.z) - { - proximity_score_increment(state, PROXIMITY_WATER_TOUCH); - } - z += 16; - if (z == state.Proximity.z) - { - proximity_score_increment(state, PROXIMITY_WATER_LOW); - } - z += 112; + proximity_score_increment(state, PROXIMITY_SURFACE_TOUCH); + } + waterHeight = tileElement->asSurface()->GetWaterHeight(); + if (waterHeight != 0) + { + auto z = waterHeight; if (z <= state.Proximity.z) { - proximity_score_increment(state, PROXIMITY_WATER_HIGH); - } - } - } - break; - case TileElementType::path: - if (!tileElement->asPath()->IsQueue()) - { - if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) - { - proximity_score_increment(state, PROXIMITY_PATH_TOUCH_ABOVE); - } - if (tileElement->getBaseZ() == inputTileElement->getClearanceZ()) - { - proximity_score_increment(state, PROXIMITY_PATH_TOUCH_UNDER); - } - } - else - { - if (tileElement->getClearanceZ() <= inputTileElement->getBaseZ()) - { - proximity_score_increment(state, PROXIMITY_QUEUE_PATH_OVER); - } - if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) - { - proximity_score_increment(state, PROXIMITY_QUEUE_PATH_TOUCH_ABOVE); - } - if (tileElement->getBaseZ() == inputTileElement->getClearanceZ()) - { - proximity_score_increment(state, PROXIMITY_QUEUE_PATH_TOUCH_UNDER); - } - } - break; - case TileElementType::track: - { - auto trackType = tileElement->asTrack()->GetTrackType(); - if (trackType == TrackElemType::leftVerticalLoop || trackType == TrackElemType::rightVerticalLoop) - { - int32_t sequence = tileElement->asTrack()->GetSequenceIndex(); - if (sequence == 3 || sequence == 6) - { - if (tileElement->baseHeight - inputTileElement->clearanceHeight <= 10) - { - proximity_score_increment(state, PROXIMITY_THROUGH_VERTICAL_LOOP); - } - } - } - if (inputTileElement->asTrack()->GetRideIndex() != tileElement->asTrack()->GetRideIndex()) - { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW); - if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) - { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE); - } - if (tileElement->clearanceHeight + 2 <= inputTileElement->baseHeight) - { - if (tileElement->clearanceHeight + 10 >= inputTileElement->baseHeight) - { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE); - } - } - if (inputTileElement->clearanceHeight == tileElement->baseHeight) - { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE); - } - if (inputTileElement->clearanceHeight + 2 == tileElement->baseHeight) - { - if (static_cast(inputTileElement->clearanceHeight + 10) >= tileElement->baseHeight) - { - proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE); - } - } - } - else - { - bool isStation = tileElement->asTrack()->IsStation(); - if (tileElement->clearanceHeight == inputTileElement->baseHeight) - { - proximity_score_increment(state, PROXIMITY_OWN_TRACK_TOUCH_ABOVE); - if (isStation) - { - proximity_score_increment(state, PROXIMITY_OWN_STATION_TOUCH_ABOVE); - } - } - if (tileElement->clearanceHeight + 2 <= inputTileElement->baseHeight) - { - if (tileElement->clearanceHeight + 10 >= inputTileElement->baseHeight) - { - proximity_score_increment(state, PROXIMITY_OWN_TRACK_CLOSE_ABOVE); - if (isStation) + proximity_score_increment(state, PROXIMITY_WATER_OVER); + if (z == state.Proximity.z) { - proximity_score_increment(state, PROXIMITY_OWN_STATION_CLOSE_ABOVE); + proximity_score_increment(state, PROXIMITY_WATER_TOUCH); + } + z += 16; + if (z == state.Proximity.z) + { + proximity_score_increment(state, PROXIMITY_WATER_LOW); + } + z += 112; + if (z <= state.Proximity.z) + { + proximity_score_increment(state, PROXIMITY_WATER_HIGH); } } } - - if (inputTileElement->getClearanceZ() == tileElement->getBaseZ()) + break; + case TileElementType::path: + if (!tileElement->asPath()->IsQueue()) { - proximity_score_increment(state, PROXIMITY_OWN_TRACK_TOUCH_ABOVE); - if (isStation) + if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) { - proximity_score_increment(state, PROXIMITY_OWN_STATION_TOUCH_ABOVE); + proximity_score_increment(state, PROXIMITY_PATH_TOUCH_ABOVE); + } + if (tileElement->getBaseZ() == inputTileElement->getClearanceZ()) + { + proximity_score_increment(state, PROXIMITY_PATH_TOUCH_UNDER); } } - if (inputTileElement->clearanceHeight + 2 <= tileElement->baseHeight) + else { - if (inputTileElement->clearanceHeight + 10 >= tileElement->baseHeight) + if (tileElement->getClearanceZ() <= inputTileElement->getBaseZ()) { - proximity_score_increment(state, PROXIMITY_OWN_TRACK_CLOSE_ABOVE); - if (isStation) + proximity_score_increment(state, PROXIMITY_QUEUE_PATH_OVER); + } + if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) + { + proximity_score_increment(state, PROXIMITY_QUEUE_PATH_TOUCH_ABOVE); + } + if (tileElement->getBaseZ() == inputTileElement->getClearanceZ()) + { + proximity_score_increment(state, PROXIMITY_QUEUE_PATH_TOUCH_UNDER); + } + } + break; + case TileElementType::track: + { + auto trackType = tileElement->asTrack()->GetTrackType(); + if (trackType == TrackElemType::leftVerticalLoop || trackType == TrackElemType::rightVerticalLoop) + { + int32_t sequence = tileElement->asTrack()->GetSequenceIndex(); + if (sequence == 3 || sequence == 6) + { + if (tileElement->baseHeight - inputTileElement->clearanceHeight <= 10) { - proximity_score_increment(state, PROXIMITY_OWN_STATION_CLOSE_ABOVE); + proximity_score_increment(state, PROXIMITY_THROUGH_VERTICAL_LOOP); } } } + if (inputTileElement->asTrack()->GetRideIndex() != tileElement->asTrack()->GetRideIndex()) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW); + if (tileElement->getClearanceZ() == inputTileElement->getBaseZ()) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE); + } + if (tileElement->clearanceHeight + 2 <= inputTileElement->baseHeight) + { + if (tileElement->clearanceHeight + 10 >= inputTileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE); + } + } + if (inputTileElement->clearanceHeight == tileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE); + } + if (inputTileElement->clearanceHeight + 2 == tileElement->baseHeight) + { + if (static_cast(inputTileElement->clearanceHeight + 10) >= tileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE); + } + } + } + else + { + bool isStation = tileElement->asTrack()->IsStation(); + if (tileElement->clearanceHeight == inputTileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_OWN_TRACK_TOUCH_ABOVE); + if (isStation) + { + proximity_score_increment(state, PROXIMITY_OWN_STATION_TOUCH_ABOVE); + } + } + if (tileElement->clearanceHeight + 2 <= inputTileElement->baseHeight) + { + if (tileElement->clearanceHeight + 10 >= inputTileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_OWN_TRACK_CLOSE_ABOVE); + if (isStation) + { + proximity_score_increment(state, PROXIMITY_OWN_STATION_CLOSE_ABOVE); + } + } + } + + if (inputTileElement->getClearanceZ() == tileElement->getBaseZ()) + { + proximity_score_increment(state, PROXIMITY_OWN_TRACK_TOUCH_ABOVE); + if (isStation) + { + proximity_score_increment(state, PROXIMITY_OWN_STATION_TOUCH_ABOVE); + } + } + if (inputTileElement->clearanceHeight + 2 <= tileElement->baseHeight) + { + if (inputTileElement->clearanceHeight + 10 >= tileElement->baseHeight) + { + proximity_score_increment(state, PROXIMITY_OWN_TRACK_CLOSE_ABOVE); + if (isStation) + { + proximity_score_increment(state, PROXIMITY_OWN_STATION_CLOSE_ABOVE); + } + } + } + } + break; } - break; - } - default: - break; - } // switch tileElement->getType - } while (!(tileElement++)->isLastForTile()); + default: + break; + } // switch tileElement->getType + } while (!(tileElement++)->isLastForTile()); - uint8_t direction = inputTileElement->getDirection(); - ride_ratings_score_close_proximity_in_direction(state, inputTileElement, (direction + 1) & 3); - ride_ratings_score_close_proximity_in_direction(state, inputTileElement, (direction - 1) & 3); - ride_ratings_score_close_proximity_loops(state, inputTileElement); + uint8_t direction = inputTileElement->getDirection(); + ride_ratings_score_close_proximity_in_direction(state, inputTileElement, (direction + 1) & 3); + ride_ratings_score_close_proximity_in_direction(state, inputTileElement, (direction - 1) & 3); + ride_ratings_score_close_proximity_loops(state, inputTileElement); - if (trackTypeIsBrakes(state.ProximityTrackType)) - state.AmountOfBrakes++; - else if (trackTypeIsBooster(state.ProximityTrackType)) - state.amountOfBoosters++; - else if (trackTypeIsReverser(state.ProximityTrackType)) - state.AmountOfReversers++; -} - -static void RideRatingsCalculate(RideRating::UpdateState& state, Ride& ride) -{ - const auto& rrd = ride.getRideTypeDescriptor().RatingsData; - - switch (rrd.Type) - { - case RatingsCalculationType::normal: - if (!ride.flags.has(RideFlag::tested)) - return; - break; - case RatingsCalculationType::flatRide: - ride.flags.set(RideFlag::tested, RideFlag::noRawStats); - break; - case RatingsCalculationType::stall: - ride.upkeepCost = RideComputeUpkeep(state, ride); - ride.windowInvalidateFlags.set(RideInvalidateFlag::income); - // Exit ratings - return; + if (trackTypeIsBrakes(state.ProximityTrackType)) + state.AmountOfBrakes++; + else if (trackTypeIsBooster(state.ProximityTrackType)) + state.amountOfBoosters++; + else if (trackTypeIsReverser(state.ProximityTrackType)) + state.AmountOfReversers++; } - ride.unreliabilityFactor = rrd.Unreliability; - SetUnreliabilityFactor(ride); - - const auto shelteredEighths = GetNumOfShelteredEighths(ride); - ride.shelteredEighths = (rrd.RideShelter == kDynamicRideShelterRating) ? shelteredEighths.TotalShelteredEighths - : rrd.RideShelter; - - RideRating::Tuple ratings = rrd.BaseRatings; - // Apply Modifiers - for (const auto& modifier : rrd.Modifiers) + static void RideRatingsCalculate(RideRating::UpdateState& state, Ride& ride) { - switch (modifier.type) + const auto& rrd = ride.getRideTypeDescriptor().RatingsData; + + switch (rrd.Type) { - case RatingsModifierType::bonusLength: - RideRatingsApplyBonusLength(ratings, ride, modifier); + case RatingsCalculationType::normal: + if (!ride.flags.has(RideFlag::tested)) + return; break; - case RatingsModifierType::bonusSynchronisation: - RideRatingsApplyBonusSynchronisation(ratings, ride, modifier); - break; - case RatingsModifierType::bonusTrainLength: - RideRatingsApplyBonusTrainLength(ratings, ride, modifier); - break; - case RatingsModifierType::bonusMaxSpeed: - RideRatingsApplyBonusMaxSpeed(ratings, ride, modifier); - break; - case RatingsModifierType::bonusAverageSpeed: - RideRatingsApplyBonusAverageSpeed(ratings, ride, modifier); - break; - case RatingsModifierType::bonusDuration: - RideRatingsApplyBonusDuration(ratings, ride, modifier); - break; - case RatingsModifierType::bonusGForces: - RideRatingsApplyBonusGForces(ratings, ride, modifier); - break; - case RatingsModifierType::bonusTurns: - RideRatingsApplyBonusTurns(ratings, ride, modifier); - break; - case RatingsModifierType::bonusDrops: - RideRatingsApplyBonusDrops(ratings, ride, modifier); - break; - case RatingsModifierType::bonusSheltered: - RideRatingsApplyBonusSheltered(ratings, ride, modifier); - break; - case RatingsModifierType::bonusProximity: - RideRatingsApplyBonusProximity(ratings, ride, state, modifier); - break; - case RatingsModifierType::bonusScenery: - RideRatingsApplyBonusScenery(ratings, ride, modifier); - break; - case RatingsModifierType::bonusRotations: - RideRatingsApplyBonusRotations(ratings, ride, modifier); - break; - case RatingsModifierType::bonusOperationOption: - RideRatingsApplyBonusOperationOption(ratings, ride, modifier); - break; - case RatingsModifierType::bonusReversedTrains: - RideRatingsApplyBonusReversedTrains(ratings, ride, modifier); - break; - case RatingsModifierType::bonusGoKartRace: - RideRatingsApplyBonusGoKartRace(ratings, ride, modifier); - break; - case RatingsModifierType::bonusTowerRide: - RideRatingsApplyBonusTowerRide(ratings, ride, modifier); - break; - case RatingsModifierType::bonusRotoDrop: - RideRatingsApplyBonusRotoDrop(ratings, ride); - break; - case RatingsModifierType::bonusMazeSize: - RideRatingsApplyBonusMazeSize(ratings, ride, modifier); - break; - case RatingsModifierType::bonusBoatHireNoCircuit: - RideRatingsApplyBonusBoatHireNoCircuit(ratings, ride, modifier); - break; - case RatingsModifierType::bonusSlideUnlimitedRides: - RideRatingsApplyBonusSlideUnlimitedRides(ratings, ride, modifier); - break; - case RatingsModifierType::bonusMotionSimulatorMode: - RideRatingsApplyBonusMotionSimulatorMode(ratings, ride, modifier); - break; - case RatingsModifierType::bonus3DCinemaMode: - RideRatingsApplyBonus3DCinemaMode(ratings, ride, modifier); - break; - case RatingsModifierType::bonusTopSpinMode: - RideRatingsApplyBonusTopSpinMode(ratings, ride, modifier); - break; - case RatingsModifierType::bonusReversals: - RideRatingsApplyBonusReversals(ratings, ride, state, modifier); - break; - case RatingsModifierType::bonusHoles: - RideRatingsApplyBonusHoles(ratings, ride, modifier); - break; - case RatingsModifierType::bonusNumTrains: - RideRatingsApplyBonusNumTrains(ratings, ride, modifier); - break; - case RatingsModifierType::bonusDownwardLaunch: - RideRatingsApplyBonusDownwardLaunch(ratings, ride, modifier); - break; - case RatingsModifierType::bonusLaunchedFreefallSpecial: - RideRatingsApplyBonusLaunchedFreefallSpecial(ratings, ride, state, modifier); - break; - case RatingsModifierType::requirementLength: - RideRatingsApplyRequirementLength(ratings, ride, modifier); - break; - case RatingsModifierType::requirementMaxSpeed: - RideRatingsApplyRequirementMaxSpeed(ratings, ride, modifier); - break; - case RatingsModifierType::requirementLateralGs: - RideRatingsApplyRequirementLateralGs(ratings, ride, modifier); - break; - case RatingsModifierType::requirementInversions: - RideRatingsApplyRequirementInversions(ratings, ride, modifier); - break; - case RatingsModifierType::requirementUnsheltered: - RideRatingsApplyRequirementUnsheltered(ratings, ride, shelteredEighths.TrackShelteredEighths, modifier); - break; - case RatingsModifierType::requirementReversals: - RideRatingsApplyRequirementReversals(ratings, ride, state, modifier); - break; - case RatingsModifierType::requirementHoles: - RideRatingsApplyRequirementHoles(ratings, ride, modifier); - break; - case RatingsModifierType::requirementStations: - RideRatingsApplyRequirementStations(ratings, ride, modifier); - break; - case RatingsModifierType::requirementSplashdown: - RideRatingsApplyRequirementSplashdown(ratings, ride, modifier); - break; - case RatingsModifierType::penaltyLateralGs: - RideRatingsApplyPenaltyLateralGs(ratings, ride, modifier); - break; - default: + case RatingsCalculationType::flatRide: + ride.flags.set(RideFlag::tested, RideFlag::noRawStats); break; + case RatingsCalculationType::stall: + ride.upkeepCost = RideComputeUpkeep(state, ride); + ride.windowInvalidateFlags.set(RideInvalidateFlag::income); + // Exit ratings + return; } - // Requirements that may be ignored if the ride has inversions - if (ride.numInversions == 0 || !rrd.RelaxRequirementsIfInversions) + ride.unreliabilityFactor = rrd.Unreliability; + SetUnreliabilityFactor(ride); + + const auto shelteredEighths = GetNumOfShelteredEighths(ride); + ride.shelteredEighths = (rrd.RideShelter == kDynamicRideShelterRating) ? shelteredEighths.TotalShelteredEighths + : rrd.RideShelter; + + RideRating::Tuple ratings = rrd.BaseRatings; + // Apply Modifiers + for (const auto& modifier : rrd.Modifiers) { switch (modifier.type) { - case RatingsModifierType::requirementDropHeight: - RideRatingsApplyRequirementDropHeight(ratings, ride, modifier); + case RatingsModifierType::bonusLength: + RideRatingsApplyBonusLength(ratings, ride, modifier); break; - case RatingsModifierType::requirementNumDrops: - RideRatingsApplyRequirementNumDrops(ratings, ride, modifier); + case RatingsModifierType::bonusSynchronisation: + RideRatingsApplyBonusSynchronisation(ratings, ride, modifier); break; - case RatingsModifierType::requirementNegativeGs: - RideRatingsApplyRequirementNegativeGs(ratings, ride, modifier); + case RatingsModifierType::bonusTrainLength: + RideRatingsApplyBonusTrainLength(ratings, ride, modifier); + break; + case RatingsModifierType::bonusMaxSpeed: + RideRatingsApplyBonusMaxSpeed(ratings, ride, modifier); + break; + case RatingsModifierType::bonusAverageSpeed: + RideRatingsApplyBonusAverageSpeed(ratings, ride, modifier); + break; + case RatingsModifierType::bonusDuration: + RideRatingsApplyBonusDuration(ratings, ride, modifier); + break; + case RatingsModifierType::bonusGForces: + RideRatingsApplyBonusGForces(ratings, ride, modifier); + break; + case RatingsModifierType::bonusTurns: + RideRatingsApplyBonusTurns(ratings, ride, modifier); + break; + case RatingsModifierType::bonusDrops: + RideRatingsApplyBonusDrops(ratings, ride, modifier); + break; + case RatingsModifierType::bonusSheltered: + RideRatingsApplyBonusSheltered(ratings, ride, modifier); + break; + case RatingsModifierType::bonusProximity: + RideRatingsApplyBonusProximity(ratings, ride, state, modifier); + break; + case RatingsModifierType::bonusScenery: + RideRatingsApplyBonusScenery(ratings, ride, modifier); + break; + case RatingsModifierType::bonusRotations: + RideRatingsApplyBonusRotations(ratings, ride, modifier); + break; + case RatingsModifierType::bonusOperationOption: + RideRatingsApplyBonusOperationOption(ratings, ride, modifier); + break; + case RatingsModifierType::bonusReversedTrains: + RideRatingsApplyBonusReversedTrains(ratings, ride, modifier); + break; + case RatingsModifierType::bonusGoKartRace: + RideRatingsApplyBonusGoKartRace(ratings, ride, modifier); + break; + case RatingsModifierType::bonusTowerRide: + RideRatingsApplyBonusTowerRide(ratings, ride, modifier); + break; + case RatingsModifierType::bonusRotoDrop: + RideRatingsApplyBonusRotoDrop(ratings, ride); + break; + case RatingsModifierType::bonusMazeSize: + RideRatingsApplyBonusMazeSize(ratings, ride, modifier); + break; + case RatingsModifierType::bonusBoatHireNoCircuit: + RideRatingsApplyBonusBoatHireNoCircuit(ratings, ride, modifier); + break; + case RatingsModifierType::bonusSlideUnlimitedRides: + RideRatingsApplyBonusSlideUnlimitedRides(ratings, ride, modifier); + break; + case RatingsModifierType::bonusMotionSimulatorMode: + RideRatingsApplyBonusMotionSimulatorMode(ratings, ride, modifier); + break; + case RatingsModifierType::bonus3DCinemaMode: + RideRatingsApplyBonus3DCinemaMode(ratings, ride, modifier); + break; + case RatingsModifierType::bonusTopSpinMode: + RideRatingsApplyBonusTopSpinMode(ratings, ride, modifier); + break; + case RatingsModifierType::bonusReversals: + RideRatingsApplyBonusReversals(ratings, ride, state, modifier); + break; + case RatingsModifierType::bonusHoles: + RideRatingsApplyBonusHoles(ratings, ride, modifier); + break; + case RatingsModifierType::bonusNumTrains: + RideRatingsApplyBonusNumTrains(ratings, ride, modifier); + break; + case RatingsModifierType::bonusDownwardLaunch: + RideRatingsApplyBonusDownwardLaunch(ratings, ride, modifier); + break; + case RatingsModifierType::bonusLaunchedFreefallSpecial: + RideRatingsApplyBonusLaunchedFreefallSpecial(ratings, ride, state, modifier); + break; + case RatingsModifierType::requirementLength: + RideRatingsApplyRequirementLength(ratings, ride, modifier); + break; + case RatingsModifierType::requirementMaxSpeed: + RideRatingsApplyRequirementMaxSpeed(ratings, ride, modifier); + break; + case RatingsModifierType::requirementLateralGs: + RideRatingsApplyRequirementLateralGs(ratings, ride, modifier); + break; + case RatingsModifierType::requirementInversions: + RideRatingsApplyRequirementInversions(ratings, ride, modifier); + break; + case RatingsModifierType::requirementUnsheltered: + RideRatingsApplyRequirementUnsheltered(ratings, ride, shelteredEighths.TrackShelteredEighths, modifier); + break; + case RatingsModifierType::requirementReversals: + RideRatingsApplyRequirementReversals(ratings, ride, state, modifier); + break; + case RatingsModifierType::requirementHoles: + RideRatingsApplyRequirementHoles(ratings, ride, modifier); + break; + case RatingsModifierType::requirementStations: + RideRatingsApplyRequirementStations(ratings, ride, modifier); + break; + case RatingsModifierType::requirementSplashdown: + RideRatingsApplyRequirementSplashdown(ratings, ride, modifier); + break; + case RatingsModifierType::penaltyLateralGs: + RideRatingsApplyPenaltyLateralGs(ratings, ride, modifier); break; default: break; } - } - } - // Universl ratings adjustments - RideRatingsApplyIntensityPenalty(ratings); - RideRatingsApplyAdjustments(ride, ratings); - if (ride.ratings != ratings) - { - ride.ratings = ratings; - ride.windowInvalidateFlags.set(RideInvalidateFlag::ratings); - } - ride.upkeepCost = RideComputeUpkeep(state, ride); - ride.windowInvalidateFlags.set(RideInvalidateFlag::income); + // Requirements that may be ignored if the ride has inversions + if (ride.numInversions == 0 || !rrd.RelaxRequirementsIfInversions) + { + switch (modifier.type) + { + case RatingsModifierType::requirementDropHeight: + RideRatingsApplyRequirementDropHeight(ratings, ride, modifier); + break; + case RatingsModifierType::requirementNumDrops: + RideRatingsApplyRequirementNumDrops(ratings, ride, modifier); + break; + case RatingsModifierType::requirementNegativeGs: + RideRatingsApplyRequirementNegativeGs(ratings, ride, modifier); + break; + default: + break; + } + } + } + // Universl ratings adjustments + RideRatingsApplyIntensityPenalty(ratings); + RideRatingsApplyAdjustments(ride, ratings); + if (ride.ratings != ratings) + { + ride.ratings = ratings; + ride.windowInvalidateFlags.set(RideInvalidateFlag::ratings); + } + + ride.upkeepCost = RideComputeUpkeep(state, ride); + ride.windowInvalidateFlags.set(RideInvalidateFlag::income); #ifdef ORIGINAL_RATINGS - if (!ride.ratings.isNull()) - { - // Address underflows allowed by original RCT2 code - ride.ratings.excitement = std::max(0, ride.ratings.excitement); - ride.ratings.intensity = std::max(0, ride.ratings.intensity); - ride.ratings.nausea = std::max(0, ride.ratings.nausea); - } + if (!ride.ratings.isNull()) + { + // Address underflows allowed by original RCT2 code + ride.ratings.excitement = std::max(0, ride.ratings.excitement); + ride.ratings.intensity = std::max(0, ride.ratings.intensity); + ride.ratings.nausea = std::max(0, ride.ratings.nausea); + } #endif #ifdef ENABLE_SCRIPTING - // Only call the 'ride.ratings.calculate' API hook if testing of the ride is complete - if (ride.flags.has(RideFlag::tested)) - { - auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); - if (hookEngine.HasSubscriptions(HookType::rideRatingsCalculate)) + // Only call the 'ride.ratings.calculate' API hook if testing of the ride is complete + if (ride.flags.has(RideFlag::tested)) { - auto ctx = GetContext()->GetScriptEngine().GetContext(); - auto originalRatings = ride.ratings; - - // Create event args object - JSValue obj = JS_NewObject(ctx); - JS_SetPropertyStr(ctx, obj, "rideId", JS_NewInt32(ctx, ride.id.ToUnderlying())); - JS_SetPropertyStr(ctx, obj, "excitement", JS_NewInt32(ctx, originalRatings.excitement)); - JS_SetPropertyStr(ctx, obj, "intensity", JS_NewInt32(ctx, originalRatings.intensity)); - JS_SetPropertyStr(ctx, obj, "nausea", JS_NewInt32(ctx, originalRatings.nausea)); - - // Call the subscriptions - hookEngine.Call(HookType::rideRatingsCalculate, obj, true, true); - - auto scriptExcitement = AsOrDefault(ctx, obj, "excitement", static_cast(originalRatings.excitement)); - auto scriptIntensity = AsOrDefault(ctx, obj, "intensity", static_cast(originalRatings.intensity)); - auto scriptNausea = AsOrDefault(ctx, obj, "nausea", static_cast(originalRatings.nausea)); - JS_FreeValue(ctx, obj); - - ride.ratings.excitement = std::clamp(scriptExcitement, 0, INT16_MAX); - ride.ratings.intensity = std::clamp(scriptIntensity, 0, INT16_MAX); - ride.ratings.nausea = std::clamp(scriptNausea, 0, INT16_MAX); - } - } -#endif -} - -static void RideRatingsCalculateValue(Ride& ride) -{ - struct Row - { - int32_t months, multiplier, divisor, summand; - }; - static constexpr auto kAgeTable = std::to_array({ - { 5, 1, 1, 30 }, // +30 - { 13, 1, 1, 10 }, // +10 - { 40, 1, 1, 0 }, // 1x - { 64, 3, 4, 0 }, // 0.75x - { 88, 9, 16, 0 }, // 0.56x - { 104, 27, 64, 0 }, // 0.42x - { 120, 81, 256, 0 }, // 0.32x - { 128, 81, 512, 0 }, // 0.16x - { 200, 81, 1024, 0 }, // 0.08x - { 200, 9, 16, 0 }, // 0.56x "easter egg" - }); - - if (!RideHasRatings(ride)) - { - return; - } - - // Start with the base ratings, multiplied by the ride type specific weights for excitement, intensity and nausea. - const auto& ratingsMultipliers = ride.getRideTypeDescriptor().RatingsMultipliers; - money64 value = (((ride.ratings.excitement * ratingsMultipliers.excitement) * 32) >> 15) - + (((ride.ratings.intensity * ratingsMultipliers.intensity) * 32) >> 15) - + (((ride.ratings.nausea * ratingsMultipliers.nausea) * 32) >> 15); - - int32_t monthsOld = 0; - if (!getGameState().cheats.disableRideValueAging) - { - monthsOld = ride.getAge(); - } - - Row lastRow = kAgeTable[kAgeTable.size() - 1]; - - // Ride is older than oldest age in the table? - if (monthsOld >= lastRow.months) - { - value = (value * lastRow.multiplier) / lastRow.divisor + lastRow.summand; - } - else - { - // Find the first hit in the table that matches this ride's age - for (const Row& curr : kAgeTable) - { - if (monthsOld < curr.months) + auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine(); + if (hookEngine.HasSubscriptions(HookType::rideRatingsCalculate)) { - value = (value * curr.multiplier) / curr.divisor + curr.summand; - break; + auto ctx = GetContext()->GetScriptEngine().GetContext(); + auto originalRatings = ride.ratings; + + // Create event args object + JSValue obj = JS_NewObject(ctx); + JS_SetPropertyStr(ctx, obj, "rideId", JS_NewInt32(ctx, ride.id.ToUnderlying())); + JS_SetPropertyStr(ctx, obj, "excitement", JS_NewInt32(ctx, originalRatings.excitement)); + JS_SetPropertyStr(ctx, obj, "intensity", JS_NewInt32(ctx, originalRatings.intensity)); + JS_SetPropertyStr(ctx, obj, "nausea", JS_NewInt32(ctx, originalRatings.nausea)); + + // Call the subscriptions + hookEngine.Call(HookType::rideRatingsCalculate, obj, true, true); + + auto scriptExcitement = AsOrDefault(ctx, obj, "excitement", static_cast(originalRatings.excitement)); + auto scriptIntensity = AsOrDefault(ctx, obj, "intensity", static_cast(originalRatings.intensity)); + auto scriptNausea = AsOrDefault(ctx, obj, "nausea", static_cast(originalRatings.nausea)); + JS_FreeValue(ctx, obj); + + ride.ratings.excitement = std::clamp(scriptExcitement, 0, INT16_MAX); + ride.ratings.intensity = std::clamp(scriptIntensity, 0, INT16_MAX); + ride.ratings.nausea = std::clamp(scriptNausea, 0, INT16_MAX); } } +#endif } - // Other ride of same type penalty - const auto& gameState = getGameState(); - const auto& rideManager = RideManager(gameState); - auto rideType = ride.type; - auto otherRidesOfSameType = std::count_if(rideManager.begin(), rideManager.end(), [rideType](const Ride& r) { - return r.status == RideStatus::open && r.type == rideType; - }); - if (otherRidesOfSameType > 1) - value -= value / 4; - - ride.value = std::max(0.00_GBP, value); -} - -/** - * I think this function computes ride upkeep? Though it is weird that the - * rct2: Sub65E621 - * inputs - * - edi: ride ptr - */ -static money64 RideComputeUpkeep(RideRating::UpdateState& state, const Ride& ride) -{ - // data stored at 0x0057E3A8, incrementing 18 bytes at a time - auto upkeep = ride.getRideTypeDescriptor().UpkeepCosts.BaseCost; - - auto trackCost = ride.getRideTypeDescriptor().UpkeepCosts.CostPerTrackPiece; - upkeep += trackCost * ride.numPoweredLifts; - - uint32_t totalLength = ToHumanReadableRideLength(ride.getTotalLength()); - - // The data originally here was 20's and 0's. The 20's all represented - // rides that had tracks. The 0's were fixed rides like crooked house or - // dodgems. - // Data source is 0x0097E3AC - totalLength *= ride.getRideTypeDescriptor().UpkeepCosts.TrackLengthMultiplier; - upkeep += static_cast(totalLength >> 10); - - if (ride.flags.has(RideFlag::onRidePhoto)) + static void RideRatingsCalculateValue(Ride& ride) { - // The original code read from a table starting at 0x0097E3AE and - // incrementing by 0x12 bytes between values. However, all of these - // values were 40. I have replaced the table lookup with the constant - // 40 in this case. - upkeep += 40; - } - - // Add maintenance cost for reverser track pieces - upkeep += 10 * state.AmountOfReversers; - - // Add maintenance cost for brake track pieces - upkeep += 20 * state.AmountOfBrakes; - - // Add maintenance cost for booster track pieces - upkeep += 80 * state.amountOfBoosters; - - // these seem to be adhoc adjustments to a ride's upkeep/cost, times - // various variables set on the ride itself. - - // https://gist.github.com/kevinburke/e19b803cd2769d96c540 - upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerTrain * ride.numTrains; - upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerCar * ride.numCarsPerTrain; - - // slight upkeep boosts for some rides - 5 for mini railway, 10 for log - // flume/rapids, 10 for roller coaster, 28 for giga coaster - upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerStation * ride.numStations; - - if (ride.mode == RideMode::reverseInclineLaunchedShuttle) - { - upkeep += 30; - } - else if (ride.mode == RideMode::poweredLaunchPassthrough) - { - upkeep += 160; - } - else if (ride.mode == RideMode::limPoweredLaunch) - { - upkeep += 320; - } - else if (ride.mode == RideMode::poweredLaunch || ride.mode == RideMode::poweredLaunchBlockSectioned) - { - upkeep += 220; - } - - // multiply by 5/8 - upkeep *= 10; - upkeep >>= 4; - return upkeep; -} - -/** - * - * rct2: 0x0065E7FB - * - * inputs - * - bx: excitement - * - cx: intensity - * - bp: nausea - * - edi: ride ptr - */ -static void RideRatingsApplyAdjustments(const Ride& ride, RideRating::Tuple& ratings) -{ - const auto* rideEntry = GetRideEntryByIndex(ride.subtype); - - if (rideEntry == nullptr) - { - return; - } - - // Apply ride entry multipliers - RideRatingsAdd( - ratings, ((static_cast(ratings.excitement) * rideEntry->excitement_multiplier) >> 7), - ((static_cast(ratings.intensity) * rideEntry->intensity_multiplier) >> 7), - ((static_cast(ratings.nausea) * rideEntry->nausea_multiplier) >> 7)); - - // Apply total air time -#ifdef ORIGINAL_RATINGS - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasAirTime)) - { - uint16_t totalAirTime = ride.totalAirTime; - if (rideEntry->flags.has(RideEntryFlag::limitAirTimeBonus)) + struct Row { - if (totalAirTime >= 96) + int32_t months, multiplier, divisor, summand; + }; + static constexpr auto kAgeTable = std::to_array({ + { 5, 1, 1, 30 }, // +30 + { 13, 1, 1, 10 }, // +10 + { 40, 1, 1, 0 }, // 1x + { 64, 3, 4, 0 }, // 0.75x + { 88, 9, 16, 0 }, // 0.56x + { 104, 27, 64, 0 }, // 0.42x + { 120, 81, 256, 0 }, // 0.32x + { 128, 81, 512, 0 }, // 0.16x + { 200, 81, 1024, 0 }, // 0.08x + { 200, 9, 16, 0 }, // 0.56x "easter egg" + }); + + if (!RideHasRatings(ride)) + { + return; + } + + // Start with the base ratings, multiplied by the ride type specific weights for excitement, intensity and nausea. + const auto& ratingsMultipliers = ride.getRideTypeDescriptor().RatingsMultipliers; + money64 value = (((ride.ratings.excitement * ratingsMultipliers.excitement) * 32) >> 15) + + (((ride.ratings.intensity * ratingsMultipliers.intensity) * 32) >> 15) + + (((ride.ratings.nausea * ratingsMultipliers.nausea) * 32) >> 15); + + int32_t monthsOld = 0; + if (!getGameState().cheats.disableRideValueAging) + { + monthsOld = ride.getAge(); + } + + Row lastRow = kAgeTable[kAgeTable.size() - 1]; + + // Ride is older than oldest age in the table? + if (monthsOld >= lastRow.months) + { + value = (value * lastRow.multiplier) / lastRow.divisor + lastRow.summand; + } + else + { + // Find the first hit in the table that matches this ride's age + for (const Row& curr : kAgeTable) { - totalAirTime -= 96; - ratings.excitement -= totalAirTime / 8; + if (monthsOld < curr.months) + { + value = (value * curr.multiplier) / curr.divisor + curr.summand; + break; + } + } + } + + // Other ride of same type penalty + const auto& gameState = getGameState(); + const auto& rideManager = RideManager(gameState); + auto rideType = ride.type; + auto otherRidesOfSameType = std::count_if(rideManager.begin(), rideManager.end(), [rideType](const Ride& r) { + return r.status == RideStatus::open && r.type == rideType; + }); + if (otherRidesOfSameType > 1) + value -= value / 4; + + ride.value = std::max(0.00_GBP, value); + } + + /** + * I think this function computes ride upkeep? Though it is weird that the + * rct2: Sub65E621 + * inputs + * - edi: ride ptr + */ + static money64 RideComputeUpkeep(RideRating::UpdateState& state, const Ride& ride) + { + // data stored at 0x0057E3A8, incrementing 18 bytes at a time + auto upkeep = ride.getRideTypeDescriptor().UpkeepCosts.BaseCost; + + auto trackCost = ride.getRideTypeDescriptor().UpkeepCosts.CostPerTrackPiece; + upkeep += trackCost * ride.numPoweredLifts; + + uint32_t totalLength = ToHumanReadableRideLength(ride.getTotalLength()); + + // The data originally here was 20's and 0's. The 20's all represented + // rides that had tracks. The 0's were fixed rides like crooked house or + // dodgems. + // Data source is 0x0097E3AC + totalLength *= ride.getRideTypeDescriptor().UpkeepCosts.TrackLengthMultiplier; + upkeep += static_cast(totalLength >> 10); + + if (ride.flags.has(RideFlag::onRidePhoto)) + { + // The original code read from a table starting at 0x0097E3AE and + // incrementing by 0x12 bytes between values. However, all of these + // values were 40. I have replaced the table lookup with the constant + // 40 in this case. + upkeep += 40; + } + + // Add maintenance cost for reverser track pieces + upkeep += 10 * state.AmountOfReversers; + + // Add maintenance cost for brake track pieces + upkeep += 20 * state.AmountOfBrakes; + + // Add maintenance cost for booster track pieces + upkeep += 80 * state.amountOfBoosters; + + // these seem to be adhoc adjustments to a ride's upkeep/cost, times + // various variables set on the ride itself. + + // https://gist.github.com/kevinburke/e19b803cd2769d96c540 + upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerTrain * ride.numTrains; + upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerCar * ride.numCarsPerTrain; + + // slight upkeep boosts for some rides - 5 for mini railway, 10 for log + // flume/rapids, 10 for roller coaster, 28 for giga coaster + upkeep += ride.getRideTypeDescriptor().UpkeepCosts.CostPerStation * ride.numStations; + + if (ride.mode == RideMode::reverseInclineLaunchedShuttle) + { + upkeep += 30; + } + else if (ride.mode == RideMode::poweredLaunchPassthrough) + { + upkeep += 160; + } + else if (ride.mode == RideMode::limPoweredLaunch) + { + upkeep += 320; + } + else if (ride.mode == RideMode::poweredLaunch || ride.mode == RideMode::poweredLaunchBlockSectioned) + { + upkeep += 220; + } + + // multiply by 5/8 + upkeep *= 10; + upkeep >>= 4; + return upkeep; + } + + /** + * + * rct2: 0x0065E7FB + * + * inputs + * - bx: excitement + * - cx: intensity + * - bp: nausea + * - edi: ride ptr + */ + static void RideRatingsApplyAdjustments(const Ride& ride, RideRating::Tuple& ratings) + { + const auto* rideEntry = GetRideEntryByIndex(ride.subtype); + + if (rideEntry == nullptr) + { + return; + } + + // Apply ride entry multipliers + RideRatingsAdd( + ratings, ((static_cast(ratings.excitement) * rideEntry->excitement_multiplier) >> 7), + ((static_cast(ratings.intensity) * rideEntry->intensity_multiplier) >> 7), + ((static_cast(ratings.nausea) * rideEntry->nausea_multiplier) >> 7)); + + // Apply total air time +#ifdef ORIGINAL_RATINGS + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasAirTime)) + { + uint16_t totalAirTime = ride.totalAirTime; + if (rideEntry->flags.has(RideEntryFlag::limitAirTimeBonus)) + { + if (totalAirTime >= 96) + { + totalAirTime -= 96; + ratings.excitement -= totalAirTime / 8; + ratings.nausea += totalAirTime / 16; + } + } + else + { + ratings.excitement += totalAirTime / 8; ratings.nausea += totalAirTime / 16; } } - else - { - ratings.excitement += totalAirTime / 8; - ratings.nausea += totalAirTime / 16; - } - } #else - if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasAirTime)) - { - int32_t excitementModifier; - int32_t totalAirTime = ride.totalAirTime; - if (rideEntry->flags.has(RideEntryFlag::limitAirTimeBonus)) + if (ride.getRideTypeDescriptor().flags.has(RtdFlag::hasAirTime)) { - totalAirTime = std::max(0, totalAirTime - 96); - excitementModifier = -1 * (std::min(totalAirTime, 200) / 8); - } - else - { - excitementModifier = std::min(totalAirTime, 200) / 8; - } - int32_t nauseaModifier = totalAirTime / 16; - - RideRatingsAdd(ratings, excitementModifier, 0, nauseaModifier); - } -#endif -} - -/** - * Lowers excitement, the higher the intensity. - * rct2: 0x0065E7A3 - */ -static void RideRatingsApplyIntensityPenalty(RideRating::Tuple& ratings) -{ - static constexpr RideRating_t intensityBounds[] = { 1000, 1100, 1200, 1320, 1450 }; - RideRating_t excitement = ratings.excitement; - for (auto intensityBound : intensityBounds) - { - if (ratings.intensity >= intensityBound) - { - excitement -= excitement / 4; - } - } - ratings.excitement = excitement; -} - -/** - * - * rct2: 0x00655FD6 - */ -static void SetUnreliabilityFactor(Ride& ride) -{ - const auto& rtd = ride.getRideTypeDescriptor(); - // Special unreliability for a few ride types - if (rtd.flags.has(RtdFlag::reverseInclineLaunchAffectsReliability) && ride.mode == RideMode::reverseInclineLaunchedShuttle) - { - ride.unreliabilityFactor += 10; - } - else if (rtd.flags.has(RtdFlag::poweredLaunchAffectsReliability) && ride.isPoweredLaunched()) - { - ride.unreliabilityFactor += 5; - } - else if (rtd.flags.has(RtdFlag::runningSpeedAffectsReliability)) - { - ride.unreliabilityFactor += (ride.speed * 2); - } - // The bigger the difference in lift speed and minimum the higher the unreliability - uint8_t minLiftSpeed = ride.getRideTypeDescriptor().LiftData.minimum_speed; - ride.unreliabilityFactor += (ride.liftHillSpeed - minLiftSpeed) * 2; -} - -static uint32_t get_proximity_score_helper_1(uint16_t x, uint16_t max, uint32_t multiplier) -{ - return (std::min(x, max) * multiplier) >> 16; -} - -static uint32_t get_proximity_score_helper_2(uint16_t x, uint16_t additionIfNotZero, uint16_t max, uint32_t multiplier) -{ - uint32_t result = x; - if (result != 0) - result += additionIfNotZero; - return (std::min(result, max) * multiplier) >> 16; -} - -static uint32_t get_proximity_score_helper_3(uint16_t x, uint16_t resultIfNotZero) -{ - return x == 0 ? 0 : resultIfNotZero; -} - -/** - * - * rct2: 0x0065E277 - */ -static uint32_t ride_ratings_get_proximity_score(RideRating::UpdateState& state) -{ - const uint16_t* scores = state.ProximityScores; - - uint32_t result = 0; - result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_OVER], 60, 0x00AAAA); - result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_TOUCH], 22, 0x0245D1); - result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_LOW], 10, 0x020000); - result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_HIGH], 40, 0x00A000); - result += get_proximity_score_helper_1(scores[PROXIMITY_SURFACE_TOUCH], 70, 0x01B6DB); - result += get_proximity_score_helper_1(scores[PROXIMITY_QUEUE_PATH_OVER] + 8, 12, 0x064000); - result += get_proximity_score_helper_3(scores[PROXIMITY_QUEUE_PATH_TOUCH_ABOVE], 40); - result += get_proximity_score_helper_3(scores[PROXIMITY_QUEUE_PATH_TOUCH_UNDER], 45); - result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_TOUCH_ABOVE], 10, 20, 0x03C000); - result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_TOUCH_UNDER], 10, 20, 0x044000); - result += get_proximity_score_helper_2(scores[PROXIMITY_OWN_TRACK_TOUCH_ABOVE], 10, 15, 0x035555); - result += get_proximity_score_helper_1(scores[PROXIMITY_OWN_TRACK_CLOSE_ABOVE], 5, 0x060000); - result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW], 10, 15, 0x02AAAA); - result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE], 10, 15, 0x04AAAA); - result += get_proximity_score_helper_1(scores[PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE], 5, 0x090000); - result += get_proximity_score_helper_1(scores[PROXIMITY_SCENERY_SIDE_BELOW], 35, 0x016DB6); - result += get_proximity_score_helper_1(scores[PROXIMITY_SCENERY_SIDE_ABOVE], 35, 0x00DB6D); - result += get_proximity_score_helper_3(scores[PROXIMITY_OWN_STATION_TOUCH_ABOVE], 55); - result += get_proximity_score_helper_3(scores[PROXIMITY_OWN_STATION_CLOSE_ABOVE], 25); - result += get_proximity_score_helper_2(scores[PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP], 4, 6, 0x140000); - result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_THROUGH_VERTICAL_LOOP], 4, 6, 0x0F0000); - result += get_proximity_score_helper_3(scores[PROXIMITY_INTERSECTING_VERTICAL_LOOP], 100); - result += get_proximity_score_helper_2(scores[PROXIMITY_THROUGH_VERTICAL_LOOP], 4, 6, 0x0A0000); - result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_SIDE_CLOSE], 10, 20, 0x01C000); - result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE], 10, 20, 0x024000); - result += get_proximity_score_helper_2(scores[PROXIMITY_SURFACE_SIDE_CLOSE], 10, 20, 0x028000); - return result; -} - -/** - * Calculates how much of the track is sheltered in eighths. - * rct2: 0x0065E72D - */ -static ShelteredEights GetNumOfShelteredEighths(const Ride& ride) -{ - int32_t totalLength = ride.getTotalLength(); - int32_t shelteredLength = ride.shelteredLength; - int32_t lengthEighth = totalLength / 8; - int32_t lengthCounter = lengthEighth; - uint8_t numShelteredEighths = 0; - for (int32_t i = 0; i < 7; i++) - { - if (shelteredLength >= lengthCounter) - { - lengthCounter += lengthEighth; - numShelteredEighths++; - } - } - - uint8_t trackShelteredEighths = numShelteredEighths; - const auto* rideType = GetRideEntryByIndex(ride.subtype); - if (rideType == nullptr) - { - return { 0, 0 }; - } - if (rideType->flags.has(RideEntryFlag::isACoveredRide)) - numShelteredEighths = 7; - - return { trackShelteredEighths, numShelteredEighths }; -} - -static RideRating::Tuple get_flat_turns_rating(const Ride& ride) -{ - int32_t num3PlusTurns = GetTurnCount3Elements(ride, 0); - int32_t num2Turns = GetTurnCount2Elements(ride, 0); - int32_t num1Turns = GetTurnCount1Element(ride, 0); - - RideRating::Tuple rating; - rating.excitement = (num3PlusTurns * 0x28000) >> 16; - rating.excitement += (num2Turns * 0x30000) >> 16; - rating.excitement += (num1Turns * 63421) >> 16; - - rating.intensity = (num3PlusTurns * 81920) >> 16; - rating.intensity += (num2Turns * 49152) >> 16; - rating.intensity += (num1Turns * 21140) >> 16; - - rating.nausea = (num3PlusTurns * 0x50000) >> 16; - rating.nausea += (num2Turns * 0x32000) >> 16; - rating.nausea += (num1Turns * 42281) >> 16; - - return rating; -} - -/** - * - * rct2: 0x0065DF72 - */ -static RideRating::Tuple get_banked_turns_rating(const Ride& ride) -{ - int32_t num3PlusTurns = GetTurnCount3Elements(ride, 1); - int32_t num2Turns = GetTurnCount2Elements(ride, 1); - int32_t num1Turns = GetTurnCount1Element(ride, 1); - - RideRating::Tuple rating; - rating.excitement = (num3PlusTurns * 0x3C000) >> 16; - rating.excitement += (num2Turns * 0x3C000) >> 16; - rating.excitement += (num1Turns * 73992) >> 16; - - rating.intensity = (num3PlusTurns * 0x14000) >> 16; - rating.intensity += (num2Turns * 49152) >> 16; - rating.intensity += (num1Turns * 21140) >> 16; - - rating.nausea = (num3PlusTurns * 0x50000) >> 16; - rating.nausea += (num2Turns * 0x32000) >> 16; - rating.nausea += (num1Turns * 48623) >> 16; - - return rating; -} - -/** - * - * rct2: 0x0065E047 - */ -static RideRating::Tuple get_sloped_turns_rating(const Ride& ride) -{ - RideRating::Tuple rating; - - int32_t num4PlusTurns = GetTurnCount4PlusElements(ride, 2); - int32_t num3Turns = GetTurnCount3Elements(ride, 2); - int32_t num2Turns = GetTurnCount2Elements(ride, 2); - int32_t num1Turns = GetTurnCount1Element(ride, 2); - - rating.excitement = (std::min(num4PlusTurns, 4) * 0x78000) >> 16; - rating.excitement += (std::min(num3Turns, 6) * 273066) >> 16; - rating.excitement += (std::min(num2Turns, 6) * 0x3AAAA) >> 16; - rating.excitement += (std::min(num1Turns, 7) * 187245) >> 16; - rating.intensity = 0; - rating.nausea = (std::min(num4PlusTurns, 8) * 0x78000) >> 16; - - return rating; -} - -/** - * - * rct2: 0x0065E0F2 - */ -static RideRating::Tuple getInversionsRatings(uint16_t inversions) -{ - RideRating::Tuple rating; - - rating.excitement = (std::min(inversions, 6) * 0x1AAAAA) >> 16; - rating.intensity = (inversions * 0x320000) >> 16; - rating.nausea = (inversions * 0x15AAAA) >> 16; - - return rating; -} - -void SpecialTrackElementRatingsAjustment_Default(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) -{ - if (ride.hasWaterSplash()) - { - excitement += 50; - intensity += 30; - nausea += 20; - } - if (ride.hasWaterfall()) - { - excitement += 55; - intensity += 30; - } - if (ride.hasWhirlpool()) - { - excitement += 35; - intensity += 20; - nausea += 23; - } -} - -void SpecialTrackElementRatingsAjustment_GhostTrain(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) -{ - if (ride.hasSpinningTunnel()) - { - excitement += 40; - intensity += 25; - nausea += 55; - } -} - -void SpecialTrackElementRatingsAjustment_LogFlume(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) -{ - if (ride.hasLogReverser()) - { - excitement += 48; - intensity += 55; - nausea += 65; - } -} - -static RideRating::Tuple GetSpecialTrackElementsRating(uint8_t type, const Ride& ride) -{ - int32_t excitement = 0, intensity = 0, nausea = 0; - const auto& rtd = ride.getRideTypeDescriptor(); - rtd.SpecialElementRatingAdjustment(ride, excitement, intensity, nausea); - - auto helixSections = ride.numHelices; - - int32_t helixesUpTo9 = std::min(helixSections, 9); - excitement += (helixesUpTo9 * 254862) >> 16; - - int32_t helixesUpTo11 = std::min(helixSections, 11); - intensity += (helixesUpTo11 * 148945) >> 16; - - int32_t helixesOver5UpTo10 = std::clamp(helixSections - 5, 0, 10); - nausea += (helixesOver5UpTo10 * 0x140000) >> 16; - - RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), - static_cast(nausea) }; - return rating; -} - -/** - * - * rct2: 0x0065DDD1 - */ -static RideRating::Tuple ride_ratings_get_turns_ratings(const Ride& ride) -{ - int32_t excitement = 0, intensity = 0, nausea = 0; - - RideRating::Tuple specialTrackElementsRating = GetSpecialTrackElementsRating(ride.type, ride); - excitement += specialTrackElementsRating.excitement; - intensity += specialTrackElementsRating.intensity; - nausea += specialTrackElementsRating.nausea; - - RideRating::Tuple flatTurnsRating = get_flat_turns_rating(ride); - excitement += flatTurnsRating.excitement; - intensity += flatTurnsRating.intensity; - nausea += flatTurnsRating.nausea; - - RideRating::Tuple bankedTurnsRating = get_banked_turns_rating(ride); - excitement += bankedTurnsRating.excitement; - intensity += bankedTurnsRating.intensity; - nausea += bankedTurnsRating.nausea; - - RideRating::Tuple slopedTurnsRating = get_sloped_turns_rating(ride); - excitement += slopedTurnsRating.excitement; - intensity += slopedTurnsRating.intensity; - nausea += slopedTurnsRating.nausea; - - RideRating::Tuple inversionsRating = getInversionsRatings(ride.numInversions); - excitement += inversionsRating.excitement; - intensity += inversionsRating.intensity; - nausea += inversionsRating.nausea; - - RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), - static_cast(nausea) }; - return rating; -} - -/** - * - * rct2: 0x0065E1C2 - */ -static RideRating::Tuple ride_ratings_get_sheltered_ratings(const Ride& ride) -{ - int32_t shelteredLengthShifted = (ride.shelteredLength) >> 16; - - uint32_t shelteredLengthUpTo1000 = std::min(shelteredLengthShifted, 1000); - uint32_t shelteredLengthUpTo2000 = std::min(shelteredLengthShifted, 2000); - - int32_t excitement = (shelteredLengthUpTo1000 * 9175) >> 16; - int32_t intensity = (shelteredLengthUpTo2000 * 0x2666) >> 16; - int32_t nausea = (shelteredLengthUpTo1000 * 0x4000) >> 16; - - /*eax = (ride.var11C * 30340) >> 16;*/ - /*nausea += eax;*/ - - if (ride.numShelteredSections & ShelteredSectionsBits::kBankingWhileSheltered) - { - excitement += 20; - nausea += 15; - } - - if (ride.numShelteredSections & ShelteredSectionsBits::kRotatingWhileSheltered) - { - excitement += 20; - nausea += 15; - } - - uint8_t lowerVal = ride.getNumShelteredSections(); - lowerVal = std::min(lowerVal, 11); - excitement += (lowerVal * 774516) >> 16; - - RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), - static_cast(nausea) }; - return rating; -} - -/** - * - * rct2: 0x0065DCDC - */ -static RideRating::Tuple ride_ratings_get_gforce_ratings(const Ride& ride) -{ - RideRating::Tuple result = { - .excitement = 0, - .intensity = 0, - .nausea = 0, - }; - - // Apply maximum positive G force factor - result.excitement += (ride.maxPositiveVerticalG * 5242) >> 16; - result.intensity += (ride.maxPositiveVerticalG * 52428) >> 16; - result.nausea += (ride.maxPositiveVerticalG * 17039) >> 16; - - // Apply maximum negative G force factor - fixed16_2dp gforce = ride.maxNegativeVerticalG; - result.excitement += (std::clamp(gforce, -RideRating::make(2, 50), RideRating::make(0, 00)) * -15728) >> 16; - result.intensity += ((gforce - RideRating::make(1, 00)) * -52428) >> 16; - result.nausea += ((gforce - RideRating::make(1, 00)) * -14563) >> 16; - - // Apply lateral G force factor - result.excitement += (std::min(RideRating::make(1, 50), ride.maxLateralG) * 26214) >> 16; - result.intensity += ride.maxLateralG; - result.nausea += (ride.maxLateralG * 21845) >> 16; - -// Very high lateral G force penalty -#ifdef ORIGINAL_RATINGS - if (ride.maxLateralG > MakeFixed16_2dp(2, 80)) - { - result.intensity += RideRating::make(3, 75); - result.nausea += RideRating::make(2, 00); - } - if (ride.maxLateralG > MakeFixed16_2dp(3, 10)) - { - result.excitement /= 2; - result.intensity += RideRating::make(8, 50); - result.nausea += RideRating::make(4, 00); - } -#endif - - return result; -} - -/** - * - * rct2: 0x0065E139 - */ -static RideRating::Tuple ride_ratings_get_drop_ratings(const Ride& ride) -{ - RideRating::Tuple result = { - /* .excitement = */ 0, - /* .intensity = */ 0, - /* .nausea = */ 0, - }; - - // Apply number of drops factor - int32_t drops = ride.numDrops; - result.excitement += (std::min(9, drops) * 728177) >> 16; - result.intensity += (drops * 928426) >> 16; - result.nausea += (drops * 655360) >> 16; - - // Apply highest drop factor - RideRatingsAdd( - result, ((ride.highestDropHeight * 2) * 16000) >> 16, ((ride.highestDropHeight * 2) * 32000) >> 16, - ((ride.highestDropHeight * 2) * 10240) >> 16); - - return result; -} - -/** - * Calculates a score based on the surrounding scenery. - * rct2: 0x0065E557 - */ -static int32_t ride_ratings_get_scenery_score(const Ride& ride) -{ - auto stationIndex = RideGetFirstValidStationStart(ride); - CoordsXY location; - - if (stationIndex.IsNull()) - { - return 0; - } - - const auto& rtd = ride.getRideTypeDescriptor(); - if (rtd.specialType == RtdSpecialType::maze) - { - location = ride.getStation().Entrance.ToCoordsXY(); - } - else - { - location = ride.getStation(stationIndex).Start; - } - - int32_t z = TileElementHeight(location); - - // Check if station is underground, returns a fixed mediocre score since you can't have scenery underground - if (z > ride.getStation(stationIndex).GetBaseZ()) - { - return 40; - } - - // Count surrounding scenery items - int32_t numSceneryItems = 0; - auto tileLocation = TileCoordsXY(location); - auto& gameState = getGameState(); - for (int32_t yy = std::max(tileLocation.y - 5, 0); yy <= std::min(tileLocation.y + 5, gameState.mapSize.y - 1); yy++) - { - for (int32_t xx = std::max(tileLocation.x - 5, 0); xx <= std::min(tileLocation.x + 5, gameState.mapSize.x - 1); xx++) - { - // Count scenery items on this tile - TileElement* tileElement = MapGetFirstElementAt(TileCoordsXY{ xx, yy }); - if (tileElement == nullptr) - continue; - do + int32_t excitementModifier; + int32_t totalAirTime = ride.totalAirTime; + if (rideEntry->flags.has(RideEntryFlag::limitAirTimeBonus)) { - if (tileElement->isGhost()) - continue; + totalAirTime = std::max(0, totalAirTime - 96); + excitementModifier = -1 * (std::min(totalAirTime, 200) / 8); + } + else + { + excitementModifier = std::min(totalAirTime, 200) / 8; + } + int32_t nauseaModifier = totalAirTime / 16; - const auto type = tileElement->getType(); - if (type == TileElementType::smallScenery || type == TileElementType::largeScenery) - numSceneryItems++; - } while (!(tileElement++)->isLastForTile()); + RideRatingsAdd(ratings, excitementModifier, 0, nauseaModifier); + } +#endif + } + + /** + * Lowers excitement, the higher the intensity. + * rct2: 0x0065E7A3 + */ + static void RideRatingsApplyIntensityPenalty(RideRating::Tuple& ratings) + { + static constexpr RideRating_t intensityBounds[] = { 1000, 1100, 1200, 1320, 1450 }; + RideRating_t excitement = ratings.excitement; + for (auto intensityBound : intensityBounds) + { + if (ratings.intensity >= intensityBound) + { + excitement -= excitement / 4; + } + } + ratings.excitement = excitement; + } + + /** + * + * rct2: 0x00655FD6 + */ + static void SetUnreliabilityFactor(Ride& ride) + { + const auto& rtd = ride.getRideTypeDescriptor(); + // Special unreliability for a few ride types + if (rtd.flags.has(RtdFlag::reverseInclineLaunchAffectsReliability) + && ride.mode == RideMode::reverseInclineLaunchedShuttle) + { + ride.unreliabilityFactor += 10; + } + else if (rtd.flags.has(RtdFlag::poweredLaunchAffectsReliability) && ride.isPoweredLaunched()) + { + ride.unreliabilityFactor += 5; + } + else if (rtd.flags.has(RtdFlag::runningSpeedAffectsReliability)) + { + ride.unreliabilityFactor += (ride.speed * 2); + } + // The bigger the difference in lift speed and minimum the higher the unreliability + uint8_t minLiftSpeed = ride.getRideTypeDescriptor().LiftData.minimum_speed; + ride.unreliabilityFactor += (ride.liftHillSpeed - minLiftSpeed) * 2; + } + + static uint32_t get_proximity_score_helper_1(uint16_t x, uint16_t max, uint32_t multiplier) + { + return (std::min(x, max) * multiplier) >> 16; + } + + static uint32_t get_proximity_score_helper_2(uint16_t x, uint16_t additionIfNotZero, uint16_t max, uint32_t multiplier) + { + uint32_t result = x; + if (result != 0) + result += additionIfNotZero; + return (std::min(result, max) * multiplier) >> 16; + } + + static uint32_t get_proximity_score_helper_3(uint16_t x, uint16_t resultIfNotZero) + { + return x == 0 ? 0 : resultIfNotZero; + } + + /** + * + * rct2: 0x0065E277 + */ + static uint32_t ride_ratings_get_proximity_score(RideRating::UpdateState& state) + { + const uint16_t* scores = state.ProximityScores; + + uint32_t result = 0; + result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_OVER], 60, 0x00AAAA); + result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_TOUCH], 22, 0x0245D1); + result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_LOW], 10, 0x020000); + result += get_proximity_score_helper_1(scores[PROXIMITY_WATER_HIGH], 40, 0x00A000); + result += get_proximity_score_helper_1(scores[PROXIMITY_SURFACE_TOUCH], 70, 0x01B6DB); + result += get_proximity_score_helper_1(scores[PROXIMITY_QUEUE_PATH_OVER] + 8, 12, 0x064000); + result += get_proximity_score_helper_3(scores[PROXIMITY_QUEUE_PATH_TOUCH_ABOVE], 40); + result += get_proximity_score_helper_3(scores[PROXIMITY_QUEUE_PATH_TOUCH_UNDER], 45); + result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_TOUCH_ABOVE], 10, 20, 0x03C000); + result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_TOUCH_UNDER], 10, 20, 0x044000); + result += get_proximity_score_helper_2(scores[PROXIMITY_OWN_TRACK_TOUCH_ABOVE], 10, 15, 0x035555); + result += get_proximity_score_helper_1(scores[PROXIMITY_OWN_TRACK_CLOSE_ABOVE], 5, 0x060000); + result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_ABOVE_OR_BELOW], 10, 15, 0x02AAAA); + result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_TOUCH_ABOVE], 10, 15, 0x04AAAA); + result += get_proximity_score_helper_1(scores[PROXIMITY_FOREIGN_TRACK_CLOSE_ABOVE], 5, 0x090000); + result += get_proximity_score_helper_1(scores[PROXIMITY_SCENERY_SIDE_BELOW], 35, 0x016DB6); + result += get_proximity_score_helper_1(scores[PROXIMITY_SCENERY_SIDE_ABOVE], 35, 0x00DB6D); + result += get_proximity_score_helper_3(scores[PROXIMITY_OWN_STATION_TOUCH_ABOVE], 55); + result += get_proximity_score_helper_3(scores[PROXIMITY_OWN_STATION_CLOSE_ABOVE], 25); + result += get_proximity_score_helper_2(scores[PROXIMITY_TRACK_THROUGH_VERTICAL_LOOP], 4, 6, 0x140000); + result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_THROUGH_VERTICAL_LOOP], 4, 6, 0x0F0000); + result += get_proximity_score_helper_3(scores[PROXIMITY_INTERSECTING_VERTICAL_LOOP], 100); + result += get_proximity_score_helper_2(scores[PROXIMITY_THROUGH_VERTICAL_LOOP], 4, 6, 0x0A0000); + result += get_proximity_score_helper_2(scores[PROXIMITY_PATH_SIDE_CLOSE], 10, 20, 0x01C000); + result += get_proximity_score_helper_2(scores[PROXIMITY_FOREIGN_TRACK_SIDE_CLOSE], 10, 20, 0x024000); + result += get_proximity_score_helper_2(scores[PROXIMITY_SURFACE_SIDE_CLOSE], 10, 20, 0x028000); + return result; + } + + /** + * Calculates how much of the track is sheltered in eighths. + * rct2: 0x0065E72D + */ + static ShelteredEights GetNumOfShelteredEighths(const Ride& ride) + { + int32_t totalLength = ride.getTotalLength(); + int32_t shelteredLength = ride.shelteredLength; + int32_t lengthEighth = totalLength / 8; + int32_t lengthCounter = lengthEighth; + uint8_t numShelteredEighths = 0; + for (int32_t i = 0; i < 7; i++) + { + if (shelteredLength >= lengthCounter) + { + lengthCounter += lengthEighth; + numShelteredEighths++; + } + } + + uint8_t trackShelteredEighths = numShelteredEighths; + const auto* rideType = GetRideEntryByIndex(ride.subtype); + if (rideType == nullptr) + { + return { 0, 0 }; + } + if (rideType->flags.has(RideEntryFlag::isACoveredRide)) + numShelteredEighths = 7; + + return { trackShelteredEighths, numShelteredEighths }; + } + + static RideRating::Tuple get_flat_turns_rating(const Ride& ride) + { + int32_t num3PlusTurns = GetTurnCount3Elements(ride, 0); + int32_t num2Turns = GetTurnCount2Elements(ride, 0); + int32_t num1Turns = GetTurnCount1Element(ride, 0); + + RideRating::Tuple rating; + rating.excitement = (num3PlusTurns * 0x28000) >> 16; + rating.excitement += (num2Turns * 0x30000) >> 16; + rating.excitement += (num1Turns * 63421) >> 16; + + rating.intensity = (num3PlusTurns * 81920) >> 16; + rating.intensity += (num2Turns * 49152) >> 16; + rating.intensity += (num1Turns * 21140) >> 16; + + rating.nausea = (num3PlusTurns * 0x50000) >> 16; + rating.nausea += (num2Turns * 0x32000) >> 16; + rating.nausea += (num1Turns * 42281) >> 16; + + return rating; + } + + /** + * + * rct2: 0x0065DF72 + */ + static RideRating::Tuple get_banked_turns_rating(const Ride& ride) + { + int32_t num3PlusTurns = GetTurnCount3Elements(ride, 1); + int32_t num2Turns = GetTurnCount2Elements(ride, 1); + int32_t num1Turns = GetTurnCount1Element(ride, 1); + + RideRating::Tuple rating; + rating.excitement = (num3PlusTurns * 0x3C000) >> 16; + rating.excitement += (num2Turns * 0x3C000) >> 16; + rating.excitement += (num1Turns * 73992) >> 16; + + rating.intensity = (num3PlusTurns * 0x14000) >> 16; + rating.intensity += (num2Turns * 49152) >> 16; + rating.intensity += (num1Turns * 21140) >> 16; + + rating.nausea = (num3PlusTurns * 0x50000) >> 16; + rating.nausea += (num2Turns * 0x32000) >> 16; + rating.nausea += (num1Turns * 48623) >> 16; + + return rating; + } + + /** + * + * rct2: 0x0065E047 + */ + static RideRating::Tuple get_sloped_turns_rating(const Ride& ride) + { + RideRating::Tuple rating; + + int32_t num4PlusTurns = GetTurnCount4PlusElements(ride, 2); + int32_t num3Turns = GetTurnCount3Elements(ride, 2); + int32_t num2Turns = GetTurnCount2Elements(ride, 2); + int32_t num1Turns = GetTurnCount1Element(ride, 2); + + rating.excitement = (std::min(num4PlusTurns, 4) * 0x78000) >> 16; + rating.excitement += (std::min(num3Turns, 6) * 273066) >> 16; + rating.excitement += (std::min(num2Turns, 6) * 0x3AAAA) >> 16; + rating.excitement += (std::min(num1Turns, 7) * 187245) >> 16; + rating.intensity = 0; + rating.nausea = (std::min(num4PlusTurns, 8) * 0x78000) >> 16; + + return rating; + } + + /** + * + * rct2: 0x0065E0F2 + */ + static RideRating::Tuple getInversionsRatings(uint16_t inversions) + { + RideRating::Tuple rating; + + rating.excitement = (std::min(inversions, 6) * 0x1AAAAA) >> 16; + rating.intensity = (inversions * 0x320000) >> 16; + rating.nausea = (inversions * 0x15AAAA) >> 16; + + return rating; + } + + void SpecialTrackElementRatingsAdjustment_Default( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) + { + if (ride.hasWaterSplash()) + { + excitement += 50; + intensity += 30; + nausea += 20; + } + if (ride.hasWaterfall()) + { + excitement += 55; + intensity += 30; + } + if (ride.hasWhirlpool()) + { + excitement += 35; + intensity += 20; + nausea += 23; } } - return std::min(numSceneryItems, 47) * 5; -} - -#pragma region Ride rating calculation helpers - -static void RideRatingsSet(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea) -{ - ratings.excitement = 0; - ratings.intensity = 0; - ratings.nausea = 0; - RideRatingsAdd(ratings, excitement, intensity, nausea); -} - -/** - * Add to a ride rating with overflow protection. - */ -static void RideRatingsAdd(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea) -{ - int32_t newExcitement = ratings.excitement + excitement; - int32_t newIntensity = ratings.intensity + intensity; - int32_t newNausea = ratings.nausea + nausea; - ratings.excitement = std::clamp(newExcitement, 0, INT16_MAX); - ratings.intensity = std::clamp(newIntensity, 0, INT16_MAX); - ratings.nausea = std::clamp(newNausea, 0, INT16_MAX); -} - -static void RideRatingsApplyBonusLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd( - ratings, (std::min(ToHumanReadableRideLength(ride.getTotalLength()), modifier.threshold) * modifier.excitement) >> 16, - 0, 0); -} - -static void RideRatingsApplyBonusSynchronisation(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if ((ride.departFlags & RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS) && RideHasAdjacentStation(ride)) + void SpecialTrackElementRatingsAdjustment_GhostTrain( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - } -} - -static void RideRatingsApplyBonusTrainLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd(ratings, ((ride.numCarsPerTrain - 1) * modifier.excitement) >> 16, 0, 0); -} - -static void RideRatingsApplyBonusMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - int32_t maxSpeedMod = ride.maxSpeed >> 16; - RideRatingsAdd( - ratings, (maxSpeedMod * modifier.excitement) >> 16, (maxSpeedMod * modifier.intensity) >> 16, - (maxSpeedMod * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusAverageSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - int32_t avgSpeedMod = ride.averageSpeed >> 16; - RideRatingsAdd(ratings, (avgSpeedMod * modifier.excitement) >> 16, (avgSpeedMod * modifier.intensity) >> 16, 0); -} - -static void RideRatingsApplyBonusDuration(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd(ratings, (std::min(ride.getTotalTime(), modifier.threshold) * modifier.excitement) >> 16, 0, 0); -} - -static void RideRatingsApplyBonusGForces(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRating::Tuple subRating = ride_ratings_get_gforce_ratings(ride); - RideRatingsAdd( - ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, - (subRating.nausea * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusTurns(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRating::Tuple subRating = ride_ratings_get_turns_ratings(ride); - RideRatingsAdd( - ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, - (subRating.nausea * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRating::Tuple subRating = ride_ratings_get_drop_ratings(ride); - RideRatingsAdd( - ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, - (subRating.nausea * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusSheltered(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRating::Tuple subRating = ride_ratings_get_sheltered_ratings(ride); - RideRatingsAdd( - ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, - (subRating.nausea * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusRotations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd( - ratings, ride.rotations * modifier.excitement, ride.rotations * modifier.intensity, ride.rotations * modifier.nausea); -} - -static void RideRatingsApplyBonusOperationOption(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - int32_t intensity = (modifier.intensity >= 0) ? (ride.operationOption * modifier.intensity) - : (ride.operationOption / std::abs(modifier.intensity)); - RideRatingsAdd(ratings, ride.operationOption * modifier.excitement, intensity, ride.operationOption * modifier.nausea); -} - -static void RideRatingsApplyBonusReversedTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.flags.has(RideFlag::reversedTrains)) - { - RideRatingsAdd( - ratings, ((ratings.excitement * modifier.excitement) >> 7), (ratings.intensity * modifier.intensity) >> 7, - (ratings.nausea * modifier.nausea) >> 7); - } -} - -static void RideRatingsApplyBonusGoKartRace(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.mode == RideMode::race && ride.numTrains >= modifier.threshold) - { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - - int32_t lapsFactor = (ride.numLaps - 1) * 30; - RideRatingsAdd(ratings, lapsFactor, lapsFactor / 2, 0); - } -} - -static void RideRatingsApplyBonusTowerRide(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - int32_t lengthFactor = ToHumanReadableRideLength(ride.getTotalLength()); - RideRatingsAdd( - ratings, (lengthFactor * modifier.excitement) >> 16, (lengthFactor * modifier.intensity) >> 16, - (lengthFactor * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusRotoDrop(RideRating::Tuple& ratings, const Ride& ride) -{ - int32_t lengthFactor = (ToHumanReadableRideLength(ride.getTotalLength()) * 209715) >> 16; - RideRatingsAdd(ratings, lengthFactor, lengthFactor * 2, lengthFactor * 2); -} - -static void RideRatingsApplyBonusMazeSize(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - int32_t size = std::min(ride.mazeTiles, modifier.threshold); - RideRatingsAdd(ratings, size * modifier.excitement, size / modifier.intensity, size * modifier.nausea); -} - -static void RideRatingsApplyBonusBoatHireNoCircuit(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - // Most likely checking if the ride has does not have a circuit - if (!ride.flags.has(RideFlag::tested)) - { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - } -} - -static void RideRatingsApplyBonusSlideUnlimitedRides(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.mode == RideMode::unlimitedRidesPerAdmission) - { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - } -} - -static void RideRatingsApplyBonusMotionSimulatorMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - // Hardcoded until ride mode refactor - if (ride.mode == RideMode::filmThrillRiders) - { - RideRatingsSet(ratings, RideRating::make(3, 25), RideRating::make(4, 10), RideRating::make(3, 30)); - } - else - { - RideRatingsSet(ratings, RideRating::make(2, 90), RideRating::make(3, 50), RideRating::make(3, 00)); - } -} - -static void RideRatingsApplyBonus3DCinemaMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - // Hardcoded until ride mode refactor - switch (ride.mode) - { - default: - case RideMode::mouseTails3DFilm: - RideRatingsSet(ratings, RideRating::make(3, 50), RideRating::make(2, 40), RideRating::make(1, 40)); - break; - case RideMode::stormChasers3DFilm: - RideRatingsSet(ratings, RideRating::make(4, 00), RideRating::make(2, 65), RideRating::make(1, 55)); - break; - case RideMode::spaceRaiders3DFilm: - RideRatingsSet(ratings, RideRating::make(4, 20), RideRating::make(2, 60), RideRating::make(1, 48)); - break; - } -} - -static void RideRatingsApplyBonusTopSpinMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - // Hardcoded until ride mode refactor - switch (ride.mode) - { - default: - case RideMode::beginners: - RideRatingsSet(ratings, RideRating::make(2, 00), RideRating::make(4, 80), RideRating::make(5, 74)); - break; - case RideMode::intense: - RideRatingsSet(ratings, RideRating::make(3, 00), RideRating::make(5, 75), RideRating::make(6, 64)); - break; - case RideMode::berserk: - RideRatingsSet(ratings, RideRating::make(3, 20), RideRating::make(6, 80), RideRating::make(7, 94)); - break; - } -} - -static void RideRatingsApplyBonusReversals( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) -{ - int32_t numReversers = std::min(state.AmountOfReversers, modifier.threshold); - RideRatingsAdd( - ratings, numReversers * modifier.excitement, numReversers * modifier.intensity, numReversers * modifier.nausea); -} - -static void RideRatingsApplyBonusHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - auto bonusHoles = std::min(modifier.threshold, ride.numHoles); - RideRatingsAdd(ratings, bonusHoles * modifier.excitement, bonusHoles * modifier.intensity, bonusHoles * modifier.nausea); -} - -static void RideRatingsApplyBonusNumTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - // For some reason the original code ran this twice, before and after the operation option bonus - // Has been changed to call once with double value - if (ride.numTrains >= modifier.threshold) - { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - } -} - -static void RideRatingsApplyBonusDownwardLaunch(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.mode == RideMode::downwardLaunch) - { - RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); - } -} - -static void RideRatingsApplyBonusOperationOptionFreefall(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd( - ratings, (ride.operationOption * modifier.excitement) >> 16, (ride.operationOption * modifier.intensity) >> 16, - (ride.operationOption * modifier.nausea) >> 16); -} - -static void RideRatingsApplyBonusLaunchedFreefallSpecial( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) -{ - int32_t excitement = (ToHumanReadableRideLength(ride.getTotalLength()) * 32768) >> 16; - RideRatingsAdd(ratings, excitement, 0, 0); - -#ifdef ORIGINAL_RATINGS - RideRatingsApplyBonusOperationOptionFreefall(ratings, ride, modifier); -#else - // Only apply "launch speed" effects when the setting can be modified - if (ride.mode == RideMode::upwardLaunch) - { - RideRatingsApplyBonusOperationOptionFreefall(ratings, ride, modifier); - } - else - { - // Fix #3282: When the ride mode is in downward launch mode, the intensity and - // nausea were fixed regardless of how high the ride is. The following - // calculation is based on roto-drop which is a similar mechanic. - int32_t lengthFactor = (ToHumanReadableRideLength(ride.getTotalLength()) * 209715) >> 16; - RideRatingsAdd(ratings, lengthFactor, lengthFactor * 2, lengthFactor * 2); - } -#endif -} - -static void RideRatingsApplyBonusProximity( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) -{ - RideRatingsAdd(ratings, (ride_ratings_get_proximity_score(state) * modifier.excitement) >> 16, 0, 0); -} - -static void RideRatingsApplyBonusScenery(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - RideRatingsAdd(ratings, (ride_ratings_get_scenery_score(ride) * modifier.excitement) >> 16, 0, 0); -} - -static void RideRatingsApplyRequirementLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.getStation().SegmentLength < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementDropHeight(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.highestDropHeight < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.maxSpeed < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementNumDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.numDrops < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementNegativeGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.maxNegativeVerticalG >= modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.maxLateralG < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementInversions(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.numInversions < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementUnsheltered( - RideRating::Tuple& ratings, const Ride& ride, uint8_t shelteredEighths, RatingsModifier modifier) -{ - if (shelteredEighths >= modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementReversals( - RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) -{ - if (state.AmountOfReversers < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.numHoles < modifier.threshold) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementStations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (ride.numStations <= modifier.threshold) - { - // Excitement is set to 0 in original code - this could be changed for consistency - ratings.excitement = 0; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -static void RideRatingsApplyRequirementSplashdown(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ - if (!ride.specialTrackElements.has(SpecialElement::splash)) - { - ratings.excitement /= modifier.excitement; - ratings.intensity /= modifier.intensity; - ratings.nausea /= modifier.nausea; - } -} - -#ifndef ORIGINAL_RATINGS -static RideRating::Tuple ride_ratings_get_excessive_lateral_g_penalty(const Ride& ride) -{ - RideRating::Tuple result{}; - if (ride.maxLateralG > MakeFixed16_2dp(2, 80)) - { - result.intensity = RideRating::make(3, 75); - result.nausea = RideRating::make(2, 00); + if (ride.hasSpinningTunnel()) + { + excitement += 40; + intensity += 25; + nausea += 55; + } } - if (ride.maxLateralG > MakeFixed16_2dp(3, 10)) + void SpecialTrackElementRatingsAdjustment_LogFlume( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea) { - // Remove half of the ride_ratings_get_gforce_ratings - result.excitement = (ride.maxPositiveVerticalG * 5242) >> 16; + if (ride.hasLogReverser()) + { + excitement += 48; + intensity += 55; + nausea += 65; + } + } + + static RideRating::Tuple GetSpecialTrackElementsRating(uint8_t type, const Ride& ride) + { + int32_t excitement = 0, intensity = 0, nausea = 0; + const auto& rtd = ride.getRideTypeDescriptor(); + rtd.SpecialElementRatingAdjustment(ride, excitement, intensity, nausea); + + auto helixSections = ride.numHelices; + + int32_t helixesUpTo9 = std::min(helixSections, 9); + excitement += (helixesUpTo9 * 254862) >> 16; + + int32_t helixesUpTo11 = std::min(helixSections, 11); + intensity += (helixesUpTo11 * 148945) >> 16; + + int32_t helixesOver5UpTo10 = std::clamp(helixSections - 5, 0, 10); + nausea += (helixesOver5UpTo10 * 0x140000) >> 16; + + RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), + static_cast(nausea) }; + return rating; + } + + /** + * + * rct2: 0x0065DDD1 + */ + static RideRating::Tuple ride_ratings_get_turns_ratings(const Ride& ride) + { + int32_t excitement = 0, intensity = 0, nausea = 0; + + RideRating::Tuple specialTrackElementsRating = GetSpecialTrackElementsRating(ride.type, ride); + excitement += specialTrackElementsRating.excitement; + intensity += specialTrackElementsRating.intensity; + nausea += specialTrackElementsRating.nausea; + + RideRating::Tuple flatTurnsRating = get_flat_turns_rating(ride); + excitement += flatTurnsRating.excitement; + intensity += flatTurnsRating.intensity; + nausea += flatTurnsRating.nausea; + + RideRating::Tuple bankedTurnsRating = get_banked_turns_rating(ride); + excitement += bankedTurnsRating.excitement; + intensity += bankedTurnsRating.intensity; + nausea += bankedTurnsRating.nausea; + + RideRating::Tuple slopedTurnsRating = get_sloped_turns_rating(ride); + excitement += slopedTurnsRating.excitement; + intensity += slopedTurnsRating.intensity; + nausea += slopedTurnsRating.nausea; + + RideRating::Tuple inversionsRating = getInversionsRatings(ride.numInversions); + excitement += inversionsRating.excitement; + intensity += inversionsRating.intensity; + nausea += inversionsRating.nausea; + + RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), + static_cast(nausea) }; + return rating; + } + + /** + * + * rct2: 0x0065E1C2 + */ + static RideRating::Tuple ride_ratings_get_sheltered_ratings(const Ride& ride) + { + int32_t shelteredLengthShifted = (ride.shelteredLength) >> 16; + + uint32_t shelteredLengthUpTo1000 = std::min(shelteredLengthShifted, 1000); + uint32_t shelteredLengthUpTo2000 = std::min(shelteredLengthShifted, 2000); + + int32_t excitement = (shelteredLengthUpTo1000 * 9175) >> 16; + int32_t intensity = (shelteredLengthUpTo2000 * 0x2666) >> 16; + int32_t nausea = (shelteredLengthUpTo1000 * 0x4000) >> 16; + + /*eax = (ride.var11C * 30340) >> 16;*/ + /*nausea += eax;*/ + + if (ride.numShelteredSections & ShelteredSectionsBits::kBankingWhileSheltered) + { + excitement += 20; + nausea += 15; + } + + if (ride.numShelteredSections & ShelteredSectionsBits::kRotatingWhileSheltered) + { + excitement += 20; + nausea += 15; + } + + uint8_t lowerVal = ride.getNumShelteredSections(); + lowerVal = std::min(lowerVal, 11); + excitement += (lowerVal * 774516) >> 16; + + RideRating::Tuple rating = { static_cast(excitement), static_cast(intensity), + static_cast(nausea) }; + return rating; + } + + /** + * + * rct2: 0x0065DCDC + */ + static RideRating::Tuple ride_ratings_get_gforce_ratings(const Ride& ride) + { + RideRating::Tuple result = { + .excitement = 0, + .intensity = 0, + .nausea = 0, + }; + + // Apply maximum positive G force factor + result.excitement += (ride.maxPositiveVerticalG * 5242) >> 16; + result.intensity += (ride.maxPositiveVerticalG * 52428) >> 16; + result.nausea += (ride.maxPositiveVerticalG * 17039) >> 16; // Apply maximum negative G force factor fixed16_2dp gforce = ride.maxNegativeVerticalG; result.excitement += (std::clamp(gforce, -RideRating::make(2, 50), RideRating::make(0, 00)) * -15728) >> 16; + result.intensity += ((gforce - RideRating::make(1, 00)) * -52428) >> 16; + result.nausea += ((gforce - RideRating::make(1, 00)) * -14563) >> 16; // Apply lateral G force factor result.excitement += (std::min(RideRating::make(1, 50), ride.maxLateralG) * 26214) >> 16; + result.intensity += ride.maxLateralG; + result.nausea += (ride.maxLateralG * 21845) >> 16; - // Remove half of the ride_ratings_get_gforce_ratings - result.excitement /= 2; - result.excitement *= -1; - result.intensity = RideRating::make(12, 25); - result.nausea = RideRating::make(6, 00); +// Very high lateral G force penalty +#ifdef ORIGINAL_RATINGS + if (ride.maxLateralG > MakeFixed16_2dp(2, 80)) + { + result.intensity += RideRating::make(3, 75); + result.nausea += RideRating::make(2, 00); + } + if (ride.maxLateralG > MakeFixed16_2dp(3, 10)) + { + result.excitement /= 2; + result.intensity += RideRating::make(8, 50); + result.nausea += RideRating::make(4, 00); + } +#endif + + return result; + } + + /** + * + * rct2: 0x0065E139 + */ + static RideRating::Tuple ride_ratings_get_drop_ratings(const Ride& ride) + { + RideRating::Tuple result = { + /* .excitement = */ 0, + /* .intensity = */ 0, + /* .nausea = */ 0, + }; + + // Apply number of drops factor + int32_t drops = ride.numDrops; + result.excitement += (std::min(9, drops) * 728177) >> 16; + result.intensity += (drops * 928426) >> 16; + result.nausea += (drops * 655360) >> 16; + + // Apply highest drop factor + RideRatingsAdd( + result, ((ride.highestDropHeight * 2) * 16000) >> 16, ((ride.highestDropHeight * 2) * 32000) >> 16, + ((ride.highestDropHeight * 2) * 10240) >> 16); + + return result; + } + + /** + * Calculates a score based on the surrounding scenery. + * rct2: 0x0065E557 + */ + static int32_t ride_ratings_get_scenery_score(const Ride& ride) + { + auto stationIndex = RideGetFirstValidStationStart(ride); + CoordsXY location; + + if (stationIndex.IsNull()) + { + return 0; + } + + const auto& rtd = ride.getRideTypeDescriptor(); + if (rtd.specialType == RtdSpecialType::maze) + { + location = ride.getStation().Entrance.ToCoordsXY(); + } + else + { + location = ride.getStation(stationIndex).Start; + } + + int32_t z = TileElementHeight(location); + + // Check if station is underground, returns a fixed mediocre score since you can't have scenery underground + if (z > ride.getStation(stationIndex).GetBaseZ()) + { + return 40; + } + + // Count surrounding scenery items + int32_t numSceneryItems = 0; + auto tileLocation = TileCoordsXY(location); + auto& gameState = getGameState(); + for (int32_t yy = std::max(tileLocation.y - 5, 0); yy <= std::min(tileLocation.y + 5, gameState.mapSize.y - 1); yy++) + { + for (int32_t xx = std::max(tileLocation.x - 5, 0); xx <= std::min(tileLocation.x + 5, gameState.mapSize.x - 1); + xx++) + { + // Count scenery items on this tile + TileElement* tileElement = MapGetFirstElementAt(TileCoordsXY{ xx, yy }); + if (tileElement == nullptr) + continue; + do + { + if (tileElement->isGhost()) + continue; + + const auto type = tileElement->getType(); + if (type == TileElementType::smallScenery || type == TileElementType::largeScenery) + numSceneryItems++; + } while (!(tileElement++)->isLastForTile()); + } + } + + return std::min(numSceneryItems, 47) * 5; + } + +#pragma region Ride rating calculation helpers + + static void RideRatingsSet(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea) + { + ratings.excitement = 0; + ratings.intensity = 0; + ratings.nausea = 0; + RideRatingsAdd(ratings, excitement, intensity, nausea); + } + + /** + * Add to a ride rating with overflow protection. + */ + static void RideRatingsAdd(RideRating::Tuple& ratings, int32_t excitement, int32_t intensity, int32_t nausea) + { + int32_t newExcitement = ratings.excitement + excitement; + int32_t newIntensity = ratings.intensity + intensity; + int32_t newNausea = ratings.nausea + nausea; + ratings.excitement = std::clamp(newExcitement, 0, INT16_MAX); + ratings.intensity = std::clamp(newIntensity, 0, INT16_MAX); + ratings.nausea = std::clamp(newNausea, 0, INT16_MAX); + } + + static void RideRatingsApplyBonusLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd( + ratings, + (std::min(ToHumanReadableRideLength(ride.getTotalLength()), modifier.threshold) * modifier.excitement) >> 16, 0, 0); + } + + static void RideRatingsApplyBonusSynchronisation(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if ((ride.departFlags & RIDE_DEPART_SYNCHRONISE_WITH_ADJACENT_STATIONS) && RideHasAdjacentStation(ride)) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + } + } + + static void RideRatingsApplyBonusTrainLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd(ratings, ((ride.numCarsPerTrain - 1) * modifier.excitement) >> 16, 0, 0); + } + + static void RideRatingsApplyBonusMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + int32_t maxSpeedMod = ride.maxSpeed >> 16; + RideRatingsAdd( + ratings, (maxSpeedMod * modifier.excitement) >> 16, (maxSpeedMod * modifier.intensity) >> 16, + (maxSpeedMod * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusAverageSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + int32_t avgSpeedMod = ride.averageSpeed >> 16; + RideRatingsAdd(ratings, (avgSpeedMod * modifier.excitement) >> 16, (avgSpeedMod * modifier.intensity) >> 16, 0); + } + + static void RideRatingsApplyBonusDuration(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd(ratings, (std::min(ride.getTotalTime(), modifier.threshold) * modifier.excitement) >> 16, 0, 0); + } + + static void RideRatingsApplyBonusGForces(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRating::Tuple subRating = ride_ratings_get_gforce_ratings(ride); + RideRatingsAdd( + ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, + (subRating.nausea * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusTurns(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRating::Tuple subRating = ride_ratings_get_turns_ratings(ride); + RideRatingsAdd( + ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, + (subRating.nausea * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRating::Tuple subRating = ride_ratings_get_drop_ratings(ride); + RideRatingsAdd( + ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, + (subRating.nausea * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusSheltered(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRating::Tuple subRating = ride_ratings_get_sheltered_ratings(ride); + RideRatingsAdd( + ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, + (subRating.nausea * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusRotations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd( + ratings, ride.rotations * modifier.excitement, ride.rotations * modifier.intensity, + ride.rotations * modifier.nausea); + } + + static void RideRatingsApplyBonusOperationOption(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + int32_t intensity = (modifier.intensity >= 0) ? (ride.operationOption * modifier.intensity) + : (ride.operationOption / std::abs(modifier.intensity)); + RideRatingsAdd(ratings, ride.operationOption * modifier.excitement, intensity, ride.operationOption * modifier.nausea); + } + + static void RideRatingsApplyBonusReversedTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.flags.has(RideFlag::reversedTrains)) + { + RideRatingsAdd( + ratings, ((ratings.excitement * modifier.excitement) >> 7), (ratings.intensity * modifier.intensity) >> 7, + (ratings.nausea * modifier.nausea) >> 7); + } + } + + static void RideRatingsApplyBonusGoKartRace(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.mode == RideMode::race && ride.numTrains >= modifier.threshold) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + + int32_t lapsFactor = (ride.numLaps - 1) * 30; + RideRatingsAdd(ratings, lapsFactor, lapsFactor / 2, 0); + } + } + + static void RideRatingsApplyBonusTowerRide(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + int32_t lengthFactor = ToHumanReadableRideLength(ride.getTotalLength()); + RideRatingsAdd( + ratings, (lengthFactor * modifier.excitement) >> 16, (lengthFactor * modifier.intensity) >> 16, + (lengthFactor * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusRotoDrop(RideRating::Tuple& ratings, const Ride& ride) + { + int32_t lengthFactor = (ToHumanReadableRideLength(ride.getTotalLength()) * 209715) >> 16; + RideRatingsAdd(ratings, lengthFactor, lengthFactor * 2, lengthFactor * 2); + } + + static void RideRatingsApplyBonusMazeSize(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + int32_t size = std::min(ride.mazeTiles, modifier.threshold); + RideRatingsAdd(ratings, size * modifier.excitement, size / modifier.intensity, size * modifier.nausea); + } + + static void RideRatingsApplyBonusBoatHireNoCircuit(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + // Most likely checking if the ride has does not have a circuit + if (!ride.flags.has(RideFlag::tested)) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + } + } + + static void RideRatingsApplyBonusSlideUnlimitedRides(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.mode == RideMode::unlimitedRidesPerAdmission) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + } + } + + static void RideRatingsApplyBonusMotionSimulatorMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + // Hardcoded until ride mode refactor + if (ride.mode == RideMode::filmThrillRiders) + { + RideRatingsSet(ratings, RideRating::make(3, 25), RideRating::make(4, 10), RideRating::make(3, 30)); + } + else + { + RideRatingsSet(ratings, RideRating::make(2, 90), RideRating::make(3, 50), RideRating::make(3, 00)); + } + } + + static void RideRatingsApplyBonus3DCinemaMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + // Hardcoded until ride mode refactor + switch (ride.mode) + { + default: + case RideMode::mouseTails3DFilm: + RideRatingsSet(ratings, RideRating::make(3, 50), RideRating::make(2, 40), RideRating::make(1, 40)); + break; + case RideMode::stormChasers3DFilm: + RideRatingsSet(ratings, RideRating::make(4, 00), RideRating::make(2, 65), RideRating::make(1, 55)); + break; + case RideMode::spaceRaiders3DFilm: + RideRatingsSet(ratings, RideRating::make(4, 20), RideRating::make(2, 60), RideRating::make(1, 48)); + break; + } + } + + static void RideRatingsApplyBonusTopSpinMode(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + // Hardcoded until ride mode refactor + switch (ride.mode) + { + default: + case RideMode::beginners: + RideRatingsSet(ratings, RideRating::make(2, 00), RideRating::make(4, 80), RideRating::make(5, 74)); + break; + case RideMode::intense: + RideRatingsSet(ratings, RideRating::make(3, 00), RideRating::make(5, 75), RideRating::make(6, 64)); + break; + case RideMode::berserk: + RideRatingsSet(ratings, RideRating::make(3, 20), RideRating::make(6, 80), RideRating::make(7, 94)); + break; + } + } + + static void RideRatingsApplyBonusReversals( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) + { + int32_t numReversers = std::min(state.AmountOfReversers, modifier.threshold); + RideRatingsAdd( + ratings, numReversers * modifier.excitement, numReversers * modifier.intensity, numReversers * modifier.nausea); + } + + static void RideRatingsApplyBonusHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + auto bonusHoles = std::min(modifier.threshold, ride.numHoles); + RideRatingsAdd( + ratings, bonusHoles * modifier.excitement, bonusHoles * modifier.intensity, bonusHoles * modifier.nausea); + } + + static void RideRatingsApplyBonusNumTrains(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + // For some reason the original code ran this twice, before and after the operation option bonus + // Has been changed to call once with double value + if (ride.numTrains >= modifier.threshold) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + } + } + + static void RideRatingsApplyBonusDownwardLaunch(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.mode == RideMode::downwardLaunch) + { + RideRatingsAdd(ratings, modifier.excitement, modifier.intensity, modifier.nausea); + } + } + + static void RideRatingsApplyBonusOperationOptionFreefall( + RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd( + ratings, (ride.operationOption * modifier.excitement) >> 16, (ride.operationOption * modifier.intensity) >> 16, + (ride.operationOption * modifier.nausea) >> 16); + } + + static void RideRatingsApplyBonusLaunchedFreefallSpecial( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) + { + int32_t excitement = (ToHumanReadableRideLength(ride.getTotalLength()) * 32768) >> 16; + RideRatingsAdd(ratings, excitement, 0, 0); + +#ifdef ORIGINAL_RATINGS + RideRatingsApplyBonusOperationOptionFreefall(ratings, ride, modifier); +#else + // Only apply "launch speed" effects when the setting can be modified + if (ride.mode == RideMode::upwardLaunch) + { + RideRatingsApplyBonusOperationOptionFreefall(ratings, ride, modifier); + } + else + { + // Fix #3282: When the ride mode is in downward launch mode, the intensity and + // nausea were fixed regardless of how high the ride is. The following + // calculation is based on roto-drop which is a similar mechanic. + int32_t lengthFactor = (ToHumanReadableRideLength(ride.getTotalLength()) * 209715) >> 16; + RideRatingsAdd(ratings, lengthFactor, lengthFactor * 2, lengthFactor * 2); + } +#endif + } + + static void RideRatingsApplyBonusProximity( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) + { + RideRatingsAdd(ratings, (ride_ratings_get_proximity_score(state) * modifier.excitement) >> 16, 0, 0); + } + + static void RideRatingsApplyBonusScenery(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + RideRatingsAdd(ratings, (ride_ratings_get_scenery_score(ride) * modifier.excitement) >> 16, 0, 0); + } + + static void RideRatingsApplyRequirementLength(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.getStation().SegmentLength < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementDropHeight(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.highestDropHeight < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementMaxSpeed(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.maxSpeed < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementNumDrops(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.numDrops < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementNegativeGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.maxNegativeVerticalG >= modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.maxLateralG < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementInversions(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.numInversions < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementUnsheltered( + RideRating::Tuple& ratings, const Ride& ride, uint8_t shelteredEighths, RatingsModifier modifier) + { + if (shelteredEighths >= modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementReversals( + RideRating::Tuple& ratings, const Ride& ride, RideRating::UpdateState& state, RatingsModifier modifier) + { + if (state.AmountOfReversers < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementHoles(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.numHoles < modifier.threshold) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementStations(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (ride.numStations <= modifier.threshold) + { + // Excitement is set to 0 in original code - this could be changed for consistency + ratings.excitement = 0; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + + static void RideRatingsApplyRequirementSplashdown(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { + if (!ride.specialTrackElements.has(SpecialElement::splash)) + { + ratings.excitement /= modifier.excitement; + ratings.intensity /= modifier.intensity; + ratings.nausea /= modifier.nausea; + } + } + +#ifndef ORIGINAL_RATINGS + static RideRating::Tuple ride_ratings_get_excessive_lateral_g_penalty(const Ride& ride) + { + RideRating::Tuple result{}; + if (ride.maxLateralG > MakeFixed16_2dp(2, 80)) + { + result.intensity = RideRating::make(3, 75); + result.nausea = RideRating::make(2, 00); + } + + if (ride.maxLateralG > MakeFixed16_2dp(3, 10)) + { + // Remove half of the ride_ratings_get_gforce_ratings + result.excitement = (ride.maxPositiveVerticalG * 5242) >> 16; + + // Apply maximum negative G force factor + fixed16_2dp gforce = ride.maxNegativeVerticalG; + result.excitement += (std::clamp(gforce, -RideRating::make(2, 50), RideRating::make(0, 00)) * -15728) + >> 16; + + // Apply lateral G force factor + result.excitement += (std::min(RideRating::make(1, 50), ride.maxLateralG) * 26214) >> 16; + + // Remove half of the ride_ratings_get_gforce_ratings + result.excitement /= 2; + result.excitement *= -1; + result.intensity = RideRating::make(12, 25); + result.nausea = RideRating::make(6, 00); + } + return result; } - return result; -} #endif -static void RideRatingsApplyPenaltyLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) -{ + static void RideRatingsApplyPenaltyLateralGs(RideRating::Tuple& ratings, const Ride& ride, RatingsModifier modifier) + { #ifndef ORIGINAL_RATINGS - RideRating::Tuple subRating = ride_ratings_get_excessive_lateral_g_penalty(ride); - RideRatingsAdd( - ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, - (subRating.nausea * modifier.nausea) >> 16); + RideRating::Tuple subRating = ride_ratings_get_excessive_lateral_g_penalty(ride); + RideRatingsAdd( + ratings, (subRating.excitement * modifier.excitement) >> 16, (subRating.intensity * modifier.intensity) >> 16, + (subRating.nausea * modifier.nausea) >> 16); #endif -} + } #pragma endregion -bool RideRating::Tuple::isNull() const -{ - return excitement == kUndefined; -} + bool RideRating::Tuple::isNull() const + { + return excitement == kUndefined; + } -void RideRating::Tuple::setNull() -{ - excitement = kUndefined; -} + void RideRating::Tuple::setNull() + { + excitement = kUndefined; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideRatings.h b/src/openrct2/ride/RideRatings.h index afe4933a98..dc7fc9ea36 100644 --- a/src/openrct2/ride/RideRatings.h +++ b/src/openrct2/ride/RideRatings.h @@ -15,11 +15,12 @@ #include -struct Ride; - namespace OpenRCT2 { enum class TrackElemType : uint16_t; + + struct Ride; + using RideRating_t = fixed16_2dp; namespace RideRating { @@ -73,9 +74,12 @@ namespace OpenRCT2 void UpdateRide(const Ride& ride); void UpdateAll(); } // namespace RideRating -} // namespace OpenRCT2 -// Special Track Element Adjustment functions for RTDs -void SpecialTrackElementRatingsAjustment_Default(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); -void SpecialTrackElementRatingsAjustment_GhostTrain(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); -void SpecialTrackElementRatingsAjustment_LogFlume(const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); + // Special Track Element Adjustment functions for RTDs + void SpecialTrackElementRatingsAdjustment_Default( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); + void SpecialTrackElementRatingsAdjustment_GhostTrain( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); + void SpecialTrackElementRatingsAdjustment_LogFlume( + const Ride& ride, int32_t& excitement, int32_t& intensity, int32_t& nausea); +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/RideTypes.h b/src/openrct2/ride/RideTypes.h index 48bfd78045..7de0fd188f 100644 --- a/src/openrct2/ride/RideTypes.h +++ b/src/openrct2/ride/RideTypes.h @@ -16,7 +16,10 @@ #include #include -struct Ride; +namespace OpenRCT2 +{ + struct Ride; +} using ride_type_t = uint16_t; static ride_type_t constexpr kRideTypeNull = 0xFF; diff --git a/src/openrct2/ride/ShopItem.h b/src/openrct2/ride/ShopItem.h index b5a0b55920..d445c87d2c 100644 --- a/src/openrct2/ride/ShopItem.h +++ b/src/openrct2/ride/ShopItem.h @@ -12,12 +12,12 @@ #include "../core/Money.hpp" #include "../entity/Litter.h" -struct Ride; - namespace OpenRCT2 { enum class PeepThoughtType : uint8_t; -} + + struct Ride; +} // namespace OpenRCT2 enum class ShopItem : uint8_t { @@ -131,7 +131,7 @@ enum SHOP_ITEM_FLAG_IS_RECOLOURABLE = (1 << 5), }; -money64 ShopItemGetCommonPrice(Ride* forRide, ShopItem shopItem); +money64 ShopItemGetCommonPrice(OpenRCT2::Ride* forRide, ShopItem shopItem); bool ShopItemHasCommonPrice(ShopItem shopItem); const ShopItemDescriptor& GetShopItemDescriptor(ShopItem item); diff --git a/src/openrct2/ride/Station.cpp b/src/openrct2/ride/Station.cpp index 09f04980bd..971c93892f 100644 --- a/src/openrct2/ride/Station.cpp +++ b/src/openrct2/ride/Station.cpp @@ -19,409 +19,410 @@ #include "RideEntry.h" #include "Vehicle.h" -using namespace OpenRCT2; - -static void RideUpdateStationBlockSection(Ride& ride, StationIndex stationIndex); -static void RideUpdateStationDodgems(Ride& ride, StationIndex stationIndex); -static void RideUpdateStationNormal(Ride& ride, StationIndex stationIndex); -static void RideUpdateStationRace(Ride& ride, StationIndex stationIndex); -static void RideRaceInitVehicleSpeeds(const Ride& ride); -static void RideInvalidateStationStart(Ride& ride, StationIndex stationIndex, bool greenLight); - -/** - * - * rct2: 0x006ABFFB - */ -void RideUpdateStation(Ride& ride, StationIndex stationIndex) +namespace OpenRCT2 { - if (ride.getStation(stationIndex).Start.IsNull()) - return; + static void RideUpdateStationBlockSection(Ride& ride, StationIndex stationIndex); + static void RideUpdateStationDodgems(Ride& ride, StationIndex stationIndex); + static void RideUpdateStationNormal(Ride& ride, StationIndex stationIndex); + static void RideUpdateStationRace(Ride& ride, StationIndex stationIndex); + static void RideRaceInitVehicleSpeeds(const Ride& ride); + static void RideInvalidateStationStart(Ride& ride, StationIndex stationIndex, bool greenLight); - switch (ride.mode) + /** + * + * rct2: 0x006ABFFB + */ + void RideUpdateStation(Ride& ride, StationIndex stationIndex) { - case RideMode::race: - RideUpdateStationRace(ride, stationIndex); - break; - case RideMode::dodgems: - RideUpdateStationDodgems(ride, stationIndex); - break; - case RideMode::continuousCircuitBlockSectioned: - case RideMode::poweredLaunchBlockSectioned: - RideUpdateStationBlockSection(ride, stationIndex); - break; - default: - RideUpdateStationNormal(ride, stationIndex); - break; - } -} + if (ride.getStation(stationIndex).Start.IsNull()) + return; -/** - * - * rct2: 0x006AC0A1 - */ -static void RideUpdateStationBlockSection(Ride& ride, StationIndex stationIndex) -{ - TileElement* tileElement = RideGetStationStartTrackElement(ride, stationIndex); - auto& station = ride.getStation(stationIndex); - - if ((ride.status == RideStatus::closed && ride.numRiders == 0) - || (tileElement != nullptr && tileElement->asTrack()->IsBrakeClosed())) - { - station.Depart &= ~kStationDepartFlag; - - if ((station.Depart & kStationDepartFlag) || (tileElement != nullptr && tileElement->asTrack()->HasGreenLight())) - RideInvalidateStationStart(ride, stationIndex, false); - } - else - { - if (!(station.Depart & kStationDepartFlag)) + switch (ride.mode) { - station.Depart |= kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, true); - } - else if (tileElement != nullptr && tileElement->asTrack()->HasGreenLight()) - { - RideInvalidateStationStart(ride, stationIndex, true); + case RideMode::race: + RideUpdateStationRace(ride, stationIndex); + break; + case RideMode::dodgems: + RideUpdateStationDodgems(ride, stationIndex); + break; + case RideMode::continuousCircuitBlockSectioned: + case RideMode::poweredLaunchBlockSectioned: + RideUpdateStationBlockSection(ride, stationIndex); + break; + default: + RideUpdateStationNormal(ride, stationIndex); + break; } } -} -/** - * - * rct2: 0x006AC12B - */ -static void RideUpdateStationDodgems(Ride& ride, StationIndex stationIndex) -{ - auto& station = ride.getStation(stationIndex); - - // Change of station depart flag should really call invalidate_station_start - // but since dodgems do not have station lights there is no point. - if (ride.status == RideStatus::closed || ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) + /** + * + * rct2: 0x006AC0A1 + */ + static void RideUpdateStationBlockSection(Ride& ride, StationIndex stationIndex) { - station.Depart &= ~kStationDepartFlag; - return; + TileElement* tileElement = RideGetStationStartTrackElement(ride, stationIndex); + auto& station = ride.getStation(stationIndex); + + if ((ride.status == RideStatus::closed && ride.numRiders == 0) + || (tileElement != nullptr && tileElement->asTrack()->IsBrakeClosed())) + { + station.Depart &= ~kStationDepartFlag; + + if ((station.Depart & kStationDepartFlag) || (tileElement != nullptr && tileElement->asTrack()->HasGreenLight())) + RideInvalidateStationStart(ride, stationIndex, false); + } + else + { + if (!(station.Depart & kStationDepartFlag)) + { + station.Depart |= kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, true); + } + else if (tileElement != nullptr && tileElement->asTrack()->HasGreenLight()) + { + RideInvalidateStationStart(ride, stationIndex, true); + } + } } - if (ride.flags.has(RideFlag::passStationNoStopping)) + /** + * + * rct2: 0x006AC12B + */ + static void RideUpdateStationDodgems(Ride& ride, StationIndex stationIndex) { - int32_t dx = ride.timeLimit * 32; - int32_t dh = (dx >> 8) & 0xFF; - for (size_t i = 0; i < ride.numTrains; i++) + auto& station = ride.getStation(stationIndex); + + // Change of station depart flag should really call invalidate_station_start + // but since dodgems do not have station lights there is no point. + if (ride.status == RideStatus::closed || ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle == nullptr) - continue; - - if (vehicle->NumLaps < dh) - continue; - - // End match - ride.flags.unset(RideFlag::passStationNoStopping); station.Depart &= ~kStationDepartFlag; return; } - // Continue match - station.Depart |= kStationDepartFlag; - } - else - { - // Check if all vehicles are ready to go - for (size_t i = 0; i < ride.numTrains; i++) + if (ride.flags.has(RideFlag::passStationNoStopping)) { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle == nullptr) - continue; - - if (vehicle->status != Vehicle::Status::waitingToDepart) + int32_t dx = ride.timeLimit * 32; + int32_t dh = (dx >> 8) & 0xFF; + for (size_t i = 0; i < ride.numTrains; i++) { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle == nullptr) + continue; + + if (vehicle->NumLaps < dh) + continue; + + // End match + ride.flags.unset(RideFlag::passStationNoStopping); station.Depart &= ~kStationDepartFlag; return; } - } - // Begin the match - ride.flags.set(RideFlag::passStationNoStopping); - station.Depart |= kStationDepartFlag; - ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); - } -} - -/** - * - * rct2: 0x006AC02C - */ -static void RideUpdateStationNormal(Ride& ride, StationIndex stationIndex) -{ - auto& station = ride.getStation(stationIndex); - int32_t time = station.Depart & kStationDepartMask; - const auto currentTicks = getGameState().currentTicks; - if (ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed) - || (ride.status == RideStatus::closed && ride.numRiders == 0)) - { - if (time != 0 && time != 127 && !(currentTicks & 7)) - time--; - - station.Depart = time; - RideInvalidateStationStart(ride, stationIndex, false); - } - else - { - if (time == 0) - { + // Continue match station.Depart |= kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, true); } else { - if (time != 127 && !(currentTicks & 31)) + // Check if all vehicles are ready to go + for (size_t i = 0; i < ride.numTrains; i++) + { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle == nullptr) + continue; + + if (vehicle->status != Vehicle::Status::waitingToDepart) + { + station.Depart &= ~kStationDepartFlag; + return; + } + } + + // Begin the match + ride.flags.set(RideFlag::passStationNoStopping); + station.Depart |= kStationDepartFlag; + ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + } + } + + /** + * + * rct2: 0x006AC02C + */ + static void RideUpdateStationNormal(Ride& ride, StationIndex stationIndex) + { + auto& station = ride.getStation(stationIndex); + int32_t time = station.Depart & kStationDepartMask; + const auto currentTicks = getGameState().currentTicks; + if (ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed) + || (ride.status == RideStatus::closed && ride.numRiders == 0)) + { + if (time != 0 && time != 127 && !(currentTicks & 7)) time--; station.Depart = time; RideInvalidateStationStart(ride, stationIndex, false); } - } -} - -/** - * - * rct2: 0x006AC1DF - */ -static void RideUpdateStationRace(Ride& ride, StationIndex stationIndex) -{ - auto& station = ride.getStation(stationIndex); - if (ride.status == RideStatus::closed || ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) - { - if (station.Depart & kStationDepartFlag) + else { - station.Depart &= ~kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, false); + if (time == 0) + { + station.Depart |= kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, true); + } + else + { + if (time != 127 && !(currentTicks & 31)) + time--; + + station.Depart = time; + RideInvalidateStationStart(ride, stationIndex, false); + } } - return; } - if (ride.flags.has(RideFlag::passStationNoStopping)) + /** + * + * rct2: 0x006AC1DF + */ + static void RideUpdateStationRace(Ride& ride, StationIndex stationIndex) { - int32_t numLaps = ride.numLaps; + auto& station = ride.getStation(stationIndex); + if (ride.status == RideStatus::closed || ride.flags.hasAny(RideFlag::brokenDown, RideFlag::crashed)) + { + if (station.Depart & kStationDepartFlag) + { + station.Depart &= ~kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, false); + } + return; + } + if (ride.flags.has(RideFlag::passStationNoStopping)) + { + int32_t numLaps = ride.numLaps; + + for (size_t i = 0; i < ride.numTrains; i++) + { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle == nullptr) + continue; + + if (vehicle->status != Vehicle::Status::waitingToDepart && vehicle->NumLaps >= numLaps) + { + // Found a winner + if (vehicle->num_peeps != 0) + { + auto* peep = getGameState().entities.GetEntity(vehicle->peep[0]); + if (peep != nullptr) + { + ride.raceWinner = peep->id; + ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + } + } + + // Race is over + ride.flags.unset(RideFlag::passStationNoStopping); + if (station.Depart & kStationDepartFlag) + { + station.Depart &= ~kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, false); + } + return; + } + } + + // Continue racing + station.Depart |= kStationDepartFlag; + } + else + { + // Check if all vehicles are ready to go + for (size_t i = 0; i < ride.numTrains; i++) + { + Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); + if (vehicle == nullptr) + continue; + + if (vehicle->status != Vehicle::Status::waitingToDepart && vehicle->status != Vehicle::Status::departing) + { + if (station.Depart & kStationDepartFlag) + { + station.Depart &= ~kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, false); + } + return; + } + } + + // Begin the race + RideRaceInitVehicleSpeeds(ride); + ride.flags.set(RideFlag::passStationNoStopping); + if (!(station.Depart & kStationDepartFlag)) + { + station.Depart |= kStationDepartFlag; + RideInvalidateStationStart(ride, stationIndex, true); + } + ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + } + } + + /** + * + * rct2: 0x006AC988 + * set the speed of the go kart type vehicle at the start to a random value or alter if peep name is an easter egg + * @param ride (esi) + */ + static void RideRaceInitVehicleSpeeds(const Ride& ride) + { for (size_t i = 0; i < ride.numTrains; i++) { Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); if (vehicle == nullptr) continue; - if (vehicle->status != Vehicle::Status::waitingToDepart && vehicle->NumLaps >= numLaps) + vehicle->flags.unset(VehicleFlag::currentlyColliding); + + const auto* rideEntry = vehicle->GetRideEntry(); + + vehicle->speed = (ScenarioRand() & 15) - 8 + rideEntry->Cars[vehicle->vehicle_type].powered_max_speed; + + if (vehicle->num_peeps != 0) { - // Found a winner - if (vehicle->num_peeps != 0) + auto* guest = getGameState().entities.GetEntity(vehicle->peep[0]); + + // Easter egg names should only work on guests + if (guest != nullptr) { - auto* peep = getGameState().entities.GetEntity(vehicle->peep[0]); - if (peep != nullptr) + switch (guest->getEasterEggNameId()) { - ride.raceWinner = peep->id; - ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); + case EASTEREGG_PEEP_NAME_MICHAEL_SCHUMACHER: + vehicle->speed += 35; + break; + case EASTEREGG_PEEP_NAME_JACQUES_VILLENEUVE: + vehicle->speed += 25; + break; + case EASTEREGG_PEEP_NAME_DAMON_HILL: + vehicle->speed += 55; + break; + case EASTEREGG_PEEP_NAME_CHRIS_SAWYER: + vehicle->speed += 14; + break; + case EASTEREGG_PEEP_NAME_MR_BEAN: + vehicle->speed = 9; + break; } } - - // Race is over - ride.flags.unset(RideFlag::passStationNoStopping); - if (station.Depart & kStationDepartFlag) - { - station.Depart &= ~kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, false); - } - return; - } - } - - // Continue racing - station.Depart |= kStationDepartFlag; - } - else - { - // Check if all vehicles are ready to go - for (size_t i = 0; i < ride.numTrains; i++) - { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle == nullptr) - continue; - - if (vehicle->status != Vehicle::Status::waitingToDepart && vehicle->status != Vehicle::Status::departing) - { - if (station.Depart & kStationDepartFlag) - { - station.Depart &= ~kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, false); - } - return; - } - } - - // Begin the race - RideRaceInitVehicleSpeeds(ride); - ride.flags.set(RideFlag::passStationNoStopping); - if (!(station.Depart & kStationDepartFlag)) - { - station.Depart |= kStationDepartFlag; - RideInvalidateStationStart(ride, stationIndex, true); - } - ride.windowInvalidateFlags.set(RideInvalidateFlag::main, RideInvalidateFlag::list); - } -} - -/** - * - * rct2: 0x006AC988 - * set the speed of the go kart type vehicle at the start to a random value or alter if peep name is an easter egg - * @param ride (esi) - */ -static void RideRaceInitVehicleSpeeds(const Ride& ride) -{ - for (size_t i = 0; i < ride.numTrains; i++) - { - Vehicle* vehicle = getGameState().entities.GetEntity(ride.vehicles[i]); - if (vehicle == nullptr) - continue; - - vehicle->flags.unset(VehicleFlag::currentlyColliding); - - const auto* rideEntry = vehicle->GetRideEntry(); - - vehicle->speed = (ScenarioRand() & 15) - 8 + rideEntry->Cars[vehicle->vehicle_type].powered_max_speed; - - if (vehicle->num_peeps != 0) - { - auto* guest = getGameState().entities.GetEntity(vehicle->peep[0]); - - // Easter egg names should only work on guests - if (guest != nullptr) - { - switch (guest->getEasterEggNameId()) - { - case EASTEREGG_PEEP_NAME_MICHAEL_SCHUMACHER: - vehicle->speed += 35; - break; - case EASTEREGG_PEEP_NAME_JACQUES_VILLENEUVE: - vehicle->speed += 25; - break; - case EASTEREGG_PEEP_NAME_DAMON_HILL: - vehicle->speed += 55; - break; - case EASTEREGG_PEEP_NAME_CHRIS_SAWYER: - vehicle->speed += 14; - break; - case EASTEREGG_PEEP_NAME_MR_BEAN: - vehicle->speed = 9; - break; - } } } } -} -/** - * - * rct2: 0x006AC2C7 - */ -static void RideInvalidateStationStart(Ride& ride, StationIndex stationIndex, bool greenLight) -{ - auto startPos = ride.getStation(stationIndex).Start; - TileElement* tileElement = RideGetStationStartTrackElement(ride, stationIndex); - - // If no station track found return - if (tileElement == nullptr) - return; - - TrackElement* const trackElement = tileElement->asTrack(); - if (trackElement->HasGreenLight() != greenLight) + /** + * + * rct2: 0x006AC2C7 + */ + static void RideInvalidateStationStart(Ride& ride, StationIndex stationIndex, bool greenLight) { - trackElement->SetHasGreenLight(greenLight); - MapInvalidateTileZoom1({ startPos, tileElement->getBaseZ(), tileElement->getClearanceZ() }); - } -} + auto startPos = ride.getStation(stationIndex).Start; + TileElement* tileElement = RideGetStationStartTrackElement(ride, stationIndex); -TileElement* RideGetStationStartTrackElement(const Ride& ride, StationIndex stationIndex) -{ - auto stationStart = ride.getStation(stationIndex).GetStart(); - - // Find the station track element - TileElement* tileElement = MapGetFirstElementAt(stationStart); - if (tileElement == nullptr) - return nullptr; - do - { - if (tileElement->getType() == TileElementType::track && stationStart.z == tileElement->getBaseZ()) - return tileElement; - - } while (!(tileElement++)->isLastForTile()); - - return nullptr; -} - -TileElement* RideGetStationExitElement(const CoordsXYZ& elementPos) -{ - // Find the station track element - TileElement* tileElement = MapGetFirstElementAt(elementPos); - if (tileElement == nullptr) - return nullptr; - do - { + // If no station track found return if (tileElement == nullptr) - break; - if (tileElement->getType() == TileElementType::entrance && elementPos.z == tileElement->getBaseZ()) - return tileElement; - } while (!(tileElement++)->isLastForTile()); + return; - return nullptr; -} - -StationIndex RideGetFirstValidStationExit(const Ride& ride) -{ - for (const auto& station : ride.getStations()) - { - if (!station.Exit.IsNull()) + TrackElement* const trackElement = tileElement->asTrack(); + if (trackElement->HasGreenLight() != greenLight) { - return ride.getStationIndex(&station); + trackElement->SetHasGreenLight(greenLight); + MapInvalidateTileZoom1({ startPos, tileElement->getBaseZ(), tileElement->getClearanceZ() }); } } - return StationIndex::GetNull(); -} -StationIndex RideGetFirstValidStationStart(const Ride& ride) -{ - for (const auto& station : ride.getStations()) + TileElement* RideGetStationStartTrackElement(const Ride& ride, StationIndex stationIndex) { - if (!station.Start.IsNull()) - { - return ride.getStationIndex(&station); - } - } - return StationIndex::GetNull(); -} + auto stationStart = ride.getStation(stationIndex).GetStart(); -StationIndex RideGetFirstEmptyStationStart(const Ride& ride) -{ - for (const auto& station : ride.getStations()) + // Find the station track element + TileElement* tileElement = MapGetFirstElementAt(stationStart); + if (tileElement == nullptr) + return nullptr; + do + { + if (tileElement->getType() == TileElementType::track && stationStart.z == tileElement->getBaseZ()) + return tileElement; + + } while (!(tileElement++)->isLastForTile()); + + return nullptr; + } + + TileElement* RideGetStationExitElement(const CoordsXYZ& elementPos) { - if (station.Start.IsNull()) + // Find the station track element + TileElement* tileElement = MapGetFirstElementAt(elementPos); + if (tileElement == nullptr) + return nullptr; + do { - return ride.getStationIndex(&station); - } + if (tileElement == nullptr) + break; + if (tileElement->getType() == TileElementType::entrance && elementPos.z == tileElement->getBaseZ()) + return tileElement; + } while (!(tileElement++)->isLastForTile()); + + return nullptr; } - return StationIndex::GetNull(); -} -int32_t RideStation::GetBaseZ() const -{ - return Height * kCoordsZStep; -} + StationIndex RideGetFirstValidStationExit(const Ride& ride) + { + for (const auto& station : ride.getStations()) + { + if (!station.Exit.IsNull()) + { + return ride.getStationIndex(&station); + } + } + return StationIndex::GetNull(); + } -void RideStation::SetBaseZ(int32_t newZ) -{ - Height = newZ / kCoordsZStep; -} + StationIndex RideGetFirstValidStationStart(const Ride& ride) + { + for (const auto& station : ride.getStations()) + { + if (!station.Start.IsNull()) + { + return ride.getStationIndex(&station); + } + } + return StationIndex::GetNull(); + } -CoordsXYZ RideStation::GetStart() const -{ - return { Start, GetBaseZ() }; -} + StationIndex RideGetFirstEmptyStationStart(const Ride& ride) + { + for (const auto& station : ride.getStations()) + { + if (station.Start.IsNull()) + { + return ride.getStationIndex(&station); + } + } + return StationIndex::GetNull(); + } + + int32_t RideStation::GetBaseZ() const + { + return Height * kCoordsZStep; + } + + void RideStation::SetBaseZ(int32_t newZ) + { + Height = newZ / kCoordsZStep; + } + + CoordsXYZ RideStation::GetStart() const + { + return { Start, GetBaseZ() }; + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Station.h b/src/openrct2/ride/Station.h index 8b6541cf27..a9b8633f30 100644 --- a/src/openrct2/ride/Station.h +++ b/src/openrct2/ride/Station.h @@ -11,9 +11,12 @@ #include "../Identifiers.h" -struct Ride; +namespace OpenRCT2 +{ + struct Ride; -void RideUpdateStation(Ride& ride, StationIndex stationIndex); -StationIndex RideGetFirstValidStationExit(const Ride& ride); -StationIndex RideGetFirstValidStationStart(const Ride& ride); -StationIndex RideGetFirstEmptyStationStart(const Ride& ride); + void RideUpdateStation(OpenRCT2::Ride& ride, StationIndex stationIndex); + StationIndex RideGetFirstValidStationExit(const OpenRCT2::Ride& ride); + StationIndex RideGetFirstValidStationStart(const OpenRCT2::Ride& ride); + StationIndex RideGetFirstEmptyStationStart(const OpenRCT2::Ride& ride); +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/TrackDesign.h b/src/openrct2/ride/TrackDesign.h index 2042d0d329..328d128781 100644 --- a/src/openrct2/ride/TrackDesign.h +++ b/src/openrct2/ride/TrackDesign.h @@ -21,7 +21,19 @@ #include "VehicleColour.h" #include -struct Ride; + +namespace OpenRCT2::RCT12 +{ + enum class TD46Version : uint8_t; +} + +namespace OpenRCT2 +{ + struct Ride; + + enum class RideMode : uint8_t; +} // namespace OpenRCT2 + struct ResultWithMessage; enum class ViewportInteractionItem : uint8_t; @@ -121,8 +133,6 @@ struct TrackDesignMazeElement uint16_t mazeEntry{}; }; -enum class RideMode : uint8_t; - enum class TrackDesignGameStateFlag { sceneryUnavailable, @@ -140,7 +150,7 @@ struct TrackDesignTrackAndVehicleSettings struct TrackDesignOperatingSettings { - RideMode rideMode{}; + OpenRCT2::RideMode rideMode{}; uint8_t liftHillSpeed{}; uint8_t numCircuits{}; uint8_t operationSetting{}; @@ -211,15 +221,15 @@ struct TrackDesign OpenRCT2::RCT12::TD46Version version = OpenRCT2::RCT12::TD46Version::td6; public: - ResultWithMessage CreateTrackDesign(TrackDesignState& tds, const Ride& ride); + ResultWithMessage CreateTrackDesign(TrackDesignState& tds, const OpenRCT2::Ride& ride); ResultWithMessage CreateTrackDesignScenery(TrackDesignState& tds); void Serialise(OpenRCT2::DataSerialiser& stream); private: uint8_t _saveDirection; - ResultWithMessage CreateTrackDesignTrack(TrackDesignState& tds, const Ride& ride); - ResultWithMessage CreateTrackDesignMaze(TrackDesignState& tds, const Ride& ride); - CoordsXYE MazeGetFirstElement(const Ride& ride); + ResultWithMessage CreateTrackDesignTrack(TrackDesignState& tds, const OpenRCT2::Ride& ride); + ResultWithMessage CreateTrackDesignMaze(TrackDesignState& tds, const OpenRCT2::Ride& ride); + CoordsXYE MazeGetFirstElement(const OpenRCT2::Ride& ride); }; extern bool gTrackDesignSceneryToggle; @@ -235,11 +245,12 @@ extern RideId gTrackDesignSaveRideIndex; void TrackDesignMirror(TrackDesign& td); OpenRCT2::GameActions::Result TrackDesignPlace( - const TrackDesign& td, OpenRCT2::GameActions::CommandFlags flags, bool placeScenery, Ride& ride, const CoordsXYZD& coords); -void TrackDesignPreviewRemoveGhosts(const TrackDesign& td, Ride& ride, const CoordsXYZD& coords); + const TrackDesign& td, OpenRCT2::GameActions::CommandFlags flags, bool placeScenery, OpenRCT2::Ride& ride, + const CoordsXYZD& coords); +void TrackDesignPreviewRemoveGhosts(const TrackDesign& td, OpenRCT2::Ride& ride, const CoordsXYZD& coords); void TrackDesignPreviewDrawOutlines( - TrackDesignState& tds, const TrackDesign& td, Ride& ride, const CoordsXYZD& coords, bool placeScenery); -int32_t TrackDesignGetZPlacement(const TrackDesign& td, Ride& ride, const CoordsXYZD& coords); + TrackDesignState& tds, const TrackDesign& td, OpenRCT2::Ride& ride, const CoordsXYZD& coords, bool placeScenery); +int32_t TrackDesignGetZPlacement(const TrackDesign& td, OpenRCT2::Ride& ride, const CoordsXYZD& coords); /////////////////////////////////////////////////////////////////////////////// // Track design preview diff --git a/src/openrct2/ride/TrackIteration.h b/src/openrct2/ride/TrackIteration.h index 35edc6147c..2a6e63d208 100644 --- a/src/openrct2/ride/TrackIteration.h +++ b/src/openrct2/ride/TrackIteration.h @@ -2,10 +2,9 @@ #include "../world/Location.hpp" -struct Ride; - namespace OpenRCT2 { + struct Ride; struct TrackElement; struct TrackCircuitIterator diff --git a/src/openrct2/ride/TrackPaint.h b/src/openrct2/ride/TrackPaint.h index c663863b87..322c55ca46 100644 --- a/src/openrct2/ride/TrackPaint.h +++ b/src/openrct2/ride/TrackPaint.h @@ -17,10 +17,10 @@ namespace OpenRCT2 { - class StationObject; -} + struct Ride; -struct Ride; + class StationObject; +} // namespace OpenRCT2 constexpr uint8_t kTrackMap2x2[][4] = { { 0, 1, 2, 3 }, @@ -413,13 +413,14 @@ ImageId GetStationColourScheme(PaintSession& session, const OpenRCT2::TrackEleme ImageId GetShopSupportColourScheme(PaintSession& session, const OpenRCT2::TrackElement& trackElement); bool TrackPaintUtilHasFence( - enum edge_t edge, const CoordsXY& position, const OpenRCT2::TrackElement& trackElement, const Ride& ride, uint8_t rotation); + enum edge_t edge, const CoordsXY& position, const OpenRCT2::TrackElement& trackElement, const OpenRCT2::Ride& ride, + uint8_t rotation); void TrackPaintUtilPaintFloor( PaintSession& session, uint8_t edges, ImageId colourFlags, uint16_t height, const uint32_t floorSprites[4], const OpenRCT2::StationObject* stationStyle); void TrackPaintUtilPaintFences( PaintSession& session, uint8_t edges, const CoordsXY& position, const OpenRCT2::TrackElement& trackElement, - const Ride& ride, ImageId colourFlags, uint16_t height, const uint32_t fenceSprites[4], uint8_t rotation); + const OpenRCT2::Ride& ride, ImageId colourFlags, uint16_t height, const uint32_t fenceSprites[4], uint8_t rotation); enum class StationBaseType { @@ -437,20 +438,21 @@ bool TrackPaintUtilDrawStationCovers2( PaintSession& session, enum edge_t edge, bool hasFence, const OpenRCT2::StationObject* stationObject, uint16_t height, uint8_t stationVariant, ImageId colour); bool TrackPaintUtilDrawNarrowStationPlatform( - PaintSession& session, const Ride& ride, Direction direction, int32_t height, int32_t zOffset, + PaintSession& session, const OpenRCT2::Ride& ride, Direction direction, int32_t height, int32_t zOffset, const OpenRCT2::TrackElement& trackElement, StationBaseType baseType, int32_t baseOffsetZ); bool TrackPaintUtilDrawStation( - PaintSession& session, const Ride& ride, Direction direction, uint16_t height, const OpenRCT2::TrackElement& trackElement, - StationBaseType baseType, int32_t baseOffsetZ); + PaintSession& session, const OpenRCT2::Ride& ride, Direction direction, uint16_t height, + const OpenRCT2::TrackElement& trackElement, StationBaseType baseType, int32_t baseOffsetZ); bool TrackPaintUtilDrawStation2( - PaintSession& session, const Ride& ride, Direction direction, uint16_t height, const OpenRCT2::TrackElement& trackElement, - StationBaseType baseType, int32_t baseOffsetZ, int32_t fenceOffsetA, int32_t fenceOffsetB); + PaintSession& session, const OpenRCT2::Ride& ride, Direction direction, uint16_t height, + const OpenRCT2::TrackElement& trackElement, StationBaseType baseType, int32_t baseOffsetZ, int32_t fenceOffsetA, + int32_t fenceOffsetB); bool TrackPaintUtilDrawStationInverted( - PaintSession& session, const Ride& ride, Direction direction, int32_t height, const OpenRCT2::TrackElement& trackElement, - uint8_t stationVariant); + PaintSession& session, const OpenRCT2::Ride& ride, Direction direction, int32_t height, + const OpenRCT2::TrackElement& trackElement, uint8_t stationVariant); bool TrackPaintUtilShouldPaintSupports(const CoordsXY& position); void TrackPaintUtilDrawPier( - PaintSession& session, const Ride& ride, const OpenRCT2::StationObject* stationObject, const CoordsXY& position, + PaintSession& session, const OpenRCT2::Ride& ride, const OpenRCT2::StationObject* stationObject, const CoordsXY& position, Direction direction, int32_t height, const OpenRCT2::TrackElement& trackElement, uint8_t rotation); inline void TrackPaintUtilDrawStationTunnel(PaintSession& session, Direction direction, int32_t height) { @@ -564,11 +566,11 @@ void DrawSBendRightSupports( int32_t specialA, int32_t specialB); using TrackPaintFunction = void (&)( - PaintSession& session, const Ride& ride, uint8_t trackSequence, Direction direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, Direction direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); void TrackPaintFunctionDummy( - PaintSession& session, const Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, + PaintSession& session, const OpenRCT2::Ride& ride, uint8_t trackSequence, uint8_t direction, int32_t height, const OpenRCT2::TrackElement& trackElement, SupportType supportType); TrackPaintFunction GetTrackPaintFunctionStandUpRC(OpenRCT2::TrackElemType trackType); diff --git a/src/openrct2/ride/TrainManager.h b/src/openrct2/ride/TrainManager.h index 3da3a6e1cb..ca9c5babd3 100644 --- a/src/openrct2/ride/TrainManager.h +++ b/src/openrct2/ride/TrainManager.h @@ -12,7 +12,10 @@ #include -struct Vehicle; +namespace OpenRCT2 +{ + struct Vehicle; +} namespace OpenRCT2::TrainManager { diff --git a/src/openrct2/ride/Vehicle.Animation.cpp b/src/openrct2/ride/Vehicle.Animation.cpp index b0575d9152..68dbb50cf2 100644 --- a/src/openrct2/ride/Vehicle.Animation.cpp +++ b/src/openrct2/ride/Vehicle.Animation.cpp @@ -26,1024 +26,999 @@ #include -using namespace OpenRCT2; -using namespace OpenRCT2::Audio; -using namespace OpenRCT2::TrackMetadata; - -constexpr int16_t kVehicleMaxSpinSpeed = 1536; -constexpr int16_t kVehicleMinSpinSpeed = -kVehicleMaxSpinSpeed; - -/** - * - * rct2: 0x006D9249 - */ -void Vehicle::UpdateSwinging() +namespace OpenRCT2 { - auto curRide = GetRide(); - if (curRide == nullptr) - return; + using namespace OpenRCT2::Audio; + using namespace OpenRCT2::TrackMetadata; - auto rideEntry = GetRideEntry(); - if (rideEntry == nullptr) - return; + constexpr int16_t kVehicleMaxSpinSpeed = 1536; + constexpr int16_t kVehicleMinSpinSpeed = -kVehicleMaxSpinSpeed; - // SubState for this ride means swinging state - // 0 == first swing - // 3 == full swing - uint8_t swingState = sub_state; - if (rideEntry->flags.has(RideEntryFlag::inverterShipSwingMode)) + /** + * + * rct2: 0x006D9249 + */ + void Vehicle::UpdateSwinging() { - swingState += 4; - if (rideEntry->flags.has(RideEntryFlag::magicCarpetSwingMode)) + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + auto rideEntry = GetRideEntry(); + if (rideEntry == nullptr) + return; + + // SubState for this ride means swinging state + // 0 == first swing + // 3 == full swing + uint8_t swingState = sub_state; + if (rideEntry->flags.has(RideEntryFlag::inverterShipSwingMode)) + { swingState += 4; - } - - const auto spriteMap = kSwingingTimeToSpriteMaps[swingState]; - int8_t spriteType = spriteMap[current_time + 1]; - - // 0x80 indicates that a complete swing has been - // completed and the next swing can start - if (spriteType != -128) - { - current_time++; - if (static_cast(spriteType) != flatRideAnimationFrame) - { - // Used to know which sprite to draw - flatRideAnimationFrame = static_cast(spriteType); - invalidate(); + if (rideEntry->flags.has(RideEntryFlag::magicCarpetSwingMode)) + swingState += 4; } - return; - } - current_time = -1; - NumSwings++; - if (curRide->status != RideStatus::closed) - { - // It takes 3 swings to get into full swing - // ride->rotations already takes this into account - if (NumSwings + 3 < curRide->rotations) + const auto spriteMap = kSwingingTimeToSpriteMaps[swingState]; + int8_t spriteType = spriteMap[current_time + 1]; + + // 0x80 indicates that a complete swing has been + // completed and the next swing can start + if (spriteType != -128) { - // Go to the next swing state until we - // are at full swing. - if (sub_state != 3) + current_time++; + if (static_cast(spriteType) != flatRideAnimationFrame) { - sub_state++; + // Used to know which sprite to draw + flatRideAnimationFrame = static_cast(spriteType); + invalidate(); } - UpdateSwinging(); return; } - } - // To get to this part of the code the - // swing has to be in slowing down phase - if (sub_state == 0) - { - SetState(Status::arriving); - var_C0 = 0; - return; - } - // Go towards first swing state - sub_state--; - UpdateSwinging(); -} - -/** - * - * rct2: 0x006D9413 - */ -void Vehicle::UpdateFerrisWheelRotating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - if ((ferris_wheel_var_1 -= 1) != 0) - return; - - int8_t curFerrisWheelVar0 = ferris_wheel_var_0; - - if (curFerrisWheelVar0 == 3) - { - ferris_wheel_var_0 = curFerrisWheelVar0; - ferris_wheel_var_1 = curFerrisWheelVar0; - } - else if (curFerrisWheelVar0 < 3) - { - if (curFerrisWheelVar0 != -8) - curFerrisWheelVar0--; - ferris_wheel_var_0 = curFerrisWheelVar0; - ferris_wheel_var_1 = -curFerrisWheelVar0; - } - else - { - curFerrisWheelVar0--; - ferris_wheel_var_0 = curFerrisWheelVar0; - ferris_wheel_var_1 = curFerrisWheelVar0; - } - - uint8_t rotation = flatRideAnimationFrame; - if (curRide->mode == RideMode::forwardRotation) - rotation++; - else - rotation--; - - rotation &= 0x7F; - flatRideAnimationFrame = rotation; - - if (rotation == sub_state) - NumRotations++; - - invalidate(); - - uint8_t subState = sub_state; - if (curRide->mode == RideMode::forwardRotation) - subState++; - else - subState--; - subState &= 0x7F; - - if (subState == flatRideAnimationFrame) - { - bool shouldStop = true; + current_time = -1; + NumSwings++; if (curRide->status != RideStatus::closed) { - if (NumRotations < curRide->rotations) - shouldStop = false; - } - - if (shouldStop) - { - curFerrisWheelVar0 = ferris_wheel_var_0; - ferris_wheel_var_0 = -abs(curFerrisWheelVar0); - ferris_wheel_var_1 = abs(curFerrisWheelVar0); - } - } - - if (ferris_wheel_var_0 != -8) - return; - - subState = sub_state; - if (curRide->mode == RideMode::forwardRotation) - subState += 8; - else - subState -= 8; - subState &= 0x7F; - - if (subState != flatRideAnimationFrame) - return; - - SetState(Status::arriving); - var_C0 = 0; -} - -/** - * - * rct2: 0x006D94F2 - */ -void Vehicle::UpdateSimulatorOperating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - assert(current_time >= -1); - assert(current_time < MotionSimulatorTimeToSpriteMapCount); - uint8_t al = MotionSimulatorTimeToSpriteMap[current_time + 1]; - if (al != 0xFF) - { - current_time++; - if (al == flatRideAnimationFrame) - return; - flatRideAnimationFrame = al; - invalidate(); - return; - } - - SetState(Status::arriving); - var_C0 = 0; -} - -void UpdateRotatingDefault(Vehicle& vehicle) -{ - vehicle.sub_state = 1; - vehicle.UpdateRotating(); -} - -void UpdateRotatingEnterprise(Vehicle& vehicle) -{ - if (vehicle.sub_state == 2) - { - vehicle.SetState(Vehicle::Status::arriving); - vehicle.var_C0 = 0; - return; - } - - UpdateRotatingDefault(vehicle); -} - -/** - * - * rct2: 0x006D92FF - */ -void Vehicle::UpdateRotating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - auto rideEntry = GetRideEntry(); - if (rideEntry == nullptr) - { - return; - } - - const uint8_t* timeToSpriteMap; - if (rideEntry->flags.has(RideEntryFlag::hasTwistRotationType)) - { - timeToSpriteMap = kTwistTimeToSpriteMaps[sub_state]; - } - else if (rideEntry->flags.has(RideEntryFlag::hasEnterpriseRotationType)) - { - timeToSpriteMap = kEnterpriseTimeToSpriteMaps[sub_state]; - } - else - { - timeToSpriteMap = kMerryGoRoundTimeToSpriteMaps[sub_state]; - } - - uint16_t time = current_time; - if (_vehicleBreakdown == Breakdown::controlFailure) - { - time += (curRide->breakdownSoundModifier >> 6) + 1; - } - time++; - - uint8_t sprite = timeToSpriteMap[time]; - if (sprite != 0xFF) - { - current_time = time; - if (sprite == flatRideAnimationFrame) - return; - flatRideAnimationFrame = sprite; - invalidate(); - return; - } - - current_time = -1; - NumRotations++; - if (_vehicleBreakdown != Breakdown::controlFailure) - { - bool shouldStop = true; - if (curRide->status != RideStatus::closed) - { - sprite = NumRotations + 1; - if (curRide->getRideTypeDescriptor().specialType == RtdSpecialType::enterprise) - sprite += 9; - - if (sprite < curRide->rotations) - shouldStop = false; - } - - if (shouldStop) - { - if (sub_state == 2) + // It takes 3 swings to get into full swing + // ride->rotations already takes this into account + if (NumSwings + 3 < curRide->rotations) { - SetState(Status::arriving); - var_C0 = 0; + // Go to the next swing state until we + // are at full swing. + if (sub_state != 3) + { + sub_state++; + } + UpdateSwinging(); return; } - sub_state++; - UpdateRotating(); + } + + // To get to this part of the code the + // swing has to be in slowing down phase + if (sub_state == 0) + { + SetState(Status::arriving); + var_C0 = 0; return; } + // Go towards first swing state + sub_state--; + UpdateSwinging(); } - const auto& rtd = GetRideTypeDescriptor(curRide->type); - rtd.UpdateRotating(*this); -} - -/** - * - * rct2: 0x006D97CB - */ -void Vehicle::UpdateSpaceRingsOperating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - uint8_t spriteType = kSpaceRingsTimeToSpriteMap[current_time + 1]; - if (spriteType != 255) + /** + * + * rct2: 0x006D9413 + */ + void Vehicle::UpdateFerrisWheelRotating() { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + if ((ferris_wheel_var_1 -= 1) != 0) + return; + + int8_t curFerrisWheelVar0 = ferris_wheel_var_0; + + if (curFerrisWheelVar0 == 3) + { + ferris_wheel_var_0 = curFerrisWheelVar0; + ferris_wheel_var_1 = curFerrisWheelVar0; + } + else if (curFerrisWheelVar0 < 3) + { + if (curFerrisWheelVar0 != -8) + curFerrisWheelVar0--; + ferris_wheel_var_0 = curFerrisWheelVar0; + ferris_wheel_var_1 = -curFerrisWheelVar0; + } + else + { + curFerrisWheelVar0--; + ferris_wheel_var_0 = curFerrisWheelVar0; + ferris_wheel_var_1 = curFerrisWheelVar0; + } + + uint8_t rotation = flatRideAnimationFrame; + if (curRide->mode == RideMode::forwardRotation) + rotation++; + else + rotation--; + + rotation &= 0x7F; + flatRideAnimationFrame = rotation; + + if (rotation == sub_state) + NumRotations++; + + invalidate(); + + uint8_t subState = sub_state; + if (curRide->mode == RideMode::forwardRotation) + subState++; + else + subState--; + subState &= 0x7F; + + if (subState == flatRideAnimationFrame) + { + bool shouldStop = true; + if (curRide->status != RideStatus::closed) + { + if (NumRotations < curRide->rotations) + shouldStop = false; + } + + if (shouldStop) + { + curFerrisWheelVar0 = ferris_wheel_var_0; + ferris_wheel_var_0 = -abs(curFerrisWheelVar0); + ferris_wheel_var_1 = abs(curFerrisWheelVar0); + } + } + + if (ferris_wheel_var_0 != -8) + return; + + subState = sub_state; + if (curRide->mode == RideMode::forwardRotation) + subState += 8; + else + subState -= 8; + subState &= 0x7F; + + if (subState != flatRideAnimationFrame) + return; + + SetState(Status::arriving); + var_C0 = 0; + } + + /** + * + * rct2: 0x006D94F2 + */ + void Vehicle::UpdateSimulatorOperating() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + assert(current_time >= -1); + assert(current_time < MotionSimulatorTimeToSpriteMapCount); + uint8_t al = MotionSimulatorTimeToSpriteMap[current_time + 1]; + if (al != 0xFF) + { + current_time++; + if (al == flatRideAnimationFrame) + return; + flatRideAnimationFrame = al; + invalidate(); + return; + } + + SetState(Status::arriving); + var_C0 = 0; + } + + void UpdateRotatingDefault(Vehicle& vehicle) + { + vehicle.sub_state = 1; + vehicle.UpdateRotating(); + } + + void UpdateRotatingEnterprise(Vehicle& vehicle) + { + if (vehicle.sub_state == 2) + { + vehicle.SetState(Vehicle::Status::arriving); + vehicle.var_C0 = 0; + return; + } + + UpdateRotatingDefault(vehicle); + } + + /** + * + * rct2: 0x006D92FF + */ + void Vehicle::UpdateRotating() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + auto rideEntry = GetRideEntry(); + if (rideEntry == nullptr) + { + return; + } + + const uint8_t* timeToSpriteMap; + if (rideEntry->flags.has(RideEntryFlag::hasTwistRotationType)) + { + timeToSpriteMap = kTwistTimeToSpriteMaps[sub_state]; + } + else if (rideEntry->flags.has(RideEntryFlag::hasEnterpriseRotationType)) + { + timeToSpriteMap = kEnterpriseTimeToSpriteMaps[sub_state]; + } + else + { + timeToSpriteMap = kMerryGoRoundTimeToSpriteMaps[sub_state]; + } + + uint16_t time = current_time; + if (_vehicleBreakdown == Breakdown::controlFailure) + { + time += (curRide->breakdownSoundModifier >> 6) + 1; + } + time++; + + uint8_t sprite = timeToSpriteMap[time]; + if (sprite != 0xFF) + { + current_time = time; + if (sprite == flatRideAnimationFrame) + return; + flatRideAnimationFrame = sprite; + invalidate(); + return; + } + + current_time = -1; + NumRotations++; + if (_vehicleBreakdown != Breakdown::controlFailure) + { + bool shouldStop = true; + if (curRide->status != RideStatus::closed) + { + sprite = NumRotations + 1; + if (curRide->getRideTypeDescriptor().specialType == RtdSpecialType::enterprise) + sprite += 9; + + if (sprite < curRide->rotations) + shouldStop = false; + } + + if (shouldStop) + { + if (sub_state == 2) + { + SetState(Status::arriving); + var_C0 = 0; + return; + } + sub_state++; + UpdateRotating(); + return; + } + } + + const auto& rtd = GetRideTypeDescriptor(curRide->type); + rtd.UpdateRotating(*this); + } + + /** + * + * rct2: 0x006D97CB + */ + void Vehicle::UpdateSpaceRingsOperating() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + uint8_t spriteType = kSpaceRingsTimeToSpriteMap[current_time + 1]; + if (spriteType != 255) + { + current_time++; + if (spriteType != flatRideAnimationFrame) + { + flatRideAnimationFrame = spriteType; + invalidate(); + } + } + else + { + SetState(Status::arriving); + var_C0 = 0; + } + } + + /** + * + * rct2: 0x006D9641 + */ + void Vehicle::UpdateHauntedHouseOperating() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + if (flatRideAnimationFrame != 0) + { + if (getGameState().currentTicks & 1) + { + flatRideAnimationFrame++; + invalidate(); + + if (flatRideAnimationFrame == 19) + flatRideAnimationFrame = 0; + } + } + + if (current_time + 1 > 1500) + { + SetState(Status::arriving); + var_C0 = 0; + return; + } + current_time++; - if (spriteType != flatRideAnimationFrame) + switch (current_time) { - flatRideAnimationFrame = spriteType; - invalidate(); - } - } - else - { - SetState(Status::arriving); - var_C0 = 0; - } -} - -/** - * - * rct2: 0x006D9641 - */ -void Vehicle::UpdateHauntedHouseOperating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - if (flatRideAnimationFrame != 0) - { - if (getGameState().currentTicks & 1) - { - flatRideAnimationFrame++; - invalidate(); - - if (flatRideAnimationFrame == 19) - flatRideAnimationFrame = 0; + case 45: + Play3D(SoundId::hauntedHouseScare, getLocation()); + break; + case 75: + flatRideAnimationFrame = 1; + invalidate(); + break; + case 400: + Play3D(SoundId::hauntedHouseScream1, getLocation()); + break; + case 745: + Play3D(SoundId::hauntedHouseScare, getLocation()); + break; + case 775: + flatRideAnimationFrame = 1; + invalidate(); + break; + case 1100: + Play3D(SoundId::hauntedHouseScream2, getLocation()); + break; } } - if (current_time + 1 > 1500) + /** + * + * rct2: 0x006d9781 + */ + void Vehicle::UpdateCrookedHouseOperating() { - SetState(Status::arriving); - var_C0 = 0; - return; - } + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; - current_time++; - switch (current_time) - { - case 45: - Play3D(SoundId::hauntedHouseScare, getLocation()); - break; - case 75: - flatRideAnimationFrame = 1; - invalidate(); - break; - case 400: - Play3D(SoundId::hauntedHouseScream1, getLocation()); - break; - case 745: - Play3D(SoundId::hauntedHouseScare, getLocation()); - break; - case 775: - flatRideAnimationFrame = 1; - invalidate(); - break; - case 1100: - Play3D(SoundId::hauntedHouseScream2, getLocation()); - break; - } -} - -/** - * - * rct2: 0x006d9781 - */ -void Vehicle::UpdateCrookedHouseOperating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - // Originally used an array of size 1 at 0x009A0AC4 and passed the sub state into it. - if (static_cast(current_time + 1) > 600) - { - SetState(Status::arriving); - var_C0 = 0; - return; - } - - current_time++; -} - -/** - * - * rct2: 0x006D9547 - */ -void Vehicle::UpdateTopSpinOperating() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - const TopSpinTimeToSpriteMap* sprite_map = kTopSpinTimeToSpriteMaps[sub_state]; - uint8_t rotation = sprite_map[current_time + 1].arm_rotation; - if (rotation != 0xFF) - { - current_time = current_time + 1; - if (rotation != flatRideAnimationFrame) + // Originally used an array of size 1 at 0x009A0AC4 and passed the sub state into it. + if (static_cast(current_time + 1) > 600) { - flatRideAnimationFrame = rotation; - invalidate(); + SetState(Status::arriving); + var_C0 = 0; + return; } - rotation = sprite_map[current_time].bank_rotation; - if (rotation != flatRideSecondaryAnimationFrame) + + current_time++; + } + + /** + * + * rct2: 0x006D9547 + */ + void Vehicle::UpdateTopSpinOperating() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + const TopSpinTimeToSpriteMap* sprite_map = kTopSpinTimeToSpriteMaps[sub_state]; + uint8_t rotation = sprite_map[current_time + 1].arm_rotation; + if (rotation != 0xFF) { - flatRideSecondaryAnimationFrame = rotation; - invalidate(); - } - return; - } - - SetState(Status::arriving); - var_C0 = 0; -} - -/** - * - * rct2: 0x006D95AD - */ -void Vehicle::UpdateShowingFilm() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - int32_t totalTime = kRideFilmLength[sub_state]; - int32_t currentTime = current_time + 1; - if (currentTime <= totalTime) - { - current_time = currentTime; - } - else - { - SetState(Status::arriving); - var_C0 = 0; - } -} - -/** - * - * rct2: 0x006D95F7 - */ -void Vehicle::UpdateDoingCircusShow() -{ - if (_vehicleBreakdown == Breakdown::safetyCutOut) - return; - - int32_t currentTime = current_time + 1; - if (currentTime <= 5000) - { - current_time = currentTime; - } - else - { - SetState(Status::arriving); - var_C0 = 0; - } -} - -int32_t Vehicle::GetSwingAmount() const -{ - switch (GetTrackType()) - { - case TrackElemType::leftQuarterTurn5Tiles: - case TrackElemType::bankedLeftQuarterTurn5Tiles: - case TrackElemType::leftQuarterTurn5TilesUp25: - case TrackElemType::leftQuarterTurn5TilesDown25: - case TrackElemType::leftQuarterTurn5TilesCovered: - case TrackElemType::leftHalfBankedHelixUpLarge: - case TrackElemType::leftHalfBankedHelixDownLarge: - case TrackElemType::leftQuarterBankedHelixLargeUp: - case TrackElemType::leftQuarterBankedHelixLargeDown: - case TrackElemType::leftQuarterHelixLargeUp: - case TrackElemType::leftQuarterHelixLargeDown: - case TrackElemType::leftBankedQuarterTurn5TileUp25: - case TrackElemType::leftBankedQuarterTurn5TileDown25: - // Loc6D67E1 - return 14; - - case TrackElemType::rightQuarterTurn5Tiles: - case TrackElemType::bankedRightQuarterTurn5Tiles: - case TrackElemType::rightQuarterTurn5TilesUp25: - case TrackElemType::rightQuarterTurn5TilesDown25: - case TrackElemType::rightQuarterTurn5TilesCovered: - case TrackElemType::rightHalfBankedHelixUpLarge: - case TrackElemType::rightHalfBankedHelixDownLarge: - case TrackElemType::rightQuarterBankedHelixLargeUp: - case TrackElemType::rightQuarterBankedHelixLargeDown: - case TrackElemType::rightQuarterHelixLargeUp: - case TrackElemType::rightQuarterHelixLargeDown: - case TrackElemType::rightBankedQuarterTurn5TileUp25: - case TrackElemType::rightBankedQuarterTurn5TileDown25: - // Loc6D6804 - return -14; - - case TrackElemType::sBendLeft: - case TrackElemType::sBendLeftCovered: - // Loc6D67EF - if (track_progress < 48) + current_time = current_time + 1; + if (rotation != flatRideAnimationFrame) { + flatRideAnimationFrame = rotation; + invalidate(); + } + rotation = sprite_map[current_time].bank_rotation; + if (rotation != flatRideSecondaryAnimationFrame) + { + flatRideSecondaryAnimationFrame = rotation; + invalidate(); + } + return; + } + + SetState(Status::arriving); + var_C0 = 0; + } + + /** + * + * rct2: 0x006D95AD + */ + void Vehicle::UpdateShowingFilm() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + int32_t totalTime = kRideFilmLength[sub_state]; + int32_t currentTime = current_time + 1; + if (currentTime <= totalTime) + { + current_time = currentTime; + } + else + { + SetState(Status::arriving); + var_C0 = 0; + } + } + + /** + * + * rct2: 0x006D95F7 + */ + void Vehicle::UpdateDoingCircusShow() + { + if (_vehicleBreakdown == Breakdown::safetyCutOut) + return; + + int32_t currentTime = current_time + 1; + if (currentTime <= 5000) + { + current_time = currentTime; + } + else + { + SetState(Status::arriving); + var_C0 = 0; + } + } + + int32_t Vehicle::GetSwingAmount() const + { + switch (GetTrackType()) + { + case TrackElemType::leftQuarterTurn5Tiles: + case TrackElemType::bankedLeftQuarterTurn5Tiles: + case TrackElemType::leftQuarterTurn5TilesUp25: + case TrackElemType::leftQuarterTurn5TilesDown25: + case TrackElemType::leftQuarterTurn5TilesCovered: + case TrackElemType::leftHalfBankedHelixUpLarge: + case TrackElemType::leftHalfBankedHelixDownLarge: + case TrackElemType::leftQuarterBankedHelixLargeUp: + case TrackElemType::leftQuarterBankedHelixLargeDown: + case TrackElemType::leftQuarterHelixLargeUp: + case TrackElemType::leftQuarterHelixLargeDown: + case TrackElemType::leftBankedQuarterTurn5TileUp25: + case TrackElemType::leftBankedQuarterTurn5TileDown25: + // Loc6D67E1 return 14; - } - return -15; - case TrackElemType::sBendRight: - case TrackElemType::sBendRightCovered: - // Loc6D67CC - if (track_progress < 48) - { + case TrackElemType::rightQuarterTurn5Tiles: + case TrackElemType::bankedRightQuarterTurn5Tiles: + case TrackElemType::rightQuarterTurn5TilesUp25: + case TrackElemType::rightQuarterTurn5TilesDown25: + case TrackElemType::rightQuarterTurn5TilesCovered: + case TrackElemType::rightHalfBankedHelixUpLarge: + case TrackElemType::rightHalfBankedHelixDownLarge: + case TrackElemType::rightQuarterBankedHelixLargeUp: + case TrackElemType::rightQuarterBankedHelixLargeDown: + case TrackElemType::rightQuarterHelixLargeUp: + case TrackElemType::rightQuarterHelixLargeDown: + case TrackElemType::rightBankedQuarterTurn5TileUp25: + case TrackElemType::rightBankedQuarterTurn5TileDown25: + // Loc6D6804 return -14; - } - return 15; - case TrackElemType::leftQuarterTurn3Tiles: - case TrackElemType::leftBankedQuarterTurn3Tiles: - case TrackElemType::leftQuarterTurn3TilesUp25: - case TrackElemType::leftQuarterTurn3TilesDown25: - case TrackElemType::leftQuarterTurn3TilesCovered: - case TrackElemType::leftHalfBankedHelixUpSmall: - case TrackElemType::leftHalfBankedHelixDownSmall: - case TrackElemType::leftBankToLeftQuarterTurn3TilesUp25: - case TrackElemType::leftQuarterTurn3TilesDown25ToLeftBank: - case TrackElemType::leftCurvedLiftHill: - case TrackElemType::leftBankedQuarterTurn3TileUp25: - case TrackElemType::leftBankedQuarterTurn3TileDown25: - // Loc6D67BE - return 13; + case TrackElemType::sBendLeft: + case TrackElemType::sBendLeftCovered: + // Loc6D67EF + if (track_progress < 48) + { + return 14; + } + return -15; - case TrackElemType::rightQuarterTurn3Tiles: - case TrackElemType::rightBankedQuarterTurn3Tiles: - case TrackElemType::rightQuarterTurn3TilesUp25: - case TrackElemType::rightQuarterTurn3TilesDown25: - case TrackElemType::rightQuarterTurn3TilesCovered: - case TrackElemType::rightHalfBankedHelixUpSmall: - case TrackElemType::rightHalfBankedHelixDownSmall: - case TrackElemType::rightBankToRightQuarterTurn3TilesUp25: - case TrackElemType::rightQuarterTurn3TilesDown25ToRightBank: - case TrackElemType::rightCurvedLiftHill: - case TrackElemType::rightBankedQuarterTurn3TileUp25: - case TrackElemType::rightBankedQuarterTurn3TileDown25: - // Loc6D67B0 - return -13; + case TrackElemType::sBendRight: + case TrackElemType::sBendRightCovered: + // Loc6D67CC + if (track_progress < 48) + { + return -14; + } + return 15; - case TrackElemType::leftQuarterTurn1Tile: - case TrackElemType::leftQuarterTurn1TileUp60: - case TrackElemType::leftQuarterTurn1TileDown60: - // Loc6D67A2 + case TrackElemType::leftQuarterTurn3Tiles: + case TrackElemType::leftBankedQuarterTurn3Tiles: + case TrackElemType::leftQuarterTurn3TilesUp25: + case TrackElemType::leftQuarterTurn3TilesDown25: + case TrackElemType::leftQuarterTurn3TilesCovered: + case TrackElemType::leftHalfBankedHelixUpSmall: + case TrackElemType::leftHalfBankedHelixDownSmall: + case TrackElemType::leftBankToLeftQuarterTurn3TilesUp25: + case TrackElemType::leftQuarterTurn3TilesDown25ToLeftBank: + case TrackElemType::leftCurvedLiftHill: + case TrackElemType::leftBankedQuarterTurn3TileUp25: + case TrackElemType::leftBankedQuarterTurn3TileDown25: + // Loc6D67BE + return 13; + + case TrackElemType::rightQuarterTurn3Tiles: + case TrackElemType::rightBankedQuarterTurn3Tiles: + case TrackElemType::rightQuarterTurn3TilesUp25: + case TrackElemType::rightQuarterTurn3TilesDown25: + case TrackElemType::rightQuarterTurn3TilesCovered: + case TrackElemType::rightHalfBankedHelixUpSmall: + case TrackElemType::rightHalfBankedHelixDownSmall: + case TrackElemType::rightBankToRightQuarterTurn3TilesUp25: + case TrackElemType::rightQuarterTurn3TilesDown25ToRightBank: + case TrackElemType::rightCurvedLiftHill: + case TrackElemType::rightBankedQuarterTurn3TileUp25: + case TrackElemType::rightBankedQuarterTurn3TileDown25: + // Loc6D67B0 + return -13; + + case TrackElemType::leftQuarterTurn1Tile: + case TrackElemType::leftQuarterTurn1TileUp60: + case TrackElemType::leftQuarterTurn1TileDown60: + // Loc6D67A2 + return 12; + + case TrackElemType::rightQuarterTurn1Tile: + case TrackElemType::rightQuarterTurn1TileUp60: + case TrackElemType::rightQuarterTurn1TileDown60: + // Loc6D6794 + return -12; + + case TrackElemType::leftEighthToDiag: + case TrackElemType::leftEighthToOrthogonal: + case TrackElemType::leftEighthBankToDiag: + case TrackElemType::leftEighthBankToOrthogonal: + // Loc6D67D3 + return 15; + + case TrackElemType::rightEighthToDiag: + case TrackElemType::rightEighthToOrthogonal: + case TrackElemType::rightEighthBankToDiag: + case TrackElemType::rightEighthBankToOrthogonal: + // Loc6D67F6 + return -15; + default: + return 0; + } + } + + static uint8_t GetSwingSprite(int16_t swingPosition) + { + if (swingPosition < -10010) + return 11; + if (swingPosition > 10010) return 12; - case TrackElemType::rightQuarterTurn1Tile: - case TrackElemType::rightQuarterTurn1TileUp60: - case TrackElemType::rightQuarterTurn1TileDown60: - // Loc6D6794 - return -12; + if (swingPosition < -8190) + return 9; + if (swingPosition > 8190) + return 10; - case TrackElemType::leftEighthToDiag: - case TrackElemType::leftEighthToOrthogonal: - case TrackElemType::leftEighthBankToDiag: - case TrackElemType::leftEighthBankToOrthogonal: - // Loc6D67D3 - return 15; + if (swingPosition < -6370) + return 7; + if (swingPosition > 6370) + return 8; - case TrackElemType::rightEighthToDiag: - case TrackElemType::rightEighthToOrthogonal: - case TrackElemType::rightEighthBankToDiag: - case TrackElemType::rightEighthBankToOrthogonal: - // Loc6D67F6 - return -15; - default: - return 0; - } -} + if (swingPosition < -4550) + return 5; + if (swingPosition > 4550) + return 6; -static uint8_t GetSwingSprite(int16_t swingPosition) -{ - if (swingPosition < -10010) - return 11; - if (swingPosition > 10010) - return 12; + if (swingPosition < -2730) + return 3; + if (swingPosition > 2730) + return 4; - if (swingPosition < -8190) - return 9; - if (swingPosition > 8190) - return 10; + if (swingPosition < -910) + return 1; + if (swingPosition > 910) + return 2; - if (swingPosition < -6370) - return 7; - if (swingPosition > 6370) - return 8; - - if (swingPosition < -4550) - return 5; - if (swingPosition > 4550) - return 6; - - if (swingPosition < -2730) - return 3; - if (swingPosition > 2730) - return 4; - - if (swingPosition < -910) - return 1; - if (swingPosition > 910) - return 2; - - return 0; -} - -/** - * - * rct2: 0x006D6776 - */ -void Vehicle::UpdateSwingingCar() -{ - int32_t dword_F64E08 = abs(_vehicleVelocityF64E08); - if (flags.has(VehicleFlag::carIsReversed)) - { - dword_F64E08 *= -1; - } - SwingSpeed += (-SwingPosition) >> 6; - int32_t swingAmount = GetSwingAmount(); - if (swingAmount < 0) - { - SwingSpeed -= dword_F64E08 >> (-swingAmount); - } - else if (swingAmount > 0) - { - SwingSpeed += dword_F64E08 >> swingAmount; + return 0; } - auto carEntry = Entry(); - if (carEntry == nullptr) + /** + * + * rct2: 0x006D6776 + */ + void Vehicle::UpdateSwingingCar() { - return; - } - int16_t dx = 3185; - if (carEntry->flags.has(CarEntryFlag::useSuspendedSwing)) - { - dx = 5006; - } - if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing)) - { - dx = 1820; - } - int16_t cx = -dx; + int32_t dword_F64E08 = abs(_vehicleVelocityF64E08); + if (flags.has(VehicleFlag::carIsReversed)) + { + dword_F64E08 *= -1; + } + SwingSpeed += (-SwingPosition) >> 6; + int32_t swingAmount = GetSwingAmount(); + if (swingAmount < 0) + { + SwingSpeed -= dword_F64E08 >> (-swingAmount); + } + else if (swingAmount > 0) + { + SwingSpeed += dword_F64E08 >> swingAmount; + } - if (carEntry->flags.has(CarEntryFlag::useSlideSwing)) - { - dx = 5370; - cx = -5370; + auto carEntry = Entry(); + if (carEntry == nullptr) + { + return; + } + int16_t dx = 3185; + if (carEntry->flags.has(CarEntryFlag::useSuspendedSwing)) + { + dx = 5006; + } + if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing)) + { + dx = 1820; + } + int16_t cx = -dx; + if (carEntry->flags.has(CarEntryFlag::useSlideSwing)) + { + dx = 5370; + cx = -5370; + + auto trackType = GetTrackType(); + switch (trackType) + { + case TrackElemType::bankedLeftQuarterTurn5Tiles: + case TrackElemType::leftBank: + case TrackElemType::leftBankedQuarterTurn3Tiles: + dx = 10831; + cx = -819; + break; + case TrackElemType::bankedRightQuarterTurn5Tiles: + case TrackElemType::rightBank: + case TrackElemType::rightBankedQuarterTurn3Tiles: + dx = 819; + cx = -10831; + break; + default: + break; + } + + if (trackTypeIsStation(trackType) || trackTypeIsBrakes(trackType) || trackTypeIsBlockBrakes(trackType)) + { + dx = 0; + cx = 0; + } + + if (flags.has(VehicleFlag::onLiftHill)) + { + dx = 0; + cx = 0; + } + } + + SwingPosition += SwingSpeed; + SwingSpeed -= SwingSpeed >> 5; + + if (SwingPosition > dx) + { + SwingPosition = dx; + SwingSpeed = 0; + } + if (SwingPosition < cx) + { + SwingPosition = cx; + SwingSpeed = 0; + } + + uint8_t swingSprite = GetSwingSprite(SwingPosition); + + if (swingSprite != SwingSprite) + { + SwingSprite = swingSprite; + invalidate(); + } + } + + /** + * + * rct2: 0x006D661F + */ + void Vehicle::UpdateSpinningCar() + { + if (flags.has(VehicleFlag::spinningIsLocked)) + { + spin_speed = 0; + return; + } + + auto carEntry = Entry(); + if (carEntry == nullptr) + { + return; + } + int32_t spinningInertia = carEntry->spinning_inertia; auto trackType = GetTrackType(); - switch (trackType) + int32_t dword_F64E08 = _vehicleVelocityF64E08; + int32_t spinSpeed{}; + // An L spin adds to the spin speed, R does the opposite + // The number indicates how much right shift of the velocity will become spin + // The bigger the number the less change in spin. + + const auto& ted = GetTrackElementDescriptor(trackType); + switch (ted.spinFunction) { - case TrackElemType::bankedLeftQuarterTurn5Tiles: - case TrackElemType::leftBank: - case TrackElemType::leftBankedQuarterTurn3Tiles: - dx = 10831; - cx = -819; + case SpinFunction::rc: + // On a rotation control track element + spinningInertia += 6; + spinSpeed = dword_F64E08 >> spinningInertia; + // Alternate the spin direction (roughly). Perhaps in future save a value to the track + if (id.ToUnderlying() & 1) + { + spin_speed -= spinSpeed; + } + else + { + spin_speed += spinSpeed; + } break; - case TrackElemType::bankedRightQuarterTurn5Tiles: - case TrackElemType::rightBank: - case TrackElemType::rightBankedQuarterTurn3Tiles: - dx = 819; - cx = -10831; + case SpinFunction::r5: + // It looks like in the original there was going to be special code for whirlpool + // this has been removed and just uses R5 + spinningInertia += 5; + spin_speed -= dword_F64E08 >> spinningInertia; break; - default: + case SpinFunction::l5: + spinningInertia += 5; + spin_speed += dword_F64E08 >> spinningInertia; break; - } - - if (trackTypeIsStation(trackType) || trackTypeIsBrakes(trackType) || trackTypeIsBlockBrakes(trackType)) - { - dx = 0; - cx = 0; - } - - if (flags.has(VehicleFlag::onLiftHill)) - { - dx = 0; - cx = 0; - } - } - - SwingPosition += SwingSpeed; - SwingSpeed -= SwingSpeed >> 5; - - if (SwingPosition > dx) - { - SwingPosition = dx; - SwingSpeed = 0; - } - if (SwingPosition < cx) - { - SwingPosition = cx; - SwingSpeed = 0; - } - - uint8_t swingSprite = GetSwingSprite(SwingPosition); - - if (swingSprite != SwingSprite) - { - SwingSprite = swingSprite; - invalidate(); - } -} - -/** - * - * rct2: 0x006D661F - */ -void Vehicle::UpdateSpinningCar() -{ - if (flags.has(VehicleFlag::spinningIsLocked)) - { - spin_speed = 0; - return; - } - - auto carEntry = Entry(); - if (carEntry == nullptr) - { - return; - } - int32_t spinningInertia = carEntry->spinning_inertia; - auto trackType = GetTrackType(); - int32_t dword_F64E08 = _vehicleVelocityF64E08; - int32_t spinSpeed{}; - // An L spin adds to the spin speed, R does the opposite - // The number indicates how much right shift of the velocity will become spin - // The bigger the number the less change in spin. - - const auto& ted = GetTrackElementDescriptor(trackType); - switch (ted.spinFunction) - { - case SpinFunction::rc: - // On a rotation control track element - spinningInertia += 6; - spinSpeed = dword_F64E08 >> spinningInertia; - // Alternate the spin direction (roughly). Perhaps in future save a value to the track - if (id.ToUnderlying() & 1) - { - spin_speed -= spinSpeed; - } - else - { - spin_speed += spinSpeed; - } - break; - case SpinFunction::r5: - // It looks like in the original there was going to be special code for whirlpool - // this has been removed and just uses R5 - spinningInertia += 5; - spin_speed -= dword_F64E08 >> spinningInertia; - break; - case SpinFunction::l5: - spinningInertia += 5; - spin_speed += dword_F64E08 >> spinningInertia; - break; - case SpinFunction::r7: - spinningInertia += 7; - spin_speed -= dword_F64E08 >> spinningInertia; - break; - case SpinFunction::l7: - spinningInertia += 7; - spin_speed += dword_F64E08 >> spinningInertia; - break; - case SpinFunction::rl: - // Right Left Curve Track Piece - if (track_progress < 48) - { - // R8 + case SpinFunction::r7: + spinningInertia += 7; + spin_speed -= dword_F64E08 >> spinningInertia; + break; + case SpinFunction::l7: + spinningInertia += 7; + spin_speed += dword_F64E08 >> spinningInertia; + break; + case SpinFunction::rl: + // Right Left Curve Track Piece + if (track_progress < 48) + { + // R8 + spinningInertia += 8; + spin_speed -= dword_F64E08 >> spinningInertia; + break; + } + [[fallthrough]]; + case SpinFunction::l9: + spinningInertia += 9; + spin_speed += dword_F64E08 >> spinningInertia; + break; + case SpinFunction::l8: + spinningInertia += 8; + spin_speed += dword_F64E08 >> spinningInertia; + break; + case SpinFunction::sp: + // On rapids spin after fully on them + if (track_progress > 22) + { + // L5 + spinningInertia += 5; + spin_speed += dword_F64E08 >> spinningInertia; + } + break; + case SpinFunction::lr: + // Left Right Curve Track Piece + if (track_progress < 48) + { + // L8 + spinningInertia += 8; + spin_speed += dword_F64E08 >> spinningInertia; + break; + } + [[fallthrough]]; + case SpinFunction::r9: + spinningInertia += 9; + spin_speed -= dword_F64E08 >> spinningInertia; + break; + case SpinFunction::r8: spinningInertia += 8; spin_speed -= dword_F64E08 >> spinningInertia; break; - } - [[fallthrough]]; - case SpinFunction::l9: - spinningInertia += 9; - spin_speed += dword_F64E08 >> spinningInertia; - break; - case SpinFunction::l8: - spinningInertia += 8; - spin_speed += dword_F64E08 >> spinningInertia; - break; - case SpinFunction::sp: - // On rapids spin after fully on them - if (track_progress > 22) - { - // L5 - spinningInertia += 5; - spin_speed += dword_F64E08 >> spinningInertia; - } - break; - case SpinFunction::lr: - // Left Right Curve Track Piece - if (track_progress < 48) - { - // L8 - spinningInertia += 8; - spin_speed += dword_F64E08 >> spinningInertia; + case SpinFunction::none: break; - } - [[fallthrough]]; - case SpinFunction::r9: - spinningInertia += 9; - spin_speed -= dword_F64E08 >> spinningInertia; - break; - case SpinFunction::r8: - spinningInertia += 8; - spin_speed -= dword_F64E08 >> spinningInertia; - break; - case SpinFunction::none: - break; + } + + spinSpeed = std::clamp(spin_speed, kVehicleMinSpinSpeed, kVehicleMaxSpinSpeed); + spin_speed = spinSpeed; + spin_sprite += spinSpeed >> 8; + // Note this actually increases the spin speed if going right! + spin_speed -= spinSpeed >> carEntry->spinning_friction; + invalidate(); } - spinSpeed = std::clamp(spin_speed, kVehicleMinSpinSpeed, kVehicleMaxSpinSpeed); - spin_speed = spinSpeed; - spin_sprite += spinSpeed >> 8; - // Note this actually increases the spin speed if going right! - spin_speed -= spinSpeed >> carEntry->spinning_friction; - invalidate(); -} - -void Vehicle::UpdateAnimationAnimalFlying() -{ - if (animationState > 0) + void Vehicle::UpdateAnimationAnimalFlying() + { + if (animationState > 0) + { + animationState--; + return; + } + + if (animation_frame == 0) + { + auto trackType = GetTrackType(); + TileElement* trackElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); + if (trackElement != nullptr && trackElement->asTrack()->HasChain()) + { + // start flapping, bird + animation_frame = 1; + animationState = 5; + invalidate(); + } + } + else + { + // continue flapping until reaching frame 0 + animation_frame = (animation_frame + 1) % 4; + invalidate(); + } + // number of frames to skip before updating again + constexpr std::array frameWaitTimes = { 5, 3, 5, 3 }; + animationState = frameWaitTimes[animation_frame]; + } + + /** + * Get the frame of animation for the current animationState based on animation speed and animation frames + */ + static uint8_t GetTargetFrame(const CarEntry& carEntry, uint32_t animationState) + { + if (carEntry.AnimationSpeed == 0) + return 0; + auto targetFrame = animationState / (carEntry.AnimationSpeed << 2); + // mask of 0xFF + targetFrame &= std::numeric_limits::max(); + // multiply by number of frames. After the bitshift 8, the range will be 0 to AnimationFrames - 1 + targetFrame *= carEntry.AnimationFrames; + return targetFrame >> std::numeric_limits::digits; + } + + /** + * Compute the position that steam should be spawned + */ + static constexpr CoordsXYZ ComputeSteamOffset(int32_t height, int32_t length, VehiclePitch pitch, uint8_t yaw) + { + uint8_t trueYaw = Entity::Yaw::YawTo64(yaw); + auto offsets = Math::Trigonometry::PitchToDirectionVectorFromGeometry[EnumValue(pitch)]; + int32_t projectedRun = (offsets.x * length - offsets.y * height) / 256; + int32_t projectedHeight = (offsets.x * height + offsets.y * length) / 256; + return { Math::Trigonometry::ComputeXYVector(projectedRun, trueYaw), projectedHeight }; + } + + /** + * Decide based on current frame and number of frames if a steam particle should be generated on this frame + */ + static bool ShouldMakeSteam(uint8_t targetFrame, uint8_t animationFrames) + { + if (animationFrames < 1) + return false; + // steam is produced twice per wheel revolution + return targetFrame == 0 || targetFrame == animationFrames / 2; + } + + /** + * Dummy function + */ + static void AnimateNone(Vehicle& vehicle, const CarEntry& carEntry) { - animationState--; return; } - if (animation_frame == 0) + /** + * Animate the vehicle based on its speed + */ + static void AnimateSimpleVehicle(Vehicle& vehicle, const CarEntry& carEntry) { - auto trackType = GetTrackType(); - TileElement* trackElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); - if (trackElement != nullptr && trackElement->asTrack()->HasChain()) + vehicle.animationState += _vehicleVelocityF64E08; + uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState); + if (vehicle.animation_frame != targetFrame) { - // start flapping, bird - animation_frame = 1; - animationState = 5; - invalidate(); + vehicle.animation_frame = targetFrame; + vehicle.invalidate(); } } - else + + /** + * Animate the vehicle based on its speed plus add steam particles + */ + static void AnimateSteamLocomotive(Vehicle& vehicle, const CarEntry& carEntry) { - // continue flapping until reaching frame 0 - animation_frame = (animation_frame + 1) % 4; - invalidate(); - } - // number of frames to skip before updating again - constexpr std::array frameWaitTimes = { 5, 3, 5, 3 }; - animationState = frameWaitTimes[animation_frame]; -} - -/** - * Get the frame of animation for the current animationState based on animation speed and animation frames - */ -static uint8_t GetTargetFrame(const CarEntry& carEntry, uint32_t animationState) -{ - if (carEntry.AnimationSpeed == 0) - return 0; - auto targetFrame = animationState / (carEntry.AnimationSpeed << 2); - // mask of 0xFF - targetFrame &= std::numeric_limits::max(); - // multiply by number of frames. After the bitshift 8, the range will be 0 to AnimationFrames - 1 - targetFrame *= carEntry.AnimationFrames; - return targetFrame >> std::numeric_limits::digits; -} - -/** - * Compute the position that steam should be spawned - */ -static constexpr CoordsXYZ ComputeSteamOffset(int32_t height, int32_t length, VehiclePitch pitch, uint8_t yaw) -{ - uint8_t trueYaw = Entity::Yaw::YawTo64(yaw); - auto offsets = Math::Trigonometry::PitchToDirectionVectorFromGeometry[EnumValue(pitch)]; - int32_t projectedRun = (offsets.x * length - offsets.y * height) / 256; - int32_t projectedHeight = (offsets.x * height + offsets.y * length) / 256; - return { Math::Trigonometry::ComputeXYVector(projectedRun, trueYaw), projectedHeight }; -} - -/** - * Decide based on current frame and number of frames if a steam particle should be generated on this frame - */ -static bool ShouldMakeSteam(uint8_t targetFrame, uint8_t animationFrames) -{ - if (animationFrames < 1) - return false; - // steam is produced twice per wheel revolution - return targetFrame == 0 || targetFrame == animationFrames / 2; -} - -/** - * Dummy function - */ -static void AnimateNone(Vehicle& vehicle, const CarEntry& carEntry) -{ - return; -} - -/** - * Animate the vehicle based on its speed - */ -static void AnimateSimpleVehicle(Vehicle& vehicle, const CarEntry& carEntry) -{ - vehicle.animationState += _vehicleVelocityF64E08; - uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState); - if (vehicle.animation_frame != targetFrame) - { - vehicle.animation_frame = targetFrame; - vehicle.invalidate(); - } -} - -/** - * Animate the vehicle based on its speed plus add steam particles - */ -static void AnimateSteamLocomotive(Vehicle& vehicle, const CarEntry& carEntry) -{ - vehicle.animationState += _vehicleVelocityF64E08; - uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState); - if (vehicle.animation_frame != targetFrame) - { - vehicle.animation_frame = targetFrame; - if (ShouldMakeSteam(targetFrame, carEntry.AnimationFrames)) + vehicle.animationState += _vehicleVelocityF64E08; + uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState); + if (vehicle.animation_frame != targetFrame) { - auto curRide = vehicle.GetRide(); - if (curRide != nullptr) + vehicle.animation_frame = targetFrame; + if (ShouldMakeSteam(targetFrame, carEntry.AnimationFrames)) { - if (!RideHasStationShelter(*curRide) - || (vehicle.status != Vehicle::Status::movingToEndOfStation && vehicle.status != Vehicle::Status::arriving)) + auto curRide = vehicle.GetRide(); + if (curRide != nullptr) { - CoordsXYZ steamOffset = ComputeSteamOffset( - carEntry.SteamEffect.Vertical, carEntry.SteamEffect.Longitudinal, vehicle.pitch, vehicle.orientation); - SteamParticle::Create(CoordsXYZ(vehicle.x, vehicle.y, vehicle.z) + steamOffset); + if (!RideHasStationShelter(*curRide) + || (vehicle.status != Vehicle::Status::movingToEndOfStation + && vehicle.status != Vehicle::Status::arriving)) + { + CoordsXYZ steamOffset = ComputeSteamOffset( + carEntry.SteamEffect.Vertical, carEntry.SteamEffect.Longitudinal, vehicle.pitch, + vehicle.orientation); + SteamParticle::Create(CoordsXYZ(vehicle.x, vehicle.y, vehicle.z) + steamOffset); + } } } + vehicle.invalidate(); } - vehicle.invalidate(); } -} -/** - * Animate the vehicle based on its speed. Specialized animation with exactly 2 frames due to how peep animation works. - */ -static void AnimateSwanBoat(Vehicle& vehicle, const CarEntry& carEntry) -{ - // The animation of swan boats places frames at 0 and 2 instead of 0 and 1 like Water Tricycles due to the second - // pair of peeps. The animation technically uses 4 frames, but ignores frames 1 and 3. - vehicle.animationState += _vehicleVelocityF64E08; - uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState) * 2; - if (vehicle.animation_frame != targetFrame) + /** + * Animate the vehicle based on its speed. Specialized animation with exactly 2 frames due to how peep animation works. + */ + static void AnimateSwanBoat(Vehicle& vehicle, const CarEntry& carEntry) { - vehicle.animation_frame = targetFrame; - vehicle.invalidate(); + // The animation of swan boats places frames at 0 and 2 instead of 0 and 1 like Water Tricycles due to the second + // pair of peeps. The animation technically uses 4 frames, but ignores frames 1 and 3. + vehicle.animationState += _vehicleVelocityF64E08; + uint8_t targetFrame = GetTargetFrame(carEntry, vehicle.animationState) * 2; + if (vehicle.animation_frame != targetFrame) + { + vehicle.animation_frame = targetFrame; + vehicle.invalidate(); + } } -} -/** - * Monorail Cycle animation only animates when a peep is present - */ -static void AnimateMonorailCycle(Vehicle& vehicle, const CarEntry& carEntry) -{ - if (vehicle.num_peeps != 0) + /** + * Monorail Cycle animation only animates when a peep is present + */ + static void AnimateMonorailCycle(Vehicle& vehicle, const CarEntry& carEntry) { - AnimateSimpleVehicle(vehicle, carEntry); + if (vehicle.num_peeps != 0) + { + AnimateSimpleVehicle(vehicle, carEntry); + } } -} -/** - * Observation tower animates at a constant speed continuously - */ -static void AnimateObservationTower(Vehicle& vehicle, const CarEntry& carEntry) -{ - if (vehicle.animationState <= 0xCCCC) - { - vehicle.animationState += carEntry.AnimationSpeed; - } - else - { - vehicle.animationState = 0; - vehicle.animation_frame += 1; - vehicle.animation_frame %= carEntry.AnimationFrames; - vehicle.invalidate(); - } -} -/** - * seatRotation value of 4 translates to animationFrame value of 0. This function makes that true for any number of animation - * frames - */ -static int16_t MultiDimensionTargetAngle(int16_t seatRotation, int16_t animationFrames) -{ - return ((seatRotation - 4) % animationFrames + animationFrames) % animationFrames; -} - -/** - * Multidimension targets a specific animation frame based on track - */ -static void AnimateMultiDimension(Vehicle& vehicle, const CarEntry& carEntry) -{ - if (vehicle.seat_rotation != vehicle.target_seat_rotation) + /** + * Observation tower animates at a constant speed continuously + */ + static void AnimateObservationTower(Vehicle& vehicle, const CarEntry& carEntry) { if (vehicle.animationState <= 0xCCCC) { @@ -1052,53 +1027,82 @@ static void AnimateMultiDimension(Vehicle& vehicle, const CarEntry& carEntry) else { vehicle.animationState = 0; + vehicle.animation_frame += 1; + vehicle.animation_frame %= carEntry.AnimationFrames; + vehicle.invalidate(); + } + } + /** + * seatRotation value of 4 translates to animationFrame value of 0. This function makes that true for any number of + * animation frames + */ + static int16_t MultiDimensionTargetAngle(int16_t seatRotation, int16_t animationFrames) + { + return ((seatRotation - 4) % animationFrames + animationFrames) % animationFrames; + } - if (vehicle.seat_rotation >= vehicle.target_seat_rotation) - vehicle.seat_rotation--; - else - vehicle.seat_rotation++; - - int16_t targetSeatRotation = MultiDimensionTargetAngle(vehicle.seat_rotation, carEntry.AnimationFrames); - if (targetSeatRotation != vehicle.animation_frame) + /** + * Multidimension targets a specific animation frame based on track + */ + static void AnimateMultiDimension(Vehicle& vehicle, const CarEntry& carEntry) + { + if (vehicle.seat_rotation != vehicle.target_seat_rotation) + { + if (vehicle.animationState <= 0xCCCC) { - vehicle.animation_frame = targetSeatRotation; - vehicle.invalidate(); + vehicle.animationState += carEntry.AnimationSpeed; + } + else + { + vehicle.animationState = 0; + + if (vehicle.seat_rotation >= vehicle.target_seat_rotation) + vehicle.seat_rotation--; + else + vehicle.seat_rotation++; + + int16_t targetSeatRotation = MultiDimensionTargetAngle(vehicle.seat_rotation, carEntry.AnimationFrames); + if (targetSeatRotation != vehicle.animation_frame) + { + vehicle.animation_frame = targetSeatRotation; + vehicle.invalidate(); + } } } } -} -/** - * Animal Flying animates only on chainlift and in an unusual way. Made by Spacek531 - */ -static void AnimateAnimalFlying(Vehicle& vehicle, const CarEntry& carEntry) -{ - vehicle.UpdateAnimationAnimalFlying(); - // makes animation play faster with vehicle speed - uint8_t targetFrame = abs(_vehicleVelocityF64E08) >> carEntry.AnimationSpeed; - vehicle.animationState = std::max(vehicle.animationState - targetFrame, 0u); -} - -using AnimateFunction = void (*)(Vehicle& vehicle, const CarEntry& carEntry); - -constexpr static const AnimateFunction AnimationFunctions[]{ - AnimateNone, AnimateSimpleVehicle, AnimateSteamLocomotive, AnimateSwanBoat, - AnimateMonorailCycle, AnimateMultiDimension, AnimateObservationTower, AnimateAnimalFlying, -}; -static_assert(std::size(AnimationFunctions) == EnumValue(CarEntryAnimation::count)); - -/** - * - * rct2: 0x006D63D4 - */ -void Vehicle::UpdateAdditionalAnimation() -{ - auto carEntry = Entry(); - if (carEntry == nullptr) + /** + * Animal Flying animates only on chainlift and in an unusual way. Made by Spacek531 + */ + static void AnimateAnimalFlying(Vehicle& vehicle, const CarEntry& carEntry) { - return; + vehicle.UpdateAnimationAnimalFlying(); + // makes animation play faster with vehicle speed + uint8_t targetFrame = abs(_vehicleVelocityF64E08) >> carEntry.AnimationSpeed; + vehicle.animationState = std::max(vehicle.animationState - targetFrame, 0u); } - if (carEntry->AnimationFrames == 0 || carEntry->animation >= CarEntryAnimation::count) - return; - AnimationFunctions[EnumValue(carEntry->animation)](*this, *carEntry); -} + + using AnimateFunction = void (*)(Vehicle& vehicle, const CarEntry& carEntry); + + constexpr static const AnimateFunction AnimationFunctions[]{ + AnimateNone, AnimateSimpleVehicle, AnimateSteamLocomotive, AnimateSwanBoat, + AnimateMonorailCycle, AnimateMultiDimension, AnimateObservationTower, AnimateAnimalFlying, + }; + static_assert(std::size(AnimationFunctions) == EnumValue(CarEntryAnimation::count)); + + /** + * + * rct2: 0x006D63D4 + */ + void Vehicle::UpdateAdditionalAnimation() + { + auto carEntry = Entry(); + if (carEntry == nullptr) + { + return; + } + if (carEntry->AnimationFrames == 0 || carEntry->animation >= CarEntryAnimation::count) + return; + AnimationFunctions[EnumValue(carEntry->animation)](*this, *carEntry); + } +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Vehicle.MiniGolf.cpp b/src/openrct2/ride/Vehicle.MiniGolf.cpp index 927db89243..a56af6c685 100644 --- a/src/openrct2/ride/Vehicle.MiniGolf.cpp +++ b/src/openrct2/ride/Vehicle.MiniGolf.cpp @@ -31,7 +31,7 @@ using namespace OpenRCT2; using namespace OpenRCT2::RideVehicle; using namespace OpenRCT2::TrackMetadata; -void RideUpdateMeasurementsSpecialElements_MiniGolf(Ride& ride, const TrackElemType trackType) +void OpenRCT2::RideUpdateMeasurementsSpecialElements_MiniGolf(Ride& ride, const TrackElemType trackType) { const auto& ted = GetTrackElementDescriptor(trackType); if (ted.flags.has(TrackElementFlag::isGolfHole)) diff --git a/src/openrct2/ride/Vehicle.Sound.cpp b/src/openrct2/ride/Vehicle.Sound.cpp index b65bd7aed7..05607488b2 100644 --- a/src/openrct2/ride/Vehicle.Sound.cpp +++ b/src/openrct2/ride/Vehicle.Sound.cpp @@ -20,285 +20,287 @@ #include "RideData.h" #include "VehicleGeometry.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Audio; -using namespace OpenRCT2::RideVehicle; - -static constexpr SoundId _screamSetMisc[] = { - SoundId::scream8, - SoundId::scream1, -}; -static constexpr SoundId _screamSetWooden[] = { - SoundId::scream3, SoundId::scream1, SoundId::scream5, SoundId::scream6, - SoundId::scream7, SoundId::scream2, SoundId::scream4, -}; -static constexpr SoundId _screamSetSteel[] = { - SoundId::scream1, - SoundId::scream6, -}; - -void VehicleSoundsUpdate() +namespace OpenRCT2 { - auto windowManager = Ui::GetWindowManager(); - windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_VEHICLE_SOUNDS)); -} + using namespace OpenRCT2::Audio; + using namespace OpenRCT2::RideVehicle; -/** - * - * rct2: 0x006D7AC0 - */ -static SoundIdVolume VehicleSoundFadeInOut( - SoundId currentSoundId, uint8_t currentVolume, SoundId targetSoundId, uint8_t targetVolume) -{ - if (currentSoundId != SoundId::null) + static constexpr SoundId _screamSetMisc[] = { + SoundId::scream8, + SoundId::scream1, + }; + static constexpr SoundId _screamSetWooden[] = { + SoundId::scream3, SoundId::scream1, SoundId::scream5, SoundId::scream6, + SoundId::scream7, SoundId::scream2, SoundId::scream4, + }; + static constexpr SoundId _screamSetSteel[] = { + SoundId::scream1, + SoundId::scream6, + }; + + void VehicleSoundsUpdate() { - if (currentSoundId == targetSoundId) + auto windowManager = Ui::GetWindowManager(); + windowManager->BroadcastIntent(Intent(INTENT_ACTION_UPDATE_VEHICLE_SOUNDS)); + } + + /** + * + * rct2: 0x006D7AC0 + */ + static SoundIdVolume VehicleSoundFadeInOut( + SoundId currentSoundId, uint8_t currentVolume, SoundId targetSoundId, uint8_t targetVolume) + { + if (currentSoundId != SoundId::null) { - currentVolume = std::min(currentVolume + 15, targetVolume); - return { currentSoundId, currentVolume }; + if (currentSoundId == targetSoundId) + { + currentVolume = std::min(currentVolume + 15, targetVolume); + return { currentSoundId, currentVolume }; + } + + currentVolume -= 9; + if (currentVolume >= 80) + return { currentSoundId, currentVolume }; } - currentVolume -= 9; - if (currentVolume >= 80) - return { currentSoundId, currentVolume }; + // Begin sound at quarter volume + currentSoundId = targetSoundId; + currentVolume = targetVolume == 255 ? 255 : targetVolume / 4; + + return { currentSoundId, currentVolume }; } - // Begin sound at quarter volume - currentSoundId = targetSoundId; - currentVolume = targetVolume == 255 ? 255 : targetVolume / 4; - - return { currentSoundId, currentVolume }; -} - -void Vehicle::GetLiftHillSound(const Ride& curRide, SoundIdVolume& curSound) -{ - scream_sound_id = SoundId::null; - if (curRide.type < std::size(kRideTypeDescriptors)) + void Vehicle::GetLiftHillSound(const Ride& curRide, SoundIdVolume& curSound) { - // Get lift hill sound - curSound.id = GetRideTypeDescriptor(curRide.type).LiftData.sound_id; - curSound.volume = 243; - if (!(sound2_flags & VEHICLE_SOUND2_FLAGS_LIFT_HILL)) - curSound.id = SoundId::null; - } -} - -/** - * - * rct2: 0x006D7888 - */ -void Vehicle::UpdateSound() -{ - // frictionVolume (bl) should be set before hand - SoundIdVolume frictionSound = { SoundId::null, 255 }; - // bh screamVolume should be set before hand - SoundIdVolume screamSound = { SoundId::null, 255 }; - - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - auto rideEntry = GetRideEntry(); - if (rideEntry == nullptr) - return; - - // Always use the head car's sound data (Some of the other vehicle subtypes have improperly set data) - auto soundCarIndex = (rideEntry->FrontCar == 0xff) ? rideEntry->DefaultCar : rideEntry->FrontCar; - const auto& carEntry = rideEntry->Cars[soundCarIndex]; - - int32_t ecx = abs(velocity) - 1.0_mph; - if (ecx >= 0) - { - frictionSound.id = carEntry.friction_sound_id; - ecx >>= 15; - frictionSound.volume = std::min(208 + (ecx & 0xFF), 255); + scream_sound_id = SoundId::null; + if (curRide.type < std::size(kRideTypeDescriptors)) + { + // Get lift hill sound + curSound.id = GetRideTypeDescriptor(curRide.type).LiftData.sound_id; + curSound.volume = 243; + if (!(sound2_flags & VEHICLE_SOUND2_FLAGS_LIFT_HILL)) + curSound.id = SoundId::null; + } } - const auto currentTicks = getGameState().currentTicks; - switch (carEntry.soundRange) + /** + * + * rct2: 0x006D7888 + */ + void Vehicle::UpdateSound() { - case SoundRange::steamWhistle: - screamSound.id = scream_sound_id; - if (!(currentTicks & 0x7F)) - { - if (velocity < 4.0_mph || scream_sound_id != SoundId::null) - { - GetLiftHillSound(*curRide, screamSound); - break; - } + // frictionVolume (bl) should be set before hand + SoundIdVolume frictionSound = { SoundId::null, 255 }; + // bh screamVolume should be set before hand + SoundIdVolume screamSound = { SoundId::null, 255 }; - if ((ScenarioRand() & 0xFFFF) <= 0x5555) - { - scream_sound_id = SoundId::trainWhistle; - screamSound.volume = 255; - break; - } - } - if (screamSound.id == SoundId::noScream) - screamSound.id = SoundId::null; - screamSound.volume = 255; - break; + auto curRide = GetRide(); + if (curRide == nullptr) + return; - case SoundRange::tramBell: - screamSound.id = scream_sound_id; - if (!(currentTicks & 0x7F)) - { - if (velocity < 4.0_mph || scream_sound_id != SoundId::null) - { - GetLiftHillSound(*curRide, screamSound); - break; - } + auto rideEntry = GetRideEntry(); + if (rideEntry == nullptr) + return; - if ((ScenarioRand() & 0xFFFF) <= 0x5555) - { - scream_sound_id = SoundId::tram; - screamSound.volume = 255; - break; - } - } - if (screamSound.id == SoundId::noScream) - screamSound.id = SoundId::null; - screamSound.volume = 255; - break; + // Always use the head car's sound data (Some of the other vehicle subtypes have improperly set data) + auto soundCarIndex = (rideEntry->FrontCar == 0xff) ? rideEntry->DefaultCar : rideEntry->FrontCar; + const auto& carEntry = rideEntry->Cars[soundCarIndex]; - default: - if (carEntry.flags.has(CarEntryFlag::hasScreamingRiders)) - { - screamSound.id = UpdateScreamSound(); + int32_t ecx = abs(velocity) - 1.0_mph; + if (ecx >= 0) + { + frictionSound.id = carEntry.friction_sound_id; + ecx >>= 15; + frictionSound.volume = std::min(208 + (ecx & 0xFF), 255); + } + + const auto currentTicks = getGameState().currentTicks; + switch (carEntry.soundRange) + { + case SoundRange::steamWhistle: + screamSound.id = scream_sound_id; + if (!(currentTicks & 0x7F)) + { + if (velocity < 4.0_mph || scream_sound_id != SoundId::null) + { + GetLiftHillSound(*curRide, screamSound); + break; + } + + if ((ScenarioRand() & 0xFFFF) <= 0x5555) + { + scream_sound_id = SoundId::trainWhistle; + screamSound.volume = 255; + break; + } + } if (screamSound.id == SoundId::noScream) - { screamSound.id = SoundId::null; - break; - } - if (screamSound.id != SoundId::null) + screamSound.volume = 255; + break; + + case SoundRange::tramBell: + screamSound.id = scream_sound_id; + if (!(currentTicks & 0x7F)) { - break; + if (velocity < 4.0_mph || scream_sound_id != SoundId::null) + { + GetLiftHillSound(*curRide, screamSound); + break; + } + + if ((ScenarioRand() & 0xFFFF) <= 0x5555) + { + scream_sound_id = SoundId::tram; + screamSound.volume = 255; + break; + } } - } - GetLiftHillSound(*curRide, screamSound); + if (screamSound.id == SoundId::noScream) + screamSound.id = SoundId::null; + screamSound.volume = 255; + break; + + default: + if (carEntry.flags.has(CarEntryFlag::hasScreamingRiders)) + { + screamSound.id = UpdateScreamSound(); + if (screamSound.id == SoundId::noScream) + { + screamSound.id = SoundId::null; + break; + } + if (screamSound.id != SoundId::null) + { + break; + } + } + GetLiftHillSound(*curRide, screamSound); + } + + // Friction sound + auto soundIdVolume = VehicleSoundFadeInOut(sound1_id, sound1_volume, frictionSound.id, frictionSound.volume); + sound1_id = soundIdVolume.id; + sound1_volume = soundIdVolume.volume; + + // Scream sound + soundIdVolume = VehicleSoundFadeInOut(sound2_id, sound2_volume, screamSound.id, screamSound.volume); + sound2_id = soundIdVolume.id; + sound2_volume = soundIdVolume.volume; + + // Calculate Sound Vector (used for sound frequency calcs) + int32_t soundDirection = Geometry::getSoundDirectionFromOrientation(orientation); + int32_t soundVector = ((velocity >> 14) * soundDirection) >> 14; + soundVector = std::clamp(soundVector, -127, 127); + + dopplerShift = soundVector & 0xFF; } - // Friction sound - auto soundIdVolume = VehicleSoundFadeInOut(sound1_id, sound1_volume, frictionSound.id, frictionSound.volume); - sound1_id = soundIdVolume.id; - sound1_volume = soundIdVolume.volume; - - // Scream sound - soundIdVolume = VehicleSoundFadeInOut(sound2_id, sound2_volume, screamSound.id, screamSound.volume); - sound2_id = soundIdVolume.id; - sound2_volume = soundIdVolume.volume; - - // Calculate Sound Vector (used for sound frequency calcs) - int32_t soundDirection = Geometry::getSoundDirectionFromOrientation(orientation); - int32_t soundVector = ((velocity >> 14) * soundDirection) >> 14; - soundVector = std::clamp(soundVector, -127, 127); - - dopplerShift = soundVector & 0xFF; -} - -/** - * - * rct2: 0x006D796B - */ -SoundId Vehicle::UpdateScreamSound() -{ - int32_t totalNumPeeps = NumPeepsUntilTrainTail(); - if (totalNumPeeps == 0) - return SoundId::null; - - if (velocity < 0) + /** + * + * rct2: 0x006D796B + */ + SoundId Vehicle::UpdateScreamSound() { - if (velocity > -2.75_mph) + int32_t totalNumPeeps = NumPeepsUntilTrainTail(); + if (totalNumPeeps == 0) + return SoundId::null; + + if (velocity < 0) + { + if (velocity > -2.75_mph) + return SoundId::null; + + for (Vehicle* vehicle2 = getGameState().entities.GetEntity(id); vehicle2 != nullptr; + vehicle2 = getGameState().entities.GetEntity(vehicle2->next_vehicle_on_train)) + { + if (vehicle2->pitch < VehiclePitch::up12) + continue; + if (vehicle2->pitch <= VehiclePitch::up60) + return ProduceScreamSound(totalNumPeeps); + if (vehicle2->pitch < VehiclePitch::up75) + continue; + if (vehicle2->pitch <= VehiclePitch::up165) + return ProduceScreamSound(totalNumPeeps); + // up50 occurs on diagonal steep hills + // up8 and up16 occur on diagonal gentle hills + if (vehicle2->pitch == VehiclePitch::up50) + return ProduceScreamSound(totalNumPeeps); + } + return SoundId::null; + } + + if (velocity < 2.75_mph) return SoundId::null; for (Vehicle* vehicle2 = getGameState().entities.GetEntity(id); vehicle2 != nullptr; vehicle2 = getGameState().entities.GetEntity(vehicle2->next_vehicle_on_train)) { - if (vehicle2->pitch < VehiclePitch::up12) + if (vehicle2->pitch < VehiclePitch::down12) continue; - if (vehicle2->pitch <= VehiclePitch::up60) + if (vehicle2->pitch <= VehiclePitch::down60) return ProduceScreamSound(totalNumPeeps); - if (vehicle2->pitch < VehiclePitch::up75) + if (vehicle2->pitch <= VehiclePitch::inverted) continue; - if (vehicle2->pitch <= VehiclePitch::up165) + if (vehicle2->pitch <= VehiclePitch::down165) return ProduceScreamSound(totalNumPeeps); - // up50 occurs on diagonal steep hills - // up8 and up16 occur on diagonal gentle hills - if (vehicle2->pitch == VehiclePitch::up50) + // down50 occurs on diagonal steep drops + // down8 and down16 occur on diagonal gentle drops + if (vehicle2->pitch == VehiclePitch::down50) return ProduceScreamSound(totalNumPeeps); } return SoundId::null; } - if (velocity < 2.75_mph) - return SoundId::null; - - for (Vehicle* vehicle2 = getGameState().entities.GetEntity(id); vehicle2 != nullptr; - vehicle2 = getGameState().entities.GetEntity(vehicle2->next_vehicle_on_train)) + SoundId Vehicle::ProduceScreamSound(const int32_t totalNumPeeps) { - if (vehicle2->pitch < VehiclePitch::down12) - continue; - if (vehicle2->pitch <= VehiclePitch::down60) - return ProduceScreamSound(totalNumPeeps); - if (vehicle2->pitch <= VehiclePitch::inverted) - continue; - if (vehicle2->pitch <= VehiclePitch::down165) - return ProduceScreamSound(totalNumPeeps); - // down50 occurs on diagonal steep drops - // down8 and down16 occur on diagonal gentle drops - if (vehicle2->pitch == VehiclePitch::down50) - return ProduceScreamSound(totalNumPeeps); - } - return SoundId::null; -} + const auto* rideEntry = GetRideEntry(); -SoundId Vehicle::ProduceScreamSound(const int32_t totalNumPeeps) -{ - const auto* rideEntry = GetRideEntry(); + const auto& carEntry = rideEntry->Cars[vehicle_type]; - const auto& carEntry = rideEntry->Cars[vehicle_type]; - - if (scream_sound_id == SoundId::null) - { - auto r = ScenarioRand(); - if (totalNumPeeps >= static_cast(r % 16)) + if (scream_sound_id == SoundId::null) { - switch (carEntry.soundRange) + auto r = ScenarioRand(); + if (totalNumPeeps >= static_cast(r % 16)) { - case SoundRange::screamsMisc: - scream_sound_id = _screamSetMisc[r % std::size(_screamSetMisc)]; - break; - case SoundRange::screamsWoodenRollerCoaster: - scream_sound_id = _screamSetWooden[r % std::size(_screamSetWooden)]; - break; - case SoundRange::screamSteelRollerCoaster: - scream_sound_id = _screamSetSteel[r % std::size(_screamSetSteel)]; - break; - default: - scream_sound_id = SoundId::noScream; - break; + switch (carEntry.soundRange) + { + case SoundRange::screamsMisc: + scream_sound_id = _screamSetMisc[r % std::size(_screamSetMisc)]; + break; + case SoundRange::screamsWoodenRollerCoaster: + scream_sound_id = _screamSetWooden[r % std::size(_screamSetWooden)]; + break; + case SoundRange::screamSteelRollerCoaster: + scream_sound_id = _screamSetSteel[r % std::size(_screamSetSteel)]; + break; + default: + scream_sound_id = SoundId::noScream; + break; + } + } + else + { + scream_sound_id = SoundId::noScream; } } - else + return scream_sound_id; + } + + void Vehicle::Claxon() const + { + const auto* rideEntry = GetRideEntry(); + switch (rideEntry->Cars[vehicle_type].soundRange) { - scream_sound_id = SoundId::noScream; + case SoundRange::steamWhistle: + Play3D(SoundId::trainWhistle, { x, y, z }); + break; + case SoundRange::tramBell: + Play3D(SoundId::tram, { x, y, z }); + break; + default: + break; } } - return scream_sound_id; -} - -void Vehicle::Claxon() const -{ - const auto* rideEntry = GetRideEntry(); - switch (rideEntry->Cars[vehicle_type].soundRange) - { - case SoundRange::steamWhistle: - Play3D(SoundId::trainWhistle, { x, y, z }); - break; - case SoundRange::tramBell: - Play3D(SoundId::tram, { x, y, z }); - break; - default: - break; - } -} +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Vehicle.TrackMotion.cpp b/src/openrct2/ride/Vehicle.TrackMotion.cpp index 72f2d78ef7..8431bfa3bc 100644 --- a/src/openrct2/ride/Vehicle.TrackMotion.cpp +++ b/src/openrct2/ride/Vehicle.TrackMotion.cpp @@ -28,1578 +28,1583 @@ #include "VehicleGeometry.h" #include "ted/TrackElementDescriptor.h" -using namespace OpenRCT2; -using namespace OpenRCT2::Audio; -using namespace OpenRCT2::TrackMetadata; -using namespace OpenRCT2::RideVehicle; - -// External globals from Vehicle.cpp -extern Vehicle* gCurrentVehicle; -extern Breakdown _vehicleBreakdown; -extern StationIndex _vehicleStationIndex; -extern uint32_t _vehicleMotionTrackFlags; -extern int32_t _vehicleVelocityF64E08; -extern int32_t _vehicleVelocityF64E0C; -extern int32_t _vehicleUnkF64E10; -extern uint8_t _vehicleF64E2C; -extern Vehicle* _vehicleFrontVehicle; -extern CoordsXYZ _vehicleCurPosition; - -// Constants -constexpr uint8_t kTrackSpeedShiftAmount = 16; -constexpr uint8_t kBoosterAccelerationShiftAmount = 16; -constexpr int16_t kVehicleMaxSpinSpeedWaterRide = 512; -constexpr int16_t kVehicleMinSpinSpeedWaterRide = -kVehicleMaxSpinSpeedWaterRide; - -/** - * - * rct2: 0x006DAB90 - */ -void Vehicle::UpdateTrackMotionUpStopCheck() const +namespace OpenRCT2 { - const auto* carEntry = Entry(); - if (carEntry == nullptr) - { - return; - } + using namespace OpenRCT2::Audio; + using namespace OpenRCT2::TrackMetadata; + using namespace OpenRCT2::RideVehicle; - // No up stops (coaster types) - if (carEntry->flags.has(CarEntryFlag::hasNoUpstopWheels)) + // External globals from Vehicle.cpp + extern Vehicle* gCurrentVehicle; + extern Breakdown _vehicleBreakdown; + extern StationIndex _vehicleStationIndex; + extern uint32_t _vehicleMotionTrackFlags; + extern int32_t _vehicleVelocityF64E08; + extern int32_t _vehicleVelocityF64E0C; + extern int32_t _vehicleUnkF64E10; + extern uint8_t _vehicleF64E2C; + extern Vehicle* _vehicleFrontVehicle; + extern CoordsXYZ _vehicleCurPosition; + + // Constants + constexpr uint8_t kTrackSpeedShiftAmount = 16; + constexpr uint8_t kBoosterAccelerationShiftAmount = 16; + constexpr int16_t kVehicleMaxSpinSpeedWaterRide = 512; + constexpr int16_t kVehicleMinSpinSpeedWaterRide = -kVehicleMaxSpinSpeedWaterRide; + + /** + * + * rct2: 0x006DAB90 + */ + void Vehicle::UpdateTrackMotionUpStopCheck() const { - if (!IsOnCoveredTrack()) + const auto* carEntry = Entry(); + if (carEntry == nullptr) { - auto gForces = GetGForces(); - gForces.lateralG = std::abs(gForces.lateralG); - if (gForces.lateralG <= 150) + return; + } + + // No up stops (coaster types) + if (carEntry->flags.has(CarEntryFlag::hasNoUpstopWheels)) + { + if (!IsOnCoveredTrack()) { - if (Geometry::getAccelerationFromPitch(pitch) < 0) + auto gForces = GetGForces(); + gForces.lateralG = std::abs(gForces.lateralG); + if (gForces.lateralG <= 150) { - if (gForces.verticalG > -40) + if (Geometry::getAccelerationFromPitch(pitch) < 0) + { + if (gForces.verticalG > -40) + { + return; + } + } + else if (gForces.verticalG > -80) { return; } } - else if (gForces.verticalG > -80) + + if (pitch != VehiclePitch::down60) { - return; + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED; } } - - if (pitch != VehiclePitch::down60) + } + else if (carEntry->flags.has(CarEntryFlag::hasNoUpstopWheelsBobsleigh)) + { + // No up stops bobsleigh type + if (!IsOnCoveredTrack()) { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED; + auto gForces = GetGForces(); + + if (Geometry::getAccelerationFromPitch(pitch) < 0) + { + if (gForces.verticalG > -45) + { + return; + } + } + else + { + if (gForces.verticalG > -80) + { + return; + } + } + + if (pitch != VehiclePitch::down60 && pitch != VehiclePitch::down50) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED; + } } } } - else if (carEntry->flags.has(CarEntryFlag::hasNoUpstopWheelsBobsleigh)) + + /** + * Modifies the train's velocity to match the block-brake fixed velocity. + * This function must be called when the car is running through a non-stopping + * state block-brake (precondition), which means that the block brake is acting + * merely as a velocity regulator, in a closed state. When the brake is open, it + * boosts the train to the speed limit + */ + void Vehicle::ApplyNonStopBlockBrake() { - // No up stops bobsleigh type - if (!IsOnCoveredTrack()) + if (velocity >= 0) { - auto gForces = GetGForces(); - - if (Geometry::getAccelerationFromPitch(pitch) < 0) + // If the vehicle is below the speed limit + if (velocity <= kBlockBrakeBaseSpeed) { - if (gForces.verticalG > -45) - { - return; - } + // Boost it to the fixed block brake speed + velocity = kBlockBrakeBaseSpeed; + acceleration = 0; } - else + else if (velocity > (brake_speed << kTrackSpeedShiftAmount) + kBlockBrakeSpeedOffset) { - if (gForces.verticalG > -80) - { - return; - } - } - - if (pitch != VehiclePitch::down60 && pitch != VehiclePitch::down50) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED; + velocity -= velocity >> 4; + acceleration = 0; } } } -} -/** - * Modifies the train's velocity to match the block-brake fixed velocity. - * This function must be called when the car is running through a non-stopping - * state block-brake (precondition), which means that the block brake is acting - * merely as a velocity regulator, in a closed state. When the brake is open, it - * boosts the train to the speed limit - */ -void Vehicle::ApplyNonStopBlockBrake() -{ - if (velocity >= 0) + /** + * + * Modifies the train's velocity influenced by a block brake + */ + void Vehicle::ApplyStopBlockBrake() { - // If the vehicle is below the speed limit - if (velocity <= kBlockBrakeBaseSpeed) + // Slow it down till completely stop the car + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; + acceleration = 0; + // If the this is slow enough, stop it. If not, slow it down + if (velocity <= 2.0_mph) + { + velocity = 0; + } + else + { + velocity -= velocity >> 3; + } + } + + void Vehicle::ApplyCableLiftBlockBrake(bool brakeClosed) + { + // If we are already on the cable lift, ignore the brake + if (status == Status::travellingCableLift) + return; + + // Slow down if travelling faster than 4mph + if (velocity > kBlockBrakeBaseSpeed) + { + velocity -= velocity >> 3; + acceleration = 0; + } + // Once moving slow enough, keep moving forward until lined up with the catch car + else if (track_progress <= 18) { - // Boost it to the fixed block brake speed velocity = kBlockBrakeBaseSpeed; acceleration = 0; } - else if (velocity > (brake_speed << kTrackSpeedShiftAmount) + kBlockBrakeSpeedOffset) + // Once in position, stop, and wait for the catch car + if (velocity > 0 && track_progress >= 18) { - velocity -= velocity >> 4; + velocity = 0; acceleration = 0; + if (!brakeClosed) + SetState(Status::waitingForCableLift, sub_state); + else + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; } } -} -/** - * - * Modifies the train's velocity influenced by a block brake - */ -void Vehicle::ApplyStopBlockBrake() -{ - // Slow it down till completely stop the car - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; - acceleration = 0; - // If the this is slow enough, stop it. If not, slow it down - if (velocity <= 2.0_mph) + /** + * + * rct2: 0x006DAC43 + */ + void Vehicle::CheckAndApplyBlockSectionStopSite() { - velocity = 0; - } - else - { - velocity -= velocity >> 3; - } -} + auto curRide = GetRide(); + if (curRide == nullptr) + return; -void Vehicle::ApplyCableLiftBlockBrake(bool brakeClosed) -{ - // If we are already on the cable lift, ignore the brake - if (status == Status::travellingCableLift) - return; + auto carEntry = Entry(); + if (carEntry == nullptr) + return; - // Slow down if travelling faster than 4mph - if (velocity > kBlockBrakeBaseSpeed) - { - velocity -= velocity >> 3; - acceleration = 0; - } - // Once moving slow enough, keep moving forward until lined up with the catch car - else if (track_progress <= 18) - { - velocity = kBlockBrakeBaseSpeed; - acceleration = 0; - } - // Once in position, stop, and wait for the catch car - if (velocity > 0 && track_progress >= 18) - { - velocity = 0; - acceleration = 0; - if (!brakeClosed) - SetState(Status::waitingForCableLift, sub_state); - else - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; - } -} + // Is chair lift type + if (carEntry->flags.has(CarEntryFlag::isChairlift)) + { + velocity = _vehicleBreakdown == Breakdown::safetyCutOut ? 0 : curRide->speed << 16; + acceleration = 0; + } -/** - * - * rct2: 0x006DAC43 - */ -void Vehicle::CheckAndApplyBlockSectionStopSite() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; + auto trackType = GetTrackType(); - auto carEntry = Entry(); - if (carEntry == nullptr) - return; + TileElement* trackElement = MapGetTrackElementAtOfType(TrackLocation, trackType); - // Is chair lift type - if (carEntry->flags.has(CarEntryFlag::isChairlift)) - { - velocity = _vehicleBreakdown == Breakdown::safetyCutOut ? 0 : curRide->speed << 16; - acceleration = 0; - } + if (trackElement == nullptr) + { + return; + } - auto trackType = GetTrackType(); - - TileElement* trackElement = MapGetTrackElementAtOfType(TrackLocation, trackType); - - if (trackElement == nullptr) - { - return; - } - - switch (trackType) - { - case TrackElemType::blockBrakes: - // Check if this brake is the start of a cable lift - if (curRide->flags.has(RideFlag::cableLift)) - { - CoordsXYE track; - int32_t zUnused; - int32_t direction; - if (trackBlockGetNextFromZero(TrackLocation, *curRide, GetTrackDirection(), &track, &zUnused, &direction, false) - && track.element != nullptr && track.element->asTrack()->HasCableLift()) + switch (trackType) + { + case TrackElemType::blockBrakes: + // Check if this brake is the start of a cable lift + if (curRide->flags.has(RideFlag::cableLift)) { - ApplyCableLiftBlockBrake(curRide->isBlockSectioned() && trackElement->asTrack()->IsBrakeClosed()); - break; - } - } - [[fallthrough]]; - case TrackElemType::diagBlockBrakes: - if (curRide->isBlockSectioned() && trackElement->asTrack()->IsBrakeClosed()) - ApplyStopBlockBrake(); - else - ApplyNonStopBlockBrake(); - - break; - case TrackElemType::endStation: - if (trackElement->asTrack()->IsBrakeClosed()) - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; - - break; - case TrackElemType::up25ToFlat: - case TrackElemType::up60ToFlat: - case TrackElemType::cableLiftHill: - case TrackElemType::diagUp25ToFlat: - case TrackElemType::diagUp60ToFlat: - if (curRide->isBlockSectioned()) - { - if (trackType == TrackElemType::cableLiftHill || trackElement->asTrack()->HasChain()) - { - if (trackElement->asTrack()->IsBrakeClosed()) + CoordsXYE track; + int32_t zUnused; + int32_t direction; + if (trackBlockGetNextFromZero( + TrackLocation, *curRide, GetTrackDirection(), &track, &zUnused, &direction, false) + && track.element != nullptr && track.element->asTrack()->HasCableLift()) { - ApplyStopBlockBrake(); + ApplyCableLiftBlockBrake(curRide->isBlockSectioned() && trackElement->asTrack()->IsBrakeClosed()); + break; } } - } - break; - default: - break; - } -} + [[fallthrough]]; + case TrackElemType::diagBlockBrakes: + if (curRide->isBlockSectioned() && trackElement->asTrack()->IsBrakeClosed()) + ApplyStopBlockBrake(); + else + ApplyNonStopBlockBrake(); -/** - * - * rct2: 0x006DADAE - */ -void Vehicle::UpdateVelocity() -{ - int32_t nextVelocity = acceleration + velocity; - if (flags.has(VehicleFlag::stoppedBySafetyCutout)) - { - nextVelocity = 0; - } - if (flags.has(VehicleFlag::stoppedOnHoldingBrake)) - { - if (vertical_drop_countdown > 0) - { - nextVelocity = 0; - acceleration = 0; - vertical_drop_countdown--; + break; + case TrackElemType::endStation: + if (trackElement->asTrack()->IsBrakeClosed()) + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE; + + break; + case TrackElemType::up25ToFlat: + case TrackElemType::up60ToFlat: + case TrackElemType::cableLiftHill: + case TrackElemType::diagUp25ToFlat: + case TrackElemType::diagUp60ToFlat: + if (curRide->isBlockSectioned()) + { + if (trackType == TrackElemType::cableLiftHill || trackElement->asTrack()->HasChain()) + { + if (trackElement->asTrack()->IsBrakeClosed()) + { + ApplyStopBlockBrake(); + } + } + } + break; + default: + break; } } - velocity = nextVelocity; - _vehicleVelocityF64E08 = nextVelocity; - _vehicleVelocityF64E0C = (nextVelocity >> 10) * 42; -} - -static void BlockBrakesOpenPreviousSection(const Ride& ride, const CoordsXYZ& vehicleTrackLocation, TileElement* tileElement) -{ - CoordsXYZ location = vehicleTrackLocation; - TrackElement* trackElement = trackGetPreviousBlock(location, tileElement); - if (trackElement == nullptr) - return; - - SetBrakeClosedMultiTile(*trackElement, location, false); - MapInvalidateElement(location, reinterpret_cast(trackElement)); - - auto trackType = trackElement->GetTrackType(); - if (trackType == TrackElemType::endStation) + /** + * + * rct2: 0x006DADAE + */ + void Vehicle::UpdateVelocity() { - Play3D(SoundId::blockBrakeClose, location); - } - else if (trackTypeIsBlockBrakes(trackType)) - { - Play3D(SoundId::blockBrakeClose, location); - BlockBrakeSetLinkedBrakesClosed(location, *trackElement, false); - } -} - -void Vehicle::UpdateGoKartAttemptSwitchLanes() -{ - uint16_t probability = 0x8000; - if (flags.has(VehicleFlag::currentlyColliding)) - { - flags.unset(VehicleFlag::currentlyColliding); - } - else - { - probability = 0x0A3D; - } - if ((ScenarioRand() & 0xFFFF) <= probability) - { - // This changes "riding left" to "moving to right lane" and "riding right" to "moving to left lane". - TrackSubposition = VehicleTrackSubposition{ static_cast(static_cast(TrackSubposition) + 2u) }; - } -} - -static void vehicle_update_play_water_splash_sound() -{ - if (_vehicleVelocityF64E08 <= kBlockBrakeBaseSpeed) - { - return; - } - - Play3D(SoundId::waterSplash, { _vehicleCurPosition.x, _vehicleCurPosition.y, _vehicleCurPosition.z }); -} - -/** - * - * rct2: 0x006DB59E - */ -void Vehicle::UpdateHandleWaterSplash() const -{ - const auto* rideEntry = GetRideEntry(); - auto trackType = GetTrackType(); - - if (!rideEntry->flags.has(RideEntryFlag::playSplashSound)) - { - if (rideEntry->flags.has(RideEntryFlag::coveredTrackIsWaterChannel)) + int32_t nextVelocity = acceleration + velocity; + if (flags.has(VehicleFlag::stoppedBySafetyCutout)) { - if (IsHead()) + nextVelocity = 0; + } + if (flags.has(VehicleFlag::stoppedOnHoldingBrake)) + { + if (vertical_drop_countdown > 0) { - if (IsOnCoveredTrack()) - { - Vehicle* nextVehicle = getGameState().entities.GetEntity(next_vehicle_on_ride); - if (nextVehicle == nullptr) - return; + nextVelocity = 0; + acceleration = 0; + vertical_drop_countdown--; + } + } + velocity = nextVelocity; - Vehicle* nextNextVehicle = getGameState().entities.GetEntity(nextVehicle->next_vehicle_on_ride); - if (nextNextVehicle == nullptr) - return; - if (!nextNextVehicle->IsOnCoveredTrack()) + _vehicleVelocityF64E08 = nextVelocity; + _vehicleVelocityF64E0C = (nextVelocity >> 10) * 42; + } + + static void BlockBrakesOpenPreviousSection( + const Ride& ride, const CoordsXYZ& vehicleTrackLocation, TileElement* tileElement) + { + CoordsXYZ location = vehicleTrackLocation; + TrackElement* trackElement = trackGetPreviousBlock(location, tileElement); + if (trackElement == nullptr) + return; + + SetBrakeClosedMultiTile(*trackElement, location, false); + MapInvalidateElement(location, reinterpret_cast(trackElement)); + + auto trackType = trackElement->GetTrackType(); + if (trackType == TrackElemType::endStation) + { + Play3D(SoundId::blockBrakeClose, location); + } + else if (trackTypeIsBlockBrakes(trackType)) + { + Play3D(SoundId::blockBrakeClose, location); + BlockBrakeSetLinkedBrakesClosed(location, *trackElement, false); + } + } + + void Vehicle::UpdateGoKartAttemptSwitchLanes() + { + uint16_t probability = 0x8000; + if (flags.has(VehicleFlag::currentlyColliding)) + { + flags.unset(VehicleFlag::currentlyColliding); + } + else + { + probability = 0x0A3D; + } + if ((ScenarioRand() & 0xFFFF) <= probability) + { + // This changes "riding left" to "moving to right lane" and "riding right" to "moving to left lane". + TrackSubposition = VehicleTrackSubposition{ static_cast(static_cast(TrackSubposition) + 2u) }; + } + } + + static void vehicle_update_play_water_splash_sound() + { + if (_vehicleVelocityF64E08 <= kBlockBrakeBaseSpeed) + { + return; + } + + Play3D(SoundId::waterSplash, { _vehicleCurPosition.x, _vehicleCurPosition.y, _vehicleCurPosition.z }); + } + + /** + * + * rct2: 0x006DB59E + */ + void Vehicle::UpdateHandleWaterSplash() const + { + const auto* rideEntry = GetRideEntry(); + auto trackType = GetTrackType(); + + if (!rideEntry->flags.has(RideEntryFlag::playSplashSound)) + { + if (rideEntry->flags.has(RideEntryFlag::coveredTrackIsWaterChannel)) + { + if (IsHead()) + { + if (IsOnCoveredTrack()) { - if (track_progress == 4) + Vehicle* nextVehicle = getGameState().entities.GetEntity(next_vehicle_on_ride); + if (nextVehicle == nullptr) + return; + + Vehicle* nextNextVehicle = getGameState().entities.GetEntity( + nextVehicle->next_vehicle_on_ride); + if (nextNextVehicle == nullptr) + return; + if (!nextNextVehicle->IsOnCoveredTrack()) { - vehicle_update_play_water_splash_sound(); + if (track_progress == 4) + { + vehicle_update_play_water_splash_sound(); + } } } } } } - } - else - { - if (trackType == TrackElemType::down25ToFlat) - { - if (track_progress == 12) - { - vehicle_update_play_water_splash_sound(); - } - } - } - if (IsHead()) - { - if (trackType == TrackElemType::waterSplash) - { - if (track_progress == 48) - { - vehicle_update_play_water_splash_sound(); - } - } - } -} - -/** - * - * rct2: 0x006DBF3E - */ -void Vehicle::Sub6DBF3E() -{ - const auto* carEntry = Entry(); - - acceleration /= _vehicleUnkF64E10; - if (TrackSubposition == VehicleTrackSubposition::chairliftGoingBack) - { - return; - } - - auto trackType = GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) - { - return; - } - - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_3; - - TileElement* tileElement = nullptr; - if (MapIsLocationValid(TrackLocation)) - { - tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); - } - - if (tileElement == nullptr) - { - return; - } - - if (_vehicleStationIndex.IsNull()) - { - _vehicleStationIndex = tileElement->asTrack()->GetStationIndex(); - } - - if (trackType == TrackElemType::towerBase && this == gCurrentVehicle) - { - if (track_progress > 3 && !flags.has(VehicleFlag::poweredCarInReverse)) - { - CoordsXYE output; - int32_t outputZ, outputDirection; - - CoordsXYE input = { TrackLocation, tileElement }; - if (!trackBlockGetNext(&input, &output, &outputZ, &outputDirection)) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_12; - } - } - - if (track_progress <= 3) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; - } - } - - if (trackType != TrackElemType::endStation || this != gCurrentVehicle) - { - return; - } - - uint16_t ax = track_progress; - if (_vehicleVelocityF64E08 < 0) - { - if (ax <= 22) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; - } - } - else - { - uint16_t cx = 17; - if (carEntry->flags.has(CarEntryFlag::isChairlift)) - { - cx = 6; - } - if (carEntry->flags.has(CarEntryFlag::isGoKart)) - { - // Determine the stop positions for the karts. If in left lane it's further along the track than the right lane. - // Since it's not possible to overtake when the race has ended, this does not check for overtake states (7 and - // 8). - cx = TrackSubposition == VehicleTrackSubposition::goKartsRightLane ? 18 : 20; - } - - if (ax > cx) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; - } - } -} - -/** - * Determine whether to use block brake speed or brake speed. If block brake is closed or no block brake present, use the - * brake's speed; if block brake is open, use maximum of brake speed or block brake speed. - */ -uint8_t Vehicle::ChooseBrakeSpeed() const -{ - if (!trackTypeIsBrakes(GetTrackType())) - return brake_speed; - auto trackElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, GetTrackType(), 0); - if (trackElement != nullptr) - { - if (trackElement->asTrack()->IsBrakeClosed()) - return brake_speed; else - return std::max(brake_speed, BlockBrakeSpeed); - } - return brake_speed; -} - -/** - * Populate the vehicle's brake_speed and BlockBrakeSpeed values. - */ -void Vehicle::PopulateBrakeSpeed(const CoordsXYZ& vehicleTrackLocation, TrackElement& brake) -{ - auto trackSpeed = brake.GetBrakeBoosterSpeed(); - brake_speed = trackSpeed; - if (!trackTypeIsBrakes(brake.GetTrackType())) - { - BlockBrakeSpeed = trackSpeed; - return; - } - // As soon as feasible, encode block brake speed into track element so the lookforward can be skipped here. - - CoordsXYE output = CoordsXYE(vehicleTrackLocation.x, vehicleTrackLocation.y, reinterpret_cast(&brake)); - int32_t outputZ = vehicleTrackLocation.z; - uint16_t timeoutCount = 256; - do - { - if (trackTypeIsBlockBrakes(output.element->asTrack()->GetTrackType())) { - BlockBrakeSpeed = output.element->asTrack()->GetBrakeBoosterSpeed(); - return; - } - if (!trackTypeIsBrakes(output.element->asTrack()->GetTrackType())) - { - break; - } - timeoutCount--; - } while (trackBlockGetNext(&output, &output, &outputZ, nullptr) && timeoutCount); - - // If block brake is not found, use the track's speed - BlockBrakeSpeed = trackSpeed; -} - -/** - * - * rct2: 0x006DB08C - */ -bool Vehicle::UpdateTrackMotionForwardsGetNewTrack( - TrackElemType trackType, const Ride& curRide, const RideObjectEntry& rideEntry) -{ - CoordsXYZD location = {}; - - auto pitchAndRollEnd = TrackPitchAndRollEnd(trackType); - TileElement* tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); - - if (tileElement == nullptr) - { - return false; - } - - if (trackType == TrackElemType::cableLiftHill && this == gCurrentVehicle) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_11; - } - - if (tileElement->asTrack()->IsBlockStart()) - { - if (next_vehicle_on_train.IsNull()) - { - SetBrakeClosedMultiTile(*tileElement->asTrack(), TrackLocation, true); - if (trackTypeIsBlockBrakes(trackType) || trackType == TrackElemType::endStation) + if (trackType == TrackElemType::down25ToFlat) { - if (!rideEntry.Cars[0].flags.has(CarEntryFlag::isPowered)) + if (track_progress == 12) { - Play3D(SoundId::blockBrakeRelease, TrackLocation); + vehicle_update_play_water_splash_sound(); } } - MapInvalidateElement(TrackLocation, tileElement); - BlockBrakesOpenPreviousSection(curRide, TrackLocation, tileElement); - if (trackTypeIsBlockBrakes(trackType)) + } + if (IsHead()) + { + if (trackType == TrackElemType::waterSplash) { - BlockBrakeSetLinkedBrakesClosed(TrackLocation, *tileElement->asTrack(), true); + if (track_progress == 48) + { + vehicle_update_play_water_splash_sound(); + } } } } - // Change from original: this used to check if the vehicle allowed doors. - UpdateSceneryDoor(); - - bool isGoingBack = false; - switch (TrackSubposition) + /** + * + * rct2: 0x006DBF3E + */ + void Vehicle::Sub6DBF3E() { - case VehicleTrackSubposition::chairliftGoingBack: - case VehicleTrackSubposition::chairliftEndBullwheel: - TrackSubposition = VehicleTrackSubposition::chairliftGoingBack; - isGoingBack = true; - break; - case VehicleTrackSubposition::chairliftStartBullwheel: - TrackSubposition = VehicleTrackSubposition::chairliftGoingOut; - break; - case VehicleTrackSubposition::goKartsMovingToRightLane: - TrackSubposition = VehicleTrackSubposition::goKartsRightLane; - break; - case VehicleTrackSubposition::goKartsMovingToLeftLane: - TrackSubposition = VehicleTrackSubposition::goKartsLeftLane; - break; - default: - break; + const auto* carEntry = Entry(); + + acceleration /= _vehicleUnkF64E10; + if (TrackSubposition == VehicleTrackSubposition::chairliftGoingBack) + { + return; + } + + auto trackType = GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + if (!ted.sequenceData.sequences[0].flags.has(SequenceFlag::trackOrigin)) + { + return; + } + + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_3; + + TileElement* tileElement = nullptr; + if (MapIsLocationValid(TrackLocation)) + { + tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); + } + + if (tileElement == nullptr) + { + return; + } + + if (_vehicleStationIndex.IsNull()) + { + _vehicleStationIndex = tileElement->asTrack()->GetStationIndex(); + } + + if (trackType == TrackElemType::towerBase && this == gCurrentVehicle) + { + if (track_progress > 3 && !flags.has(VehicleFlag::poweredCarInReverse)) + { + CoordsXYE output; + int32_t outputZ, outputDirection; + + CoordsXYE input = { TrackLocation, tileElement }; + if (!trackBlockGetNext(&input, &output, &outputZ, &outputDirection)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_12; + } + } + + if (track_progress <= 3) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; + } + } + + if (trackType != TrackElemType::endStation || this != gCurrentVehicle) + { + return; + } + + uint16_t ax = track_progress; + if (_vehicleVelocityF64E08 < 0) + { + if (ax <= 22) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; + } + } + else + { + uint16_t cx = 17; + if (carEntry->flags.has(CarEntryFlag::isChairlift)) + { + cx = 6; + } + if (carEntry->flags.has(CarEntryFlag::isGoKart)) + { + // Determine the stop positions for the karts. If in left lane it's further along the track than the right lane. + // Since it's not possible to overtake when the race has ended, this does not check for overtake states (7 and + // 8). + cx = TrackSubposition == VehicleTrackSubposition::goKartsRightLane ? 18 : 20; + } + + if (ax > cx) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION; + } + } } - if (isGoingBack) + /** + * Determine whether to use block brake speed or brake speed. If block brake is closed or no block brake present, use the + * brake's speed; if block brake is open, use maximum of brake speed or block brake speed. + */ + uint8_t Vehicle::ChooseBrakeSpeed() const { - TrackBeginEnd trackBeginEnd; - if (!trackBlockGetPrevious({ TrackLocation, tileElement }, &trackBeginEnd)) + if (!trackTypeIsBrakes(GetTrackType())) + return brake_speed; + auto trackElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, GetTrackType(), 0); + if (trackElement != nullptr) + { + if (trackElement->asTrack()->IsBrakeClosed()) + return brake_speed; + else + return std::max(brake_speed, BlockBrakeSpeed); + } + return brake_speed; + } + + /** + * Populate the vehicle's brake_speed and BlockBrakeSpeed values. + */ + void Vehicle::PopulateBrakeSpeed(const CoordsXYZ& vehicleTrackLocation, TrackElement& brake) + { + auto trackSpeed = brake.GetBrakeBoosterSpeed(); + brake_speed = trackSpeed; + if (!trackTypeIsBrakes(brake.GetTrackType())) + { + BlockBrakeSpeed = trackSpeed; + return; + } + // As soon as feasible, encode block brake speed into track element so the lookforward can be skipped here. + + CoordsXYE output = CoordsXYE(vehicleTrackLocation.x, vehicleTrackLocation.y, reinterpret_cast(&brake)); + int32_t outputZ = vehicleTrackLocation.z; + uint16_t timeoutCount = 256; + do + { + if (trackTypeIsBlockBrakes(output.element->asTrack()->GetTrackType())) + { + BlockBrakeSpeed = output.element->asTrack()->GetBrakeBoosterSpeed(); + return; + } + if (!trackTypeIsBrakes(output.element->asTrack()->GetTrackType())) + { + break; + } + timeoutCount--; + } while (trackBlockGetNext(&output, &output, &outputZ, nullptr) && timeoutCount); + + // If block brake is not found, use the track's speed + BlockBrakeSpeed = trackSpeed; + } + + /** + * + * rct2: 0x006DB08C + */ + bool Vehicle::UpdateTrackMotionForwardsGetNewTrack( + TrackElemType trackType, const Ride& curRide, const RideObjectEntry& rideEntry) + { + CoordsXYZD location = {}; + + auto pitchAndRollEnd = TrackPitchAndRollEnd(trackType); + TileElement* tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); + + if (tileElement == nullptr) { return false; } - location.x = trackBeginEnd.begin_x; - location.y = trackBeginEnd.begin_y; - location.z = trackBeginEnd.begin_z; - location.direction = trackBeginEnd.begin_direction; - tileElement = trackBeginEnd.begin_element; - } - else - { + + if (trackType == TrackElemType::cableLiftHill && this == gCurrentVehicle) { - int32_t curZ, direction; - CoordsXYE xyElement = { TrackLocation, tileElement }; - if (!trackBlockGetNext(&xyElement, &xyElement, &curZ, &direction)) + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_11; + } + + if (tileElement->asTrack()->IsBlockStart()) + { + if (next_vehicle_on_train.IsNull()) + { + SetBrakeClosedMultiTile(*tileElement->asTrack(), TrackLocation, true); + if (trackTypeIsBlockBrakes(trackType) || trackType == TrackElemType::endStation) + { + if (!rideEntry.Cars[0].flags.has(CarEntryFlag::isPowered)) + { + Play3D(SoundId::blockBrakeRelease, TrackLocation); + } + } + MapInvalidateElement(TrackLocation, tileElement); + BlockBrakesOpenPreviousSection(curRide, TrackLocation, tileElement); + if (trackTypeIsBlockBrakes(trackType)) + { + BlockBrakeSetLinkedBrakesClosed(TrackLocation, *tileElement->asTrack(), true); + } + } + } + + // Change from original: this used to check if the vehicle allowed doors. + UpdateSceneryDoor(); + + bool isGoingBack = false; + switch (TrackSubposition) + { + case VehicleTrackSubposition::chairliftGoingBack: + case VehicleTrackSubposition::chairliftEndBullwheel: + TrackSubposition = VehicleTrackSubposition::chairliftGoingBack; + isGoingBack = true; + break; + case VehicleTrackSubposition::chairliftStartBullwheel: + TrackSubposition = VehicleTrackSubposition::chairliftGoingOut; + break; + case VehicleTrackSubposition::goKartsMovingToRightLane: + TrackSubposition = VehicleTrackSubposition::goKartsRightLane; + break; + case VehicleTrackSubposition::goKartsMovingToLeftLane: + TrackSubposition = VehicleTrackSubposition::goKartsLeftLane; + break; + default: + break; + } + + if (isGoingBack) + { + TrackBeginEnd trackBeginEnd; + if (!trackBlockGetPrevious({ TrackLocation, tileElement }, &trackBeginEnd)) { return false; } - tileElement = xyElement.element; - location = { xyElement, curZ, static_cast(direction) }; + location.x = trackBeginEnd.begin_x; + location.y = trackBeginEnd.begin_y; + location.z = trackBeginEnd.begin_z; + location.direction = trackBeginEnd.begin_direction; + tileElement = trackBeginEnd.begin_element; } - if (tileElement->asTrack()->GetTrackType() == TrackElemType::leftReverser - || tileElement->asTrack()->GetTrackType() == TrackElemType::rightReverser) + else { - if (IsHead() && velocity <= 3.0_mph) { - velocity = 0; + int32_t curZ, direction; + CoordsXYE xyElement = { TrackLocation, tileElement }; + if (!trackBlockGetNext(&xyElement, &xyElement, &curZ, &direction)) + { + return false; + } + tileElement = xyElement.element; + location = { xyElement, curZ, static_cast(direction) }; + } + if (tileElement->asTrack()->GetTrackType() == TrackElemType::leftReverser + || tileElement->asTrack()->GetTrackType() == TrackElemType::rightReverser) + { + if (IsHead() && velocity <= 3.0_mph) + { + velocity = 0; + } + } + + if (PitchAndRollStart(flags.has(VehicleFlag::carIsInverted), tileElement) != pitchAndRollEnd) + { + return false; + } + + // Update VehicleFlags::CarIsInverted flag + const auto previousCarIsInverted = flags.has(VehicleFlag::carIsInverted); + flags.unset(VehicleFlag::carIsInverted); + { + auto rideType = OpenRCT2::GetRide(tileElement->asTrack()->GetRideIndex())->type; + if (GetRideTypeDescriptor(rideType).flags.has(RtdFlag::hasInvertedVariant)) + { + if (tileElement->asTrack()->IsInverted()) + { + flags.set(VehicleFlag::carIsInverted); + } + } + if (previousCarIsInverted != flags.has(VehicleFlag::carIsInverted)) + { + EntityTweener::Get().RemoveEntity(this); + } } } - if (PitchAndRollStart(flags.has(VehicleFlag::carIsInverted), tileElement) != pitchAndRollEnd) + const int32_t previousTrackHeight = TrackLocation.z; + TrackLocation = location; + + // TODO check if getting the vehicle entry again is necessary + const auto* carEntry = Entry(); + if (carEntry == nullptr) { return false; } - - // Update VehicleFlags::CarIsInverted flag - const auto previousCarIsInverted = flags.has(VehicleFlag::carIsInverted); - flags.unset(VehicleFlag::carIsInverted); + if (carEntry->flags.has(CarEntryFlag::isGoKart) && TrackSubposition < VehicleTrackSubposition::goKartsMovingToRightLane) { - auto rideType = ::GetRide(tileElement->asTrack()->GetRideIndex())->type; - if (GetRideTypeDescriptor(rideType).flags.has(RtdFlag::hasInvertedVariant)) + trackType = tileElement->asTrack()->GetTrackType(); + if (trackType == TrackElemType::flat || trackType == TrackElemType::leftQuarterTurn3Tiles + || trackType == TrackElemType::rightQuarterTurn3Tiles || trackType == TrackElemType::leftQuarterTurn5Tiles + || trackType == TrackElemType::rightQuarterTurn5Tiles || trackType == TrackElemType::leftEighthToDiag + || trackType == TrackElemType::rightEighthToDiag || trackType == TrackElemType::leftEighthToOrthogonal + || trackType == TrackElemType::rightEighthToOrthogonal || trackType == TrackElemType::diagFlat + || trackType == TrackElemType::sBendLeft || trackType == TrackElemType::sBendRight + || (curRide.flags.has(RideFlag::passStationNoStopping) && tileElement->asTrack()->IsStation())) + { + UpdateGoKartAttemptSwitchLanes(); + } + } + + if (TrackSubposition >= VehicleTrackSubposition::chairliftGoingOut + && TrackSubposition <= VehicleTrackSubposition::chairliftStartBullwheel) + { + TileCoordsXYZ curLocation{ TrackLocation }; + + if (curLocation == curRide.chairliftBullwheelLocation[1]) + { + TrackSubposition = VehicleTrackSubposition::chairliftEndBullwheel; + } + else if (curLocation == curRide.chairliftBullwheelLocation[0]) + { + TrackSubposition = VehicleTrackSubposition::chairliftStartBullwheel; + } + } + + // Loc6DB500 + // Update VehicleFlags::OnLiftHill + flags.unset(VehicleFlag::onLiftHill); + if (tileElement->asTrack()->HasChain()) + { + flags.set(VehicleFlag::onLiftHill); + } + + trackType = tileElement->asTrack()->GetTrackType(); + if (trackType != TrackElemType::brakes) + { + target_seat_rotation = tileElement->asTrack()->GetSeatRotation(); + } + SetTrackDirection(location.direction); + SetTrackType(trackType); + PopulateBrakeSpeed(TrackLocation, *tileElement->asTrack()); + if (flags.has(VehicleFlag::stoppedOnHoldingBrake) && vertical_drop_countdown <= 0) + { + flags.unset(VehicleFlag::stoppedOnHoldingBrake); + } + if (trackType == TrackElemType::onRidePhoto) + { + tileElement->asTrack()->SetPhotoTimeout(); + MapAnimations::CreateTemporary(TrackLocation, MapAnimations::TemporaryType::onRidePhoto); + } + if (trackType == TrackElemType::rotationControlToggle) + { + flags.flip(VehicleFlag::spinningIsLocked); + } + // Change from original: this used to check if the vehicle allowed doors. + UpdateSceneryDoorBackwards(); + UpdateLandscapeDoors(previousTrackHeight); + + return true; + } + + /** + * + * rct2: 0x006DAEB9 + */ + bool Vehicle::UpdateTrackMotionForwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry) + { + EntityId otherVehicleIndex = EntityId::GetNull(); + while (true) + { + auto trackType = GetTrackType(); + if (trackType == TrackElemType::heartLineTransferUp || trackType == TrackElemType::heartLineTransferDown) + { + if (track_progress == 80) + { + vehicle_type ^= 1; + carEntry = Entry(); + } + if (_vehicleVelocityF64E08 >= 0x40000) + { + acceleration = -_vehicleVelocityF64E08 * 8; + } + else if (_vehicleVelocityF64E08 < 0x20000) + { + acceleration = 0x50000; + } + } + else if (trackTypeIsBrakes(trackType)) + { + if (!curRide.hasFailingBrakes()) + { + auto brakeSpeed = ChooseBrakeSpeed() << kTrackSpeedShiftAmount; + + if ((brakeSpeed) < _vehicleVelocityF64E08) + { + acceleration = -_vehicleVelocityF64E08 * 16; + } + else if (!(getGameState().currentTicks & 0x0F)) + { + if (_vehicleF64E2C == 0) + { + _vehicleF64E2C++; + Play3D(SoundId::brakeRelease, { x, y, z }); + } + } + } + } + else if (trackTypeIsBooster(trackType)) + { + auto boosterSpeed = GetUnifiedBoosterSpeed(curRide.type, brake_speed) << kTrackSpeedShiftAmount; + if (boosterSpeed > _vehicleVelocityF64E08) + { + acceleration = GetRideTypeDescriptor(curRide.type).LegacyBoosterSettings.BoosterAcceleration + << kBoosterAccelerationShiftAmount; + } + } + else if (rideEntry.flags.has(RideEntryFlag::riderControlsSpeed) && num_peeps > 0) + { + acceleration += CalculateRiderBraking(); + } + + if ((trackType == TrackElemType::flat && curRide.getRideTypeDescriptor().flags.has(RtdFlag::hasLsmBehaviourOnFlat)) + || (trackType == TrackElemType::poweredLift)) + { + acceleration = GetRideTypeDescriptor(curRide.type).LegacyBoosterSettings.PoweredLiftAcceleration + << kBoosterAccelerationShiftAmount; + } + if (trackType == TrackElemType::brakeForDrop) + { + if (IsHead()) + { + if (!flags.has(VehicleFlag::stoppedOnHoldingBrake)) + { + if (track_progress >= 8) + { + acceleration = -_vehicleVelocityF64E08 * 16; + if (track_progress >= 24) + { + flags.set(VehicleFlag::stoppedOnHoldingBrake); + vertical_drop_countdown = 90; + } + } + } + } + } + if (trackType == TrackElemType::logFlumeReverser) + { + if (track_progress != 16 || velocity < 4.0_mph) + { + if (track_progress == 32) + { + vehicle_type = carEntry->ReversedCarIndex; + carEntry = Entry(); + } + } + else + { + track_progress += 17; + } + } + + uint16_t newTrackProgress = track_progress + 1; + + // Track Total Progress is in the two bytes before the move info list + uint16_t trackTotalProgress = GetTrackProgress(); + if (newTrackProgress >= trackTotalProgress) + { + UpdateCrossings(); + + if (!UpdateTrackMotionForwardsGetNewTrack(trackType, curRide, rideEntry)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_5; + _vehicleVelocityF64E0C -= remaining_distance + 1; + remaining_distance = -1; + return false; + } + newTrackProgress = 0; + } + + track_progress = newTrackProgress; + UpdateHandleWaterSplash(); + + // Loc6DB706 + const auto moveInfo = GetMoveInfo(); + trackType = GetTrackType(); + { + auto nextVehiclePosition = TrackLocation + + CoordsXYZ{ moveInfo->x, moveInfo->y, + moveInfo->z + GetRideTypeDescriptor(curRide.type).Heights.VehicleZOffset }; + + bool useReverserDistance = TrackSubposition == VehicleTrackSubposition::reverserRCFrontBogie + && (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) + && track_progress >= 30 && track_progress <= 66; + + // Loc6DB8A5 + remaining_distance -= Geometry::getTranslationDistance( + nextVehiclePosition - _vehicleCurPosition, useReverserDistance); + + if (TrackSubposition == VehicleTrackSubposition::reverserRCRearBogie + && (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) + && track_progress == 96) + { + ReverseReverserCar(); + + const VehicleInfo* moveInfo2 = GetMoveInfo(); + nextVehiclePosition.x = x + moveInfo2->x; + nextVehiclePosition.y = y + moveInfo2->y; + } + + _vehicleCurPosition = nextVehiclePosition; + orientation = moveInfo->yaw; + roll = moveInfo->roll; + pitch = moveInfo->pitch; + + if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing) && moveInfo->pitch != VehiclePitch::flat) + { + SwingSprite = 0; + SwingPosition = 0; + SwingSpeed = 0; + } + + // this == frontVehicle + if (this == _vehicleFrontVehicle) + { + if (_vehicleVelocityF64E08 >= 0) + { + otherVehicleIndex = prev_vehicle_on_ride; + if (UpdateMotionCollisionDetection(nextVehiclePosition, &otherVehicleIndex)) + { + _vehicleVelocityF64E0C -= remaining_distance + 1; + remaining_distance = -1; + + // Might need to be bp rather than this, but hopefully not + auto otherVeh = getGameState().entities.GetEntity(otherVehicleIndex); + if (otherVeh == nullptr) + { + // This can never happen as prev_vehicle_on_ride will always be set to a vehicle + LOG_ERROR("Failed to get next vehicle during update!"); + return true; + } + auto head = otherVeh->TrainHead(); + + auto velocityDelta = abs(velocity - head->velocity); + if (!rideEntry.flags.has(RideEntryFlag::disableCollisionCrashes)) + { + if (velocityDelta > 14.0_mph) + { + if (!carEntry->flags.has(CarEntryFlag::useBoatHireCollisionDetection)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION; + } + } + } + + if (carEntry->flags.has(CarEntryFlag::isGoKart)) + { + velocity -= velocity >> 2; + } + else + { + int32_t newHeadVelocity = velocity >> 1; + velocity = head->velocity >> 1; + head->velocity = newHeadVelocity; + } + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_1; + return false; + } + } + } + } + + // Loc6DB928 + if (remaining_distance < 0x368A) + { + return true; + } + + acceleration += Geometry::getAccelerationFromPitch(pitch); + _vehicleUnkF64E10++; + } + } + + static PitchAndRoll PitchAndRollEnd( + const Ride& curRide, bool useInvertedSprites, TrackElemType trackType, TileElement* tileElement) + { + bool isInverted = useInvertedSprites ^ tileElement->asTrack()->IsInverted(); + const auto& ted = GetTrackElementDescriptor(trackType); + return { ted.definition.pitchEnd, TrackGetActualBank2(curRide.type, isInverted, ted.definition.rollEnd) }; + } + + /** + * + * rct2: 0x006DBAA6 + */ + bool Vehicle::UpdateTrackMotionBackwardsGetNewTrack(TrackElemType trackType, const Ride& curRide, uint16_t* progress) + { + auto pitchAndRollStart = TrackPitchAndRollStart(trackType); + TileElement* tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); + + if (tileElement == nullptr) + return false; + + bool nextTileBackwards = true; + int32_t direction = 0; + // Loc6DBB08:; + auto trackPos = CoordsXYZ{ TrackLocation.x, TrackLocation.y, 0 }; + + switch (TrackSubposition) + { + case VehicleTrackSubposition::chairliftEndBullwheel: + TrackSubposition = VehicleTrackSubposition::chairliftGoingOut; + break; + case VehicleTrackSubposition::goKartsMovingToRightLane: + TrackSubposition = VehicleTrackSubposition::goKartsLeftLane; + break; + case VehicleTrackSubposition::goKartsMovingToLeftLane: + TrackSubposition = VehicleTrackSubposition::goKartsRightLane; + break; + case VehicleTrackSubposition::chairliftGoingBack: + case VehicleTrackSubposition::chairliftStartBullwheel: + TrackSubposition = VehicleTrackSubposition::chairliftGoingBack; + nextTileBackwards = false; + break; + default: + break; + } + + if (nextTileBackwards) + { + // Loc6DBB7E:; + TrackBeginEnd trackBeginEnd; + if (!trackBlockGetPrevious({ trackPos, tileElement }, &trackBeginEnd)) + { + return false; + } + tileElement = trackBeginEnd.begin_element; + + trackType = tileElement->asTrack()->GetTrackType(); + if (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) + { + return false; + } + + if (PitchAndRollEnd(curRide, flags.has(VehicleFlag::carIsInverted), trackType, tileElement) != pitchAndRollStart) + { + return false; + } + + // Update VehicleFlags::CarIsInverted + const auto previousCarIsInverted = flags.has(VehicleFlag::carIsInverted); + flags.unset(VehicleFlag::carIsInverted); + if (GetRideTypeDescriptor(curRide.type).flags.has(RtdFlag::hasInvertedVariant)) { if (tileElement->asTrack()->IsInverted()) { flags.set(VehicleFlag::carIsInverted); } - } - if (previousCarIsInverted != flags.has(VehicleFlag::carIsInverted)) - { - EntityTweener::Get().RemoveEntity(this); - } - } - } - - const int32_t previousTrackHeight = TrackLocation.z; - TrackLocation = location; - - // TODO check if getting the vehicle entry again is necessary - const auto* carEntry = Entry(); - if (carEntry == nullptr) - { - return false; - } - if (carEntry->flags.has(CarEntryFlag::isGoKart) && TrackSubposition < VehicleTrackSubposition::goKartsMovingToRightLane) - { - trackType = tileElement->asTrack()->GetTrackType(); - if (trackType == TrackElemType::flat || trackType == TrackElemType::leftQuarterTurn3Tiles - || trackType == TrackElemType::rightQuarterTurn3Tiles || trackType == TrackElemType::leftQuarterTurn5Tiles - || trackType == TrackElemType::rightQuarterTurn5Tiles || trackType == TrackElemType::leftEighthToDiag - || trackType == TrackElemType::rightEighthToDiag || trackType == TrackElemType::leftEighthToOrthogonal - || trackType == TrackElemType::rightEighthToOrthogonal || trackType == TrackElemType::diagFlat - || trackType == TrackElemType::sBendLeft || trackType == TrackElemType::sBendRight - || (curRide.flags.has(RideFlag::passStationNoStopping) && tileElement->asTrack()->IsStation())) - { - UpdateGoKartAttemptSwitchLanes(); - } - } - - if (TrackSubposition >= VehicleTrackSubposition::chairliftGoingOut - && TrackSubposition <= VehicleTrackSubposition::chairliftStartBullwheel) - { - TileCoordsXYZ curLocation{ TrackLocation }; - - if (curLocation == curRide.chairliftBullwheelLocation[1]) - { - TrackSubposition = VehicleTrackSubposition::chairliftEndBullwheel; - } - else if (curLocation == curRide.chairliftBullwheelLocation[0]) - { - TrackSubposition = VehicleTrackSubposition::chairliftStartBullwheel; - } - } - - // Loc6DB500 - // Update VehicleFlags::OnLiftHill - flags.unset(VehicleFlag::onLiftHill); - if (tileElement->asTrack()->HasChain()) - { - flags.set(VehicleFlag::onLiftHill); - } - - trackType = tileElement->asTrack()->GetTrackType(); - if (trackType != TrackElemType::brakes) - { - target_seat_rotation = tileElement->asTrack()->GetSeatRotation(); - } - SetTrackDirection(location.direction); - SetTrackType(trackType); - PopulateBrakeSpeed(TrackLocation, *tileElement->asTrack()); - if (flags.has(VehicleFlag::stoppedOnHoldingBrake) && vertical_drop_countdown <= 0) - { - flags.unset(VehicleFlag::stoppedOnHoldingBrake); - } - if (trackType == TrackElemType::onRidePhoto) - { - tileElement->asTrack()->SetPhotoTimeout(); - MapAnimations::CreateTemporary(TrackLocation, MapAnimations::TemporaryType::onRidePhoto); - } - if (trackType == TrackElemType::rotationControlToggle) - { - flags.flip(VehicleFlag::spinningIsLocked); - } - // Change from original: this used to check if the vehicle allowed doors. - UpdateSceneryDoorBackwards(); - UpdateLandscapeDoors(previousTrackHeight); - - return true; -} - -/** - * - * rct2: 0x006DAEB9 - */ -bool Vehicle::UpdateTrackMotionForwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry) -{ - EntityId otherVehicleIndex = EntityId::GetNull(); - while (true) - { - auto trackType = GetTrackType(); - if (trackType == TrackElemType::heartLineTransferUp || trackType == TrackElemType::heartLineTransferDown) - { - if (track_progress == 80) - { - vehicle_type ^= 1; - carEntry = Entry(); - } - if (_vehicleVelocityF64E08 >= 0x40000) - { - acceleration = -_vehicleVelocityF64E08 * 8; - } - else if (_vehicleVelocityF64E08 < 0x20000) - { - acceleration = 0x50000; - } - } - else if (trackTypeIsBrakes(trackType)) - { - if (!curRide.hasFailingBrakes()) - { - auto brakeSpeed = ChooseBrakeSpeed() << kTrackSpeedShiftAmount; - - if ((brakeSpeed) < _vehicleVelocityF64E08) + if (previousCarIsInverted != flags.has(VehicleFlag::carIsInverted)) { - acceleration = -_vehicleVelocityF64E08 * 16; - } - else if (!(getGameState().currentTicks & 0x0F)) - { - if (_vehicleF64E2C == 0) - { - _vehicleF64E2C++; - Play3D(SoundId::brakeRelease, { x, y, z }); - } + EntityTweener::Get().RemoveEntity(this); } } - } - else if (trackTypeIsBooster(trackType)) - { - auto boosterSpeed = GetUnifiedBoosterSpeed(curRide.type, brake_speed) << kTrackSpeedShiftAmount; - if (boosterSpeed > _vehicleVelocityF64E08) - { - acceleration = GetRideTypeDescriptor(curRide.type).LegacyBoosterSettings.BoosterAcceleration - << kBoosterAccelerationShiftAmount; - } - } - else if (rideEntry.flags.has(RideEntryFlag::riderControlsSpeed) && num_peeps > 0) - { - acceleration += CalculateRiderBraking(); - } - if ((trackType == TrackElemType::flat && curRide.getRideTypeDescriptor().flags.has(RtdFlag::hasLsmBehaviourOnFlat)) - || (trackType == TrackElemType::poweredLift)) - { - acceleration = GetRideTypeDescriptor(curRide.type).LegacyBoosterSettings.PoweredLiftAcceleration - << kBoosterAccelerationShiftAmount; + trackPos = { trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }; + direction = trackBeginEnd.begin_direction; } - if (trackType == TrackElemType::brakeForDrop) + else { - if (IsHead()) - { - if (!flags.has(VehicleFlag::stoppedOnHoldingBrake)) - { - if (track_progress >= 8) - { - acceleration = -_vehicleVelocityF64E08 * 16; - if (track_progress >= 24) - { - flags.set(VehicleFlag::stoppedOnHoldingBrake); - vertical_drop_countdown = 90; - } - } - } - } - } - if (trackType == TrackElemType::logFlumeReverser) - { - if (track_progress != 16 || velocity < 4.0_mph) - { - if (track_progress == 32) - { - vehicle_type = carEntry->ReversedCarIndex; - carEntry = Entry(); - } - } - else - { - track_progress += 17; - } - } + // Loc6DBB4F:; + CoordsXYE input; + CoordsXYE output; + int32_t outputZ{}; - uint16_t newTrackProgress = track_progress + 1; - - // Track Total Progress is in the two bytes before the move info list - uint16_t trackTotalProgress = GetTrackProgress(); - if (newTrackProgress >= trackTotalProgress) - { - UpdateCrossings(); - - if (!UpdateTrackMotionForwardsGetNewTrack(trackType, curRide, rideEntry)) + input.x = trackPos.x; + input.y = trackPos.y; + input.element = tileElement; + if (!trackBlockGetNext(&input, &output, &outputZ, &direction)) { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_5; - _vehicleVelocityF64E0C -= remaining_distance + 1; - remaining_distance = -1; return false; } - newTrackProgress = 0; + tileElement = output.element; + trackPos = { output, outputZ }; } - track_progress = newTrackProgress; - UpdateHandleWaterSplash(); + // Loc6DBC3B: + TrackLocation = trackPos; - // Loc6DB706 - const auto moveInfo = GetMoveInfo(); - trackType = GetTrackType(); + if (TrackSubposition >= VehicleTrackSubposition::chairliftGoingOut + && TrackSubposition <= VehicleTrackSubposition::chairliftStartBullwheel) { - auto nextVehiclePosition = TrackLocation - + CoordsXYZ{ moveInfo->x, moveInfo->y, - moveInfo->z + GetRideTypeDescriptor(curRide.type).Heights.VehicleZOffset }; + TileCoordsXYZ curLocation{ TrackLocation }; - bool useReverserDistance = TrackSubposition == VehicleTrackSubposition::reverserRCFrontBogie - && (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) - && track_progress >= 30 && track_progress <= 66; - - // Loc6DB8A5 - remaining_distance -= Geometry::getTranslationDistance( - nextVehiclePosition - _vehicleCurPosition, useReverserDistance); - - if (TrackSubposition == VehicleTrackSubposition::reverserRCRearBogie - && (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) - && track_progress == 96) + if (curLocation == curRide.chairliftBullwheelLocation[1]) { - ReverseReverserCar(); - - const VehicleInfo* moveInfo2 = GetMoveInfo(); - nextVehiclePosition.x = x + moveInfo2->x; - nextVehiclePosition.y = y + moveInfo2->y; + TrackSubposition = VehicleTrackSubposition::chairliftEndBullwheel; } - - _vehicleCurPosition = nextVehiclePosition; - orientation = moveInfo->yaw; - roll = moveInfo->roll; - pitch = moveInfo->pitch; - - if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing) && moveInfo->pitch != VehiclePitch::flat) + else if (curLocation == curRide.chairliftBullwheelLocation[0]) { - SwingSprite = 0; - SwingPosition = 0; - SwingSpeed = 0; + TrackSubposition = VehicleTrackSubposition::chairliftStartBullwheel; } + } - // this == frontVehicle - if (this == _vehicleFrontVehicle) + if (tileElement->asTrack()->HasChain()) + { + if (_vehicleVelocityF64E08 < 0) { - if (_vehicleVelocityF64E08 >= 0) + if (next_vehicle_on_train.IsNull()) { - otherVehicleIndex = prev_vehicle_on_ride; - if (UpdateMotionCollisionDetection(nextVehiclePosition, &otherVehicleIndex)) + trackType = tileElement->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + if (!ted.flags.has(TrackElementFlag::down)) { - _vehicleVelocityF64E0C -= remaining_distance + 1; - remaining_distance = -1; + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_9; + } + } + flags.set(VehicleFlag::onLiftHill); + } + } + else + { + if (flags.has(VehicleFlag::onLiftHill)) + { + flags.unset(VehicleFlag::onLiftHill); + if (next_vehicle_on_train.IsNull()) + { + if (_vehicleVelocityF64E08 < 0) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_8; + } + } + } + } - // Might need to be bp rather than this, but hopefully not - auto otherVeh = getGameState().entities.GetEntity(otherVehicleIndex); - if (otherVeh == nullptr) - { - // This can never happen as prev_vehicle_on_ride will always be set to a vehicle - LOG_ERROR("Failed to get next vehicle during update!"); - return true; - } - auto head = otherVeh->TrainHead(); + trackType = tileElement->asTrack()->GetTrackType(); + if (trackType != TrackElemType::brakes) + { + target_seat_rotation = tileElement->asTrack()->GetSeatRotation(); + } + direction &= 3; + SetTrackType(trackType); + SetTrackDirection(direction); + PopulateBrakeSpeed(TrackLocation, *tileElement->asTrack()); + if (flags.has(VehicleFlag::stoppedOnHoldingBrake) && vertical_drop_countdown <= 0) + { + flags.unset(VehicleFlag::stoppedOnHoldingBrake); + } + // There are two bytes before the move info list + uint16_t trackTotalProgress = GetTrackProgress(); + *progress = trackTotalProgress - 1; + return true; + } - auto velocityDelta = abs(velocity - head->velocity); - if (!rideEntry.flags.has(RideEntryFlag::disableCollisionCrashes)) + /** + * + * rct2: 0x006DBA33 + */ + bool Vehicle::UpdateTrackMotionBackwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry) + { + EntityId otherVehicleIndex = EntityId::GetNull(); + + while (true) + { + auto trackType = GetTrackType(); + if (trackType == TrackElemType::flat && curRide.getRideTypeDescriptor().flags.has(RtdFlag::hasLsmBehaviourOnFlat)) + { + int32_t unkVelocity = _vehicleVelocityF64E08; + if (unkVelocity < -524288) + { + unkVelocity = abs(unkVelocity); + acceleration = unkVelocity * 2; + } + } + + if (trackTypeIsBrakes(trackType)) + { + auto brakeSpeed = ChooseBrakeSpeed(); + + if (-(brakeSpeed << kTrackSpeedShiftAmount) > _vehicleVelocityF64E08) + { + acceleration = _vehicleVelocityF64E08 * -16; + } + } + + uint16_t newTrackProgress = track_progress - 1; + if (newTrackProgress == 0xFFFF) + { + UpdateCrossings(); + + if (!UpdateTrackMotionBackwardsGetNewTrack(trackType, curRide, &newTrackProgress)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_5; + _vehicleVelocityF64E0C -= remaining_distance - 0x368A; + remaining_distance = 0x368A; + return false; + } + } + + // Loc6DBD42 + track_progress = newTrackProgress; + { + const VehicleInfo* moveInfo = GetMoveInfo(); + auto nextVehiclePosition = TrackLocation + + CoordsXYZ{ moveInfo->x, moveInfo->y, + moveInfo->z + GetRideTypeDescriptor(curRide.type).Heights.VehicleZOffset }; + + remaining_distance += Geometry::getTranslationDistance(nextVehiclePosition - _vehicleCurPosition, false); + + _vehicleCurPosition = nextVehiclePosition; + orientation = moveInfo->yaw; + roll = moveInfo->roll; + pitch = moveInfo->pitch; + + if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing) && pitch != VehiclePitch::flat) + { + SwingSprite = 0; + SwingPosition = 0; + SwingSpeed = 0; + } + + if (this == _vehicleFrontVehicle) + { + if (_vehicleVelocityF64E08 < 0) + { + otherVehicleIndex = next_vehicle_on_ride; + if (UpdateMotionCollisionDetection(nextVehiclePosition, &otherVehicleIndex)) { - if (velocityDelta > 14.0_mph) + _vehicleVelocityF64E0C -= remaining_distance - 0x368A; + remaining_distance = 0x368A; + + Vehicle* v3 = getGameState().entities.GetEntity(otherVehicleIndex); + Vehicle* v4 = gCurrentVehicle; + if (v3 == nullptr) { - if (!carEntry->flags.has(CarEntryFlag::useBoatHireCollisionDetection)) + return false; + } + + if (!rideEntry.flags.has(RideEntryFlag::disableCollisionCrashes)) + { + if (abs(v4->velocity - v3->velocity) > 14.0_mph) { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION; + if (!carEntry->flags.has(CarEntryFlag::useBoatHireCollisionDetection)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION; + } } } - } - if (carEntry->flags.has(CarEntryFlag::isGoKart)) - { - velocity -= velocity >> 2; - } - else - { - int32_t newHeadVelocity = velocity >> 1; - velocity = head->velocity >> 1; - head->velocity = newHeadVelocity; - } - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_1; - return false; - } - } - } - } + if (carEntry->flags.has(CarEntryFlag::isGoKart)) + { + velocity -= velocity >> 2; + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_2; + } + else + { + int32_t v3Velocity = v3->velocity; + v3->velocity = v4->velocity >> 1; + v4->velocity = v3Velocity >> 1; + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_2; + } - // Loc6DB928 - if (remaining_distance < 0x368A) - { - return true; - } - - acceleration += Geometry::getAccelerationFromPitch(pitch); - _vehicleUnkF64E10++; - } -} - -static PitchAndRoll PitchAndRollEnd( - const Ride& curRide, bool useInvertedSprites, TrackElemType trackType, TileElement* tileElement) -{ - bool isInverted = useInvertedSprites ^ tileElement->asTrack()->IsInverted(); - const auto& ted = GetTrackElementDescriptor(trackType); - return { ted.definition.pitchEnd, TrackGetActualBank2(curRide.type, isInverted, ted.definition.rollEnd) }; -} - -/** - * - * rct2: 0x006DBAA6 - */ -bool Vehicle::UpdateTrackMotionBackwardsGetNewTrack(TrackElemType trackType, const Ride& curRide, uint16_t* progress) -{ - auto pitchAndRollStart = TrackPitchAndRollStart(trackType); - TileElement* tileElement = MapGetTrackElementAtOfTypeSeq(TrackLocation, trackType, 0); - - if (tileElement == nullptr) - return false; - - bool nextTileBackwards = true; - int32_t direction = 0; - // Loc6DBB08:; - auto trackPos = CoordsXYZ{ TrackLocation.x, TrackLocation.y, 0 }; - - switch (TrackSubposition) - { - case VehicleTrackSubposition::chairliftEndBullwheel: - TrackSubposition = VehicleTrackSubposition::chairliftGoingOut; - break; - case VehicleTrackSubposition::goKartsMovingToRightLane: - TrackSubposition = VehicleTrackSubposition::goKartsLeftLane; - break; - case VehicleTrackSubposition::goKartsMovingToLeftLane: - TrackSubposition = VehicleTrackSubposition::goKartsRightLane; - break; - case VehicleTrackSubposition::chairliftGoingBack: - case VehicleTrackSubposition::chairliftStartBullwheel: - TrackSubposition = VehicleTrackSubposition::chairliftGoingBack; - nextTileBackwards = false; - break; - default: - break; - } - - if (nextTileBackwards) - { - // Loc6DBB7E:; - TrackBeginEnd trackBeginEnd; - if (!trackBlockGetPrevious({ trackPos, tileElement }, &trackBeginEnd)) - { - return false; - } - tileElement = trackBeginEnd.begin_element; - - trackType = tileElement->asTrack()->GetTrackType(); - if (trackType == TrackElemType::leftReverser || trackType == TrackElemType::rightReverser) - { - return false; - } - - if (PitchAndRollEnd(curRide, flags.has(VehicleFlag::carIsInverted), trackType, tileElement) != pitchAndRollStart) - { - return false; - } - - // Update VehicleFlags::CarIsInverted - const auto previousCarIsInverted = flags.has(VehicleFlag::carIsInverted); - flags.unset(VehicleFlag::carIsInverted); - if (GetRideTypeDescriptor(curRide.type).flags.has(RtdFlag::hasInvertedVariant)) - { - if (tileElement->asTrack()->IsInverted()) - { - flags.set(VehicleFlag::carIsInverted); - } - if (previousCarIsInverted != flags.has(VehicleFlag::carIsInverted)) - { - EntityTweener::Get().RemoveEntity(this); - } - } - - trackPos = { trackBeginEnd.begin_x, trackBeginEnd.begin_y, trackBeginEnd.begin_z }; - direction = trackBeginEnd.begin_direction; - } - else - { - // Loc6DBB4F:; - CoordsXYE input; - CoordsXYE output; - int32_t outputZ{}; - - input.x = trackPos.x; - input.y = trackPos.y; - input.element = tileElement; - if (!trackBlockGetNext(&input, &output, &outputZ, &direction)) - { - return false; - } - tileElement = output.element; - trackPos = { output, outputZ }; - } - - // Loc6DBC3B: - TrackLocation = trackPos; - - if (TrackSubposition >= VehicleTrackSubposition::chairliftGoingOut - && TrackSubposition <= VehicleTrackSubposition::chairliftStartBullwheel) - { - TileCoordsXYZ curLocation{ TrackLocation }; - - if (curLocation == curRide.chairliftBullwheelLocation[1]) - { - TrackSubposition = VehicleTrackSubposition::chairliftEndBullwheel; - } - else if (curLocation == curRide.chairliftBullwheelLocation[0]) - { - TrackSubposition = VehicleTrackSubposition::chairliftStartBullwheel; - } - } - - if (tileElement->asTrack()->HasChain()) - { - if (_vehicleVelocityF64E08 < 0) - { - if (next_vehicle_on_train.IsNull()) - { - trackType = tileElement->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - if (!ted.flags.has(TrackElementFlag::down)) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_9; - } - } - flags.set(VehicleFlag::onLiftHill); - } - } - else - { - if (flags.has(VehicleFlag::onLiftHill)) - { - flags.unset(VehicleFlag::onLiftHill); - if (next_vehicle_on_train.IsNull()) - { - if (_vehicleVelocityF64E08 < 0) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_8; - } - } - } - } - - trackType = tileElement->asTrack()->GetTrackType(); - if (trackType != TrackElemType::brakes) - { - target_seat_rotation = tileElement->asTrack()->GetSeatRotation(); - } - direction &= 3; - SetTrackType(trackType); - SetTrackDirection(direction); - PopulateBrakeSpeed(TrackLocation, *tileElement->asTrack()); - if (flags.has(VehicleFlag::stoppedOnHoldingBrake) && vertical_drop_countdown <= 0) - { - flags.unset(VehicleFlag::stoppedOnHoldingBrake); - } - // There are two bytes before the move info list - uint16_t trackTotalProgress = GetTrackProgress(); - *progress = trackTotalProgress - 1; - return true; -} - -/** - * - * rct2: 0x006DBA33 - */ -bool Vehicle::UpdateTrackMotionBackwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry) -{ - EntityId otherVehicleIndex = EntityId::GetNull(); - - while (true) - { - auto trackType = GetTrackType(); - if (trackType == TrackElemType::flat && curRide.getRideTypeDescriptor().flags.has(RtdFlag::hasLsmBehaviourOnFlat)) - { - int32_t unkVelocity = _vehicleVelocityF64E08; - if (unkVelocity < -524288) - { - unkVelocity = abs(unkVelocity); - acceleration = unkVelocity * 2; - } - } - - if (trackTypeIsBrakes(trackType)) - { - auto brakeSpeed = ChooseBrakeSpeed(); - - if (-(brakeSpeed << kTrackSpeedShiftAmount) > _vehicleVelocityF64E08) - { - acceleration = _vehicleVelocityF64E08 * -16; - } - } - - uint16_t newTrackProgress = track_progress - 1; - if (newTrackProgress == 0xFFFF) - { - UpdateCrossings(); - - if (!UpdateTrackMotionBackwardsGetNewTrack(trackType, curRide, &newTrackProgress)) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_5; - _vehicleVelocityF64E0C -= remaining_distance - 0x368A; - remaining_distance = 0x368A; - return false; - } - } - - // Loc6DBD42 - track_progress = newTrackProgress; - { - const VehicleInfo* moveInfo = GetMoveInfo(); - auto nextVehiclePosition = TrackLocation - + CoordsXYZ{ moveInfo->x, moveInfo->y, - moveInfo->z + GetRideTypeDescriptor(curRide.type).Heights.VehicleZOffset }; - - remaining_distance += Geometry::getTranslationDistance(nextVehiclePosition - _vehicleCurPosition, false); - - _vehicleCurPosition = nextVehiclePosition; - orientation = moveInfo->yaw; - roll = moveInfo->roll; - pitch = moveInfo->pitch; - - if (carEntry->flags.has(CarEntryFlag::useWoodenWildMouseSwing) && pitch != VehiclePitch::flat) - { - SwingSprite = 0; - SwingPosition = 0; - SwingSpeed = 0; - } - - if (this == _vehicleFrontVehicle) - { - if (_vehicleVelocityF64E08 < 0) - { - otherVehicleIndex = next_vehicle_on_ride; - if (UpdateMotionCollisionDetection(nextVehiclePosition, &otherVehicleIndex)) - { - _vehicleVelocityF64E0C -= remaining_distance - 0x368A; - remaining_distance = 0x368A; - - Vehicle* v3 = getGameState().entities.GetEntity(otherVehicleIndex); - Vehicle* v4 = gCurrentVehicle; - if (v3 == nullptr) - { return false; } - - if (!rideEntry.flags.has(RideEntryFlag::disableCollisionCrashes)) - { - if (abs(v4->velocity - v3->velocity) > 14.0_mph) - { - if (!carEntry->flags.has(CarEntryFlag::useBoatHireCollisionDetection)) - { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION; - } - } - } - - if (carEntry->flags.has(CarEntryFlag::isGoKart)) - { - velocity -= velocity >> 2; - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_2; - } - else - { - int32_t v3Velocity = v3->velocity; - v3->velocity = v4->velocity >> 1; - v4->velocity = v3Velocity >> 1; - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_2; - } - - return false; } } } - } - // Loc6DBE3F - if (remaining_distance >= 0) - { - return true; - } - acceleration += Geometry::getAccelerationFromPitch(pitch); - _vehicleUnkF64E10++; - } -} - -/** - * - * rct2: 0x006DC1E4 - */ -static uint8_t modified_speed(TrackElemType trackType, VehicleTrackSubposition trackSubposition, uint8_t speed) -{ - enum - { - FULL_SPEED, - THREE_QUARTER_SPEED, - HALF_SPEED - }; - - uint8_t speedModifier = FULL_SPEED; - - if (trackType == TrackElemType::leftQuarterTurn1Tile) - { - speedModifier = (trackSubposition == VehicleTrackSubposition::goKartsLeftLane) ? HALF_SPEED : THREE_QUARTER_SPEED; - } - else if (trackType == TrackElemType::rightQuarterTurn1Tile) - { - speedModifier = (trackSubposition == VehicleTrackSubposition::goKartsRightLane) ? HALF_SPEED : THREE_QUARTER_SPEED; - } - - switch (speedModifier) - { - case HALF_SPEED: - return speed >> 1; - case THREE_QUARTER_SPEED: - return speed - (speed >> 2); - } - return speed; -} - -int32_t Vehicle::UpdateTrackMotionPoweredRideAcceleration( - const CarEntry* carEntry, uint32_t totalMass, const int32_t curAcceleration) -{ - if (carEntry->flags.has(CarEntryFlag::isPoweredRideWithUnrestrictedGravity)) - { - if (velocity > (speed * 0x4000)) - { - // Same code as none powered rides - if (curAcceleration <= 0 && curAcceleration >= -500 && velocity <= 0.5_mph) + // Loc6DBE3F + if (remaining_distance >= 0) { - return curAcceleration + 400; + return true; } - return curAcceleration; + acceleration += Geometry::getAccelerationFromPitch(pitch); + _vehicleUnkF64E10++; } } - uint8_t modifiedSpeed = modified_speed(GetTrackType(), TrackSubposition, speed); - int32_t poweredAcceleration = modifiedSpeed << 14; - int32_t quarterForce = (modifiedSpeed * totalMass) >> 2; - if (flags.has(VehicleFlag::poweredCarInReverse)) - { - poweredAcceleration = -poweredAcceleration; - } - poweredAcceleration -= velocity; - poweredAcceleration *= powered_acceleration << 1; - if (quarterForce != 0) - { - poweredAcceleration /= quarterForce; - } - if (carEntry->flags.has(CarEntryFlag::isLift)) + /** + * + * rct2: 0x006DC1E4 + */ + static uint8_t modified_speed(TrackElemType trackType, VehicleTrackSubposition trackSubposition, uint8_t speed) { - poweredAcceleration *= 4; - } - - if (carEntry->flags.has(CarEntryFlag::isWaterRide)) - { - if (poweredAcceleration < 0) + enum { - poweredAcceleration >>= 4; - } + FULL_SPEED, + THREE_QUARTER_SPEED, + HALF_SPEED + }; - if (carEntry->flags.has(CarEntryFlag::hasSpinning)) + uint8_t speedModifier = FULL_SPEED; + + if (trackType == TrackElemType::leftQuarterTurn1Tile) { - spin_speed = std::clamp(spin_speed, kVehicleMinSpinSpeedWaterRide, kVehicleMaxSpinSpeedWaterRide); + speedModifier = (trackSubposition == VehicleTrackSubposition::goKartsLeftLane) ? HALF_SPEED : THREE_QUARTER_SPEED; + } + else if (trackType == TrackElemType::rightQuarterTurn1Tile) + { + speedModifier = (trackSubposition == VehicleTrackSubposition::goKartsRightLane) ? HALF_SPEED : THREE_QUARTER_SPEED; } - if (pitch != VehiclePitch::flat) + switch (speedModifier) + { + case HALF_SPEED: + return speed >> 1; + case THREE_QUARTER_SPEED: + return speed - (speed >> 2); + } + return speed; + } + + int32_t Vehicle::UpdateTrackMotionPoweredRideAcceleration( + const CarEntry* carEntry, uint32_t totalMass, const int32_t curAcceleration) + { + if (carEntry->flags.has(CarEntryFlag::isPoweredRideWithUnrestrictedGravity)) + { + if (velocity > (speed * 0x4000)) + { + // Same code as none powered rides + if (curAcceleration <= 0 && curAcceleration >= -500 && velocity <= 0.5_mph) + { + return curAcceleration + 400; + } + return curAcceleration; + } + } + uint8_t modifiedSpeed = modified_speed(GetTrackType(), TrackSubposition, speed); + int32_t poweredAcceleration = modifiedSpeed << 14; + int32_t quarterForce = (modifiedSpeed * totalMass) >> 2; + if (flags.has(VehicleFlag::poweredCarInReverse)) + { + poweredAcceleration = -poweredAcceleration; + } + poweredAcceleration -= velocity; + poweredAcceleration *= powered_acceleration << 1; + if (quarterForce != 0) + { + poweredAcceleration /= quarterForce; + } + + if (carEntry->flags.has(CarEntryFlag::isLift)) + { + poweredAcceleration *= 4; + } + + if (carEntry->flags.has(CarEntryFlag::isWaterRide)) { if (poweredAcceleration < 0) { - poweredAcceleration = 0; + poweredAcceleration >>= 4; } if (carEntry->flags.has(CarEntryFlag::hasSpinning)) { - // If the vehicle is on the up slope kill the spin speedModifier - if (pitch == VehiclePitch::up25) + spin_speed = std::clamp(spin_speed, kVehicleMinSpinSpeedWaterRide, kVehicleMaxSpinSpeedWaterRide); + } + + if (pitch != VehiclePitch::flat) + { + if (poweredAcceleration < 0) { - spin_speed = 0; + poweredAcceleration = 0; } + + if (carEntry->flags.has(CarEntryFlag::hasSpinning)) + { + // If the vehicle is on the up slope kill the spin speedModifier + if (pitch == VehiclePitch::up25) + { + spin_speed = 0; + } + } + return curAcceleration + poweredAcceleration; } - return curAcceleration + poweredAcceleration; - } - } - - if (std::abs(velocity) <= 1.0_mph) - { - return poweredAcceleration; - } - - return curAcceleration + poweredAcceleration; -} - -void Vehicle::UpdateTrackMotionPreUpdate( - Vehicle& car, const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry) -{ - if (carEntry->flags.has(CarEntryFlag::hasSwinging)) - { - car.UpdateSwingingCar(); - } - if (carEntry->flags.has(CarEntryFlag::hasSpinning)) - { - car.UpdateSpinningCar(); - } - if (carEntry->flags.hasAny(CarEntryFlag::hasVehicleAnimation, CarEntryFlag::hasRiderAnimation)) - { - car.UpdateAdditionalAnimation(); - } - car.acceleration = Geometry::getAccelerationFromPitch(car.pitch); - _vehicleUnkF64E10 = 1; - - if (!car.flags.has(VehicleFlag::moveSingleCar)) - { - car.remaining_distance += _vehicleVelocityF64E0C; - } - - car.sound2_flags &= ~VEHICLE_SOUND2_FLAGS_LIFT_HILL; - _vehicleCurPosition.x = car.x; - _vehicleCurPosition.y = car.y; - _vehicleCurPosition.z = car.z; - car.invalidate(); - - while (true) - { - if (car.remaining_distance < 0) - { - // Backward loop - if (car.UpdateTrackMotionBackwards(carEntry, curRide, rideEntry)) - { - break; - } - - if (car.remaining_distance < 0x368A) - { - break; - } - car.acceleration += Geometry::getAccelerationFromPitch(car.pitch); - _vehicleUnkF64E10++; - continue; - } - if (car.remaining_distance < 0x368A) - { - // Location found - return; - } - if (car.UpdateTrackMotionForwards(carEntry, curRide, rideEntry)) - { - break; } - if (car.remaining_distance >= 0) + if (std::abs(velocity) <= 1.0_mph) { - break; + return poweredAcceleration; + } + + return curAcceleration + poweredAcceleration; + } + + void Vehicle::UpdateTrackMotionPreUpdate( + Vehicle& car, const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry) + { + if (carEntry->flags.has(CarEntryFlag::hasSwinging)) + { + car.UpdateSwingingCar(); + } + if (carEntry->flags.has(CarEntryFlag::hasSpinning)) + { + car.UpdateSpinningCar(); + } + if (carEntry->flags.hasAny(CarEntryFlag::hasVehicleAnimation, CarEntryFlag::hasRiderAnimation)) + { + car.UpdateAdditionalAnimation(); } car.acceleration = Geometry::getAccelerationFromPitch(car.pitch); - _vehicleUnkF64E10++; - } - // Loc6DBF20 - car.moveTo(_vehicleCurPosition); -} + _vehicleUnkF64E10 = 1; -/** - * - * rct2: 0x006DAB4C - */ -int32_t Vehicle::UpdateTrackMotion(int32_t* outStation) -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return 0; - - const auto* rideEntry = GetRideEntry(); - const auto* carEntry = Entry(); - - if (carEntry == nullptr) - { - return 0; - } - - if (carEntry->flags.has(CarEntryFlag::isMiniGolf)) - { - return UpdateTrackMotionMiniGolf(outStation); - } - - _vehicleF64E2C = 0; - gCurrentVehicle = this; - _vehicleMotionTrackFlags = 0; - _vehicleStationIndex = StationIndex::GetNull(); - - UpdateTrackMotionUpStopCheck(); - CheckAndApplyBlockSectionStopSite(); - UpdateVelocity(); - - Vehicle* vehicle = this; - if (_vehicleVelocityF64E08 < 0 && !vehicle->flags.has(VehicleFlag::moveSingleCar)) - { - vehicle = vehicle->TrainTail(); - } - // This will be the front vehicle even when traveling - // backwards. - _vehicleFrontVehicle = vehicle; - - auto spriteId = vehicle->id; - while (!spriteId.IsNull()) - { - Vehicle* car = getGameState().entities.GetEntity(spriteId); - if (car == nullptr) + if (!car.flags.has(VehicleFlag::moveSingleCar)) { - break; - } - carEntry = car->Entry(); - if (carEntry != nullptr) - { - UpdateTrackMotionPreUpdate(*car, *curRide, *rideEntry, carEntry); + car.remaining_distance += _vehicleVelocityF64E0C; } - car->Sub6DBF3E(); + car.sound2_flags &= ~VEHICLE_SOUND2_FLAGS_LIFT_HILL; + _vehicleCurPosition.x = car.x; + _vehicleCurPosition.y = car.y; + _vehicleCurPosition.z = car.z; + car.invalidate(); - // Loc6DC0F7 - if (car->flags.has(VehicleFlag::onLiftHill)) + while (true) { - _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_ON_LIFT_HILL; - } - if (car->flags.has(VehicleFlag::moveSingleCar)) - { - if (outStation != nullptr) - *outStation = _vehicleStationIndex.ToUnderlying(); - return _vehicleMotionTrackFlags; - } - if (_vehicleVelocityF64E08 >= 0) - { - spriteId = car->next_vehicle_on_train; - } - else - { - if (car == gCurrentVehicle) + if (car.remaining_distance < 0) + { + // Backward loop + if (car.UpdateTrackMotionBackwards(carEntry, curRide, rideEntry)) + { + break; + } + + if (car.remaining_distance < 0x368A) + { + break; + } + car.acceleration += Geometry::getAccelerationFromPitch(car.pitch); + _vehicleUnkF64E10++; + continue; + } + if (car.remaining_distance < 0x368A) + { + // Location found + return; + } + if (car.UpdateTrackMotionForwards(carEntry, curRide, rideEntry)) { break; } - spriteId = car->prev_vehicle_on_ride; - } - } - // Loc6DC144 - vehicle = gCurrentVehicle; - carEntry = vehicle->Entry(); - // eax - int32_t totalAcceleration = 0; - // ebp - int32_t totalMass = 0; - // ebx - int32_t numVehicles = 0; - - for (; vehicle != nullptr; vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - numVehicles++; - totalMass += vehicle->mass; - totalAcceleration += vehicle->acceleration; - } - - vehicle = gCurrentVehicle; - int32_t newAcceleration = (totalAcceleration / numVehicles) * 21; - if (newAcceleration < 0) - { - newAcceleration += 511; - } - newAcceleration >>= 9; - - int32_t curAcceleration = newAcceleration; - curAcceleration -= vehicle->velocity / 4096; - curAcceleration -= GetAccelerationDecrease2(vehicle->velocity, totalMass); - - if (carEntry->flags.has(CarEntryFlag::isPowered)) - { - curAcceleration = vehicle->UpdateTrackMotionPoweredRideAcceleration(carEntry, totalMass, curAcceleration); - } - else if (curAcceleration <= 0 && curAcceleration >= -500) - { - // Probably moving slowly on a flat track piece, low rolling resistance and drag. - - if (vehicle->velocity <= 0.5_mph && vehicle->velocity >= 0) - { - // Vehicle is creeping forwards very slowly (less than ~2km/h), boost speed a bit. - curAcceleration += 400; - } - } - - if (vehicle->GetTrackType() == TrackElemType::waterSplash) - { - if (vehicle->track_progress >= 48 && vehicle->track_progress <= 128) - { - curAcceleration -= vehicle->velocity >> 6; - } - } - - if (rideEntry->flags.has(RideEntryFlag::coveredTrackIsWaterChannel)) - { - if (vehicle->IsHead()) - { - if (vehicle->IsOnCoveredTrack()) + if (car.remaining_distance >= 0) { - if (vehicle->velocity > 2.0_mph) + break; + } + car.acceleration = Geometry::getAccelerationFromPitch(car.pitch); + _vehicleUnkF64E10++; + } + // Loc6DBF20 + car.moveTo(_vehicleCurPosition); + } + + /** + * + * rct2: 0x006DAB4C + */ + int32_t Vehicle::UpdateTrackMotion(int32_t* outStation) + { + auto curRide = GetRide(); + if (curRide == nullptr) + return 0; + + const auto* rideEntry = GetRideEntry(); + const auto* carEntry = Entry(); + + if (carEntry == nullptr) + { + return 0; + } + + if (carEntry->flags.has(CarEntryFlag::isMiniGolf)) + { + return UpdateTrackMotionMiniGolf(outStation); + } + + _vehicleF64E2C = 0; + gCurrentVehicle = this; + _vehicleMotionTrackFlags = 0; + _vehicleStationIndex = StationIndex::GetNull(); + + UpdateTrackMotionUpStopCheck(); + CheckAndApplyBlockSectionStopSite(); + UpdateVelocity(); + + Vehicle* vehicle = this; + if (_vehicleVelocityF64E08 < 0 && !vehicle->flags.has(VehicleFlag::moveSingleCar)) + { + vehicle = vehicle->TrainTail(); + } + // This will be the front vehicle even when traveling + // backwards. + _vehicleFrontVehicle = vehicle; + + auto spriteId = vehicle->id; + while (!spriteId.IsNull()) + { + Vehicle* car = getGameState().entities.GetEntity(spriteId); + if (car == nullptr) + { + break; + } + carEntry = car->Entry(); + if (carEntry != nullptr) + { + UpdateTrackMotionPreUpdate(*car, *curRide, *rideEntry, carEntry); + } + + car->Sub6DBF3E(); + + // Loc6DC0F7 + if (car->flags.has(VehicleFlag::onLiftHill)) + { + _vehicleMotionTrackFlags |= VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_ON_LIFT_HILL; + } + if (car->flags.has(VehicleFlag::moveSingleCar)) + { + if (outStation != nullptr) + *outStation = _vehicleStationIndex.ToUnderlying(); + return _vehicleMotionTrackFlags; + } + if (_vehicleVelocityF64E08 >= 0) + { + spriteId = car->next_vehicle_on_train; + } + else + { + if (car == gCurrentVehicle) { - curAcceleration -= vehicle->velocity >> 6; + break; + } + spriteId = car->prev_vehicle_on_ride; + } + } + // Loc6DC144 + vehicle = gCurrentVehicle; + + carEntry = vehicle->Entry(); + // eax + int32_t totalAcceleration = 0; + // ebp + int32_t totalMass = 0; + // ebx + int32_t numVehicles = 0; + + for (; vehicle != nullptr; vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + { + numVehicles++; + totalMass += vehicle->mass; + totalAcceleration += vehicle->acceleration; + } + + vehicle = gCurrentVehicle; + int32_t newAcceleration = (totalAcceleration / numVehicles) * 21; + if (newAcceleration < 0) + { + newAcceleration += 511; + } + newAcceleration >>= 9; + + int32_t curAcceleration = newAcceleration; + curAcceleration -= vehicle->velocity / 4096; + curAcceleration -= GetAccelerationDecrease2(vehicle->velocity, totalMass); + + if (carEntry->flags.has(CarEntryFlag::isPowered)) + { + curAcceleration = vehicle->UpdateTrackMotionPoweredRideAcceleration(carEntry, totalMass, curAcceleration); + } + else if (curAcceleration <= 0 && curAcceleration >= -500) + { + // Probably moving slowly on a flat track piece, low rolling resistance and drag. + + if (vehicle->velocity <= 0.5_mph && vehicle->velocity >= 0) + { + // Vehicle is creeping forwards very slowly (less than ~2km/h), boost speed a bit. + curAcceleration += 400; + } + } + + if (vehicle->GetTrackType() == TrackElemType::waterSplash) + { + if (vehicle->track_progress >= 48 && vehicle->track_progress <= 128) + { + curAcceleration -= vehicle->velocity >> 6; + } + } + + if (rideEntry->flags.has(RideEntryFlag::coveredTrackIsWaterChannel)) + { + if (vehicle->IsHead()) + { + if (vehicle->IsOnCoveredTrack()) + { + if (vehicle->velocity > 2.0_mph) + { + curAcceleration -= vehicle->velocity >> 6; + } } } } + + vehicle->acceleration = curAcceleration; + + // hook_setreturnregisters(®s); + if (outStation != nullptr) + *outStation = _vehicleStationIndex.ToUnderlying(); + return _vehicleMotionTrackFlags; } - - vehicle->acceleration = curAcceleration; - - // hook_setreturnregisters(®s); - if (outStation != nullptr) - *outStation = _vehicleStationIndex.ToUnderlying(); - return _vehicleMotionTrackFlags; -} +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Vehicle.cpp b/src/openrct2/ride/Vehicle.cpp index e7e3a620f8..a27274e464 100644 --- a/src/openrct2/ride/Vehicle.cpp +++ b/src/openrct2/ride/Vehicle.cpp @@ -41,1517 +41,1523 @@ #include #include -using namespace OpenRCT2; -using namespace OpenRCT2::Audio; -using namespace OpenRCT2::TrackMetadata; -using namespace OpenRCT2::RideVehicle; - -constexpr int16_t kVehicleMaxSpinSpeedForStopping = 700; -constexpr int16_t kVehicleStoppingSpinSpeed = 600; - -Vehicle* gCurrentVehicle; - -Breakdown _vehicleBreakdown; -StationIndex _vehicleStationIndex; -uint32_t _vehicleMotionTrackFlags; -int32_t _vehicleVelocityF64E08; -int32_t _vehicleVelocityF64E0C; -int32_t _vehicleUnkF64E10; -uint8_t _vehicleF64E2C; -Vehicle* _vehicleFrontVehicle; -CoordsXYZ _vehicleCurPosition; - -PitchAndRoll PitchAndRollStart(bool useInvertedSprites, TileElement* tileElement) +namespace OpenRCT2 { - auto trackType = tileElement->asTrack()->GetTrackType(); - const auto& ted = GetTrackElementDescriptor(trackType); - return PitchAndRoll{ ted.definition.pitchStart, TrackGetActualBank3(useInvertedSprites, tileElement) }; -} + using namespace OpenRCT2::Audio; + using namespace OpenRCT2::TrackMetadata; + using namespace OpenRCT2::RideVehicle; -int32_t GetAccelerationDecrease2(const int32_t velocity, const int32_t totalMass) -{ - int32_t accelerationDecrease2 = velocity >> 8; - accelerationDecrease2 *= accelerationDecrease2; - if (velocity < 0) + constexpr int16_t kVehicleMaxSpinSpeedForStopping = 700; + constexpr int16_t kVehicleStoppingSpinSpeed = 600; + + Vehicle* gCurrentVehicle; + + Breakdown _vehicleBreakdown; + StationIndex _vehicleStationIndex; + uint32_t _vehicleMotionTrackFlags; + int32_t _vehicleVelocityF64E08; + int32_t _vehicleVelocityF64E0C; + int32_t _vehicleUnkF64E10; + uint8_t _vehicleF64E2C; + Vehicle* _vehicleFrontVehicle; + CoordsXYZ _vehicleCurPosition; + + PitchAndRoll PitchAndRollStart(bool useInvertedSprites, TileElement* tileElement) { - accelerationDecrease2 = -accelerationDecrease2; - } - accelerationDecrease2 >>= 4; - // OpenRCT2: vehicles from different track types can have 0 mass. - if (totalMass != 0) - { - return accelerationDecrease2 / totalMass; + auto trackType = tileElement->asTrack()->GetTrackType(); + const auto& ted = GetTrackElementDescriptor(trackType); + return PitchAndRoll{ ted.definition.pitchStart, TrackGetActualBank3(useInvertedSprites, tileElement) }; } - return accelerationDecrease2; -} - -template<> -bool EntityBase::is() const -{ - return type == EntityType::vehicle; -} - -static bool vehicle_move_info_valid( - VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction, int32_t offset) -{ - uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); - - if (trackSubposition >= VehicleTrackSubposition{ std::size(gTrackVehicleInfo) }) + int32_t GetAccelerationDecrease2(const int32_t velocity, const int32_t totalMass) { - return false; + int32_t accelerationDecrease2 = velocity >> 8; + accelerationDecrease2 *= accelerationDecrease2; + if (velocity < 0) + { + accelerationDecrease2 = -accelerationDecrease2; + } + accelerationDecrease2 >>= 4; + // OpenRCT2: vehicles from different track types can have 0 mass. + if (totalMass != 0) + { + return accelerationDecrease2 / totalMass; + } + + return accelerationDecrease2; } - int32_t size = 0; - switch (trackSubposition) + + template<> + bool EntityBase::is() const { - case VehicleTrackSubposition::standard: - size = VehicleTrackSubpositionSizeDefault; - break; - case VehicleTrackSubposition::chairliftGoingOut: - size = 692; - break; - case VehicleTrackSubposition::chairliftGoingBack: - case VehicleTrackSubposition::chairliftEndBullwheel: - case VehicleTrackSubposition::chairliftStartBullwheel: - size = 404; - break; - case VehicleTrackSubposition::goKartsLeftLane: - case VehicleTrackSubposition::goKartsRightLane: - size = 1204; - break; - case VehicleTrackSubposition::goKartsMovingToRightLane: - case VehicleTrackSubposition::goKartsMovingToLeftLane: - size = 568; - break; - case VehicleTrackSubposition::miniGolfPathA9: // VehicleTrackSubposition::miniGolfStart9 - case VehicleTrackSubposition::miniGolfBallPathA10: - case VehicleTrackSubposition::miniGolfPathB11: - case VehicleTrackSubposition::miniGolfBallPathB12: - case VehicleTrackSubposition::miniGolfPathC13: - case VehicleTrackSubposition::miniGolfBallPathC14: - size = 824; - break; - case VehicleTrackSubposition::reverserRCFrontBogie: - case VehicleTrackSubposition::reverserRCRearBogie: - size = 868; - break; - default: - break; + return type == EntityType::vehicle; } - if (typeAndDirection >= size) + + static bool vehicle_move_info_valid( + VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction, int32_t offset) { - return false; - } - if (offset >= gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->size) - { - return false; - } - return true; -} + uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); -static const VehicleInfo* vehicle_get_move_info( - VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction, int32_t offset) -{ - uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); - - if (!vehicle_move_info_valid(trackSubposition, type, direction, offset)) - { - static constexpr VehicleInfo zero = {}; - return &zero; - } - return &gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->info[offset]; -} - -const VehicleInfo* Vehicle::GetMoveInfo() const -{ - return vehicle_get_move_info(TrackSubposition, GetTrackType(), GetTrackDirection(), track_progress); -} - -uint16_t VehicleGetMoveInfoSize(VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction) -{ - uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); - - if (!vehicle_move_info_valid(trackSubposition, type, direction, 0)) - { - return 0; - } - return gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->size; -} - -uint16_t Vehicle::GetTrackProgress() const -{ - return VehicleGetMoveInfoSize(TrackSubposition, GetTrackType(), GetTrackDirection()); -} - -void Vehicle::ApplyMass(int16_t appliedMass) -{ - mass = std::clamp(mass + appliedMass, 1, std::numeric_limits::max()); -} - -void Vehicle::MoveRelativeDistance(int32_t distance) -{ - remaining_distance += distance; - - flags.set(VehicleFlag::moveSingleCar, VehicleFlag::collisionDisabled); - UpdateTrackMotion(nullptr); - flags.unset(VehicleFlag::moveSingleCar, VehicleFlag::collisionDisabled); -} - -void Vehicle::UpdateTrackChange() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - const auto moveInfo = GetMoveInfo(); - if (moveInfo == nullptr || moveInfo->isInvalid()) - return; - - _vehicleCurPosition = TrackLocation - + CoordsXYZ{ moveInfo->x, moveInfo->y, moveInfo->z + GetRideTypeDescriptor(curRide->type).Heights.VehicleZOffset }; - orientation = moveInfo->yaw; - roll = moveInfo->roll; - pitch = moveInfo->pitch; - moveTo(_vehicleCurPosition); -} - -Vehicle* TryGetVehicle(EntityId spriteIndex) -{ - return getGameState().entities.TryGetEntity(spriteIndex); -} - -/** - * - * rct2: 0x006D4204 - */ -void VehicleUpdateAll() -{ - PROFILED_FUNCTION(); - - if (gLegacyScene == LegacyScene::scenarioEditor) - return; - - if (gLegacyScene == LegacyScene::trackDesigner && getGameState().editorStep != Editor::Step::rollerCoasterDesigner) - return; - - for (auto vehicle : TrainManager::View()) - { - vehicle->Update(); - } -} - -/** - * - * rct2: 0x006D6956 - * @returns true when all closed - */ -bool Vehicle::CloseRestraints() -{ - auto curRide = GetRide(); - if (curRide == nullptr) + if (trackSubposition >= VehicleTrackSubposition{ std::size(gTrackVehicleInfo) }) + { + return false; + } + int32_t size = 0; + switch (trackSubposition) + { + case VehicleTrackSubposition::standard: + size = VehicleTrackSubpositionSizeDefault; + break; + case VehicleTrackSubposition::chairliftGoingOut: + size = 692; + break; + case VehicleTrackSubposition::chairliftGoingBack: + case VehicleTrackSubposition::chairliftEndBullwheel: + case VehicleTrackSubposition::chairliftStartBullwheel: + size = 404; + break; + case VehicleTrackSubposition::goKartsLeftLane: + case VehicleTrackSubposition::goKartsRightLane: + size = 1204; + break; + case VehicleTrackSubposition::goKartsMovingToRightLane: + case VehicleTrackSubposition::goKartsMovingToLeftLane: + size = 568; + break; + case VehicleTrackSubposition::miniGolfPathA9: // VehicleTrackSubposition::miniGolfStart9 + case VehicleTrackSubposition::miniGolfBallPathA10: + case VehicleTrackSubposition::miniGolfPathB11: + case VehicleTrackSubposition::miniGolfBallPathB12: + case VehicleTrackSubposition::miniGolfPathC13: + case VehicleTrackSubposition::miniGolfBallPathC14: + size = 824; + break; + case VehicleTrackSubposition::reverserRCFrontBogie: + case VehicleTrackSubposition::reverserRCRearBogie: + size = 868; + break; + default: + break; + } + if (typeAndDirection >= size) + { + return false; + } + if (offset >= gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->size) + { + return false; + } return true; - - bool restraintsClosed = true; - for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - if (vehicle->flags.has(VehicleFlag::carIsBroken) && vehicle->restraints_position != 0 - && (curRide->breakdownReasonPending == Breakdown::restraintsStuckOpen - || curRide->breakdownReasonPending == Breakdown::doorsStuckOpen)) - { - if (!curRide->flags.has(RideFlag::brokenDown)) - { - curRide->flags.set(RideFlag::brokenDown); - - RideBreakdownAddNewsItem(*curRide); - - curRide->windowInvalidateFlags.set( - RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); - - curRide->mechanicStatus = MechanicStatus::calling; - - Vehicle* broken_vehicle = getGameState().entities.GetEntity(curRide->vehicles[curRide->brokenTrain]); - if (broken_vehicle != nullptr) - { - curRide->inspectionStation = broken_vehicle->current_station; - } - curRide->breakdownReason = curRide->breakdownReasonPending; - } - } - else - { - vehicle->restraints_position = std::max(vehicle->restraints_position - 20, 0); - if (vehicle->restraints_position == 0) - { - continue; - } - } - vehicle->invalidate(); - restraintsClosed = false; } - return restraintsClosed; -} - -/** - * - * rct2: 0x006D6A2C - * @returns true when all open - */ -bool Vehicle::OpenRestraints() -{ - int32_t restraintsOpen = true; - for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + static const VehicleInfo* vehicle_get_move_info( + VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction, int32_t offset) { - vehicle->SwingPosition = 0; - vehicle->SwingSpeed = 0; - vehicle->SwingSprite = 0; + uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); - auto curRide = vehicle->GetRide(); + if (!vehicle_move_info_valid(trackSubposition, type, direction, offset)) + { + static constexpr VehicleInfo zero = {}; + return &zero; + } + return &gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->info[offset]; + } + + const VehicleInfo* Vehicle::GetMoveInfo() const + { + return vehicle_get_move_info(TrackSubposition, GetTrackType(), GetTrackDirection(), track_progress); + } + + uint16_t VehicleGetMoveInfoSize(VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction) + { + uint16_t typeAndDirection = (EnumValue(type) << 2) | (direction & 3); + + if (!vehicle_move_info_valid(trackSubposition, type, direction, 0)) + { + return 0; + } + return gTrackVehicleInfo[EnumValue(trackSubposition)][typeAndDirection]->size; + } + + uint16_t Vehicle::GetTrackProgress() const + { + return VehicleGetMoveInfoSize(TrackSubposition, GetTrackType(), GetTrackDirection()); + } + + void Vehicle::ApplyMass(int16_t appliedMass) + { + mass = std::clamp(mass + appliedMass, 1, std::numeric_limits::max()); + } + + void Vehicle::MoveRelativeDistance(int32_t distance) + { + remaining_distance += distance; + + flags.set(VehicleFlag::moveSingleCar, VehicleFlag::collisionDisabled); + UpdateTrackMotion(nullptr); + flags.unset(VehicleFlag::moveSingleCar, VehicleFlag::collisionDisabled); + } + + void Vehicle::UpdateTrackChange() + { + auto curRide = GetRide(); if (curRide == nullptr) - continue; + return; - auto rideEntry = vehicle->GetRideEntry(); - if (rideEntry == nullptr) + const auto moveInfo = GetMoveInfo(); + if (moveInfo == nullptr || moveInfo->isInvalid()) + return; + + _vehicleCurPosition = TrackLocation + + CoordsXYZ{ moveInfo->x, moveInfo->y, moveInfo->z + GetRideTypeDescriptor(curRide->type).Heights.VehicleZOffset }; + orientation = moveInfo->yaw; + roll = moveInfo->roll; + pitch = moveInfo->pitch; + moveTo(_vehicleCurPosition); + } + + Vehicle* TryGetVehicle(EntityId spriteIndex) + { + return getGameState().entities.TryGetEntity(spriteIndex); + } + + /** + * + * rct2: 0x006D4204 + */ + void VehicleUpdateAll() + { + PROFILED_FUNCTION(); + + if (gLegacyScene == LegacyScene::scenarioEditor) + return; + + if (gLegacyScene == LegacyScene::trackDesigner && getGameState().editorStep != Editor::Step::rollerCoasterDesigner) + return; + + for (auto vehicle : TrainManager::View()) { - continue; + vehicle->Update(); } + } - const auto& carEntry = rideEntry->Cars[vehicle->vehicle_type]; + /** + * + * rct2: 0x006D6956 + * @returns true when all closed + */ + bool Vehicle::CloseRestraints() + { + auto curRide = GetRide(); + if (curRide == nullptr) + return true; - if (carEntry.flags.has(CarEntryFlag::hasSpinning)) + bool restraintsClosed = true; + for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) { - // If the vehicle is a spinner it must be spinning slow - // For vehicles without additional frames there are 4 rotations it can unload from - // For vehicles with additional frames it must be facing forward - if (abs(vehicle->spin_speed) <= kVehicleMaxSpinSpeedForStopping && !(vehicle->spin_sprite & 0x30) - && (!carEntry.flags.has(CarEntryFlag::hasSpinningCombinedWithNonSpinning) || !(vehicle->spin_sprite & 0xF8))) + if (vehicle->flags.has(VehicleFlag::carIsBroken) && vehicle->restraints_position != 0 + && (curRide->breakdownReasonPending == Breakdown::restraintsStuckOpen + || curRide->breakdownReasonPending == Breakdown::doorsStuckOpen)) { - vehicle->spin_speed = 0; + if (!curRide->flags.has(RideFlag::brokenDown)) + { + curRide->flags.set(RideFlag::brokenDown); + + RideBreakdownAddNewsItem(*curRide); + + curRide->windowInvalidateFlags.set( + RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); + + curRide->mechanicStatus = MechanicStatus::calling; + + Vehicle* broken_vehicle = getGameState().entities.GetEntity( + curRide->vehicles[curRide->brokenTrain]); + if (broken_vehicle != nullptr) + { + curRide->inspectionStation = broken_vehicle->current_station; + } + curRide->breakdownReason = curRide->breakdownReasonPending; + } } else { + vehicle->restraints_position = std::max(vehicle->restraints_position - 20, 0); + if (vehicle->restraints_position == 0) + { + continue; + } + } + vehicle->invalidate(); + restraintsClosed = false; + } + + return restraintsClosed; + } + + /** + * + * rct2: 0x006D6A2C + * @returns true when all open + */ + bool Vehicle::OpenRestraints() + { + int32_t restraintsOpen = true; + for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + { + vehicle->SwingPosition = 0; + vehicle->SwingSpeed = 0; + vehicle->SwingSprite = 0; + + auto curRide = vehicle->GetRide(); + if (curRide == nullptr) + continue; + + auto rideEntry = vehicle->GetRideEntry(); + if (rideEntry == nullptr) + { + continue; + } + + const auto& carEntry = rideEntry->Cars[vehicle->vehicle_type]; + + if (carEntry.flags.has(CarEntryFlag::hasSpinning)) + { + // If the vehicle is a spinner it must be spinning slow + // For vehicles without additional frames there are 4 rotations it can unload from + // For vehicles with additional frames it must be facing forward + if (abs(vehicle->spin_speed) <= kVehicleMaxSpinSpeedForStopping && !(vehicle->spin_sprite & 0x30) + && (!carEntry.flags.has(CarEntryFlag::hasSpinningCombinedWithNonSpinning) + || !(vehicle->spin_sprite & 0xF8))) + { + vehicle->spin_speed = 0; + } + else + { + restraintsOpen = false; + + if (abs(vehicle->spin_speed) < kVehicleStoppingSpinSpeed) + { + // Note will look odd if spinning right. + vehicle->spin_speed = kVehicleStoppingSpinSpeed; + } + int16_t value = vehicle->spin_speed / 256; + vehicle->spin_sprite += value; + vehicle->spin_speed -= value; + + vehicle->invalidate(); + continue; + } + } + if (carEntry.animation == CarEntryAnimation::observationTower && vehicle->animation_frame != 0) + { + if (vehicle->animationState <= 0xCCCC) + { + vehicle->animationState += carEntry.AnimationSpeed; + } + else + { + vehicle->animationState = 0; + vehicle->animation_frame++; + vehicle->animation_frame %= carEntry.AnimationFrames; + vehicle->invalidate(); + } restraintsOpen = false; - - if (abs(vehicle->spin_speed) < kVehicleStoppingSpinSpeed) - { - // Note will look odd if spinning right. - vehicle->spin_speed = kVehicleStoppingSpinSpeed; - } - int16_t value = vehicle->spin_speed / 256; - vehicle->spin_sprite += value; - vehicle->spin_speed -= value; - - vehicle->invalidate(); continue; } - } - if (carEntry.animation == CarEntryAnimation::observationTower && vehicle->animation_frame != 0) - { - if (vehicle->animationState <= 0xCCCC) + if (carEntry.animation == CarEntryAnimation::animalFlying + && (vehicle->animation_frame != 0 || vehicle->animationState > 0)) { - vehicle->animationState += carEntry.AnimationSpeed; + vehicle->UpdateAnimationAnimalFlying(); + restraintsOpen = false; + continue; + } + + if (vehicle->flags.has(VehicleFlag::carIsBroken) && vehicle->restraints_position != 0xFF + && (curRide->breakdownReasonPending == Breakdown::restraintsStuckClosed + || curRide->breakdownReasonPending == Breakdown::doorsStuckClosed)) + { + if (!curRide->flags.has(RideFlag::brokenDown)) + { + curRide->flags.set(RideFlag::brokenDown); + + RideBreakdownAddNewsItem(*curRide); + + curRide->windowInvalidateFlags.set( + RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); + + curRide->mechanicStatus = MechanicStatus::calling; + + Vehicle* broken_vehicle = getGameState().entities.GetEntity( + curRide->vehicles[curRide->brokenTrain]); + if (broken_vehicle != nullptr) + { + curRide->inspectionStation = broken_vehicle->current_station; + } + curRide->breakdownReason = curRide->breakdownReasonPending; + } } else { - vehicle->animationState = 0; - vehicle->animation_frame++; - vehicle->animation_frame %= carEntry.AnimationFrames; - vehicle->invalidate(); - } - restraintsOpen = false; - continue; - } - if (carEntry.animation == CarEntryAnimation::animalFlying - && (vehicle->animation_frame != 0 || vehicle->animationState > 0)) - { - vehicle->UpdateAnimationAnimalFlying(); - restraintsOpen = false; - continue; - } - - if (vehicle->flags.has(VehicleFlag::carIsBroken) && vehicle->restraints_position != 0xFF - && (curRide->breakdownReasonPending == Breakdown::restraintsStuckClosed - || curRide->breakdownReasonPending == Breakdown::doorsStuckClosed)) - { - if (!curRide->flags.has(RideFlag::brokenDown)) - { - curRide->flags.set(RideFlag::brokenDown); - - RideBreakdownAddNewsItem(*curRide); - - curRide->windowInvalidateFlags.set( - RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); - - curRide->mechanicStatus = MechanicStatus::calling; - - Vehicle* broken_vehicle = getGameState().entities.GetEntity(curRide->vehicles[curRide->brokenTrain]); - if (broken_vehicle != nullptr) + if (vehicle->restraints_position + 20 > 0xFF) { - curRide->inspectionStation = broken_vehicle->current_station; + vehicle->restraints_position = 255; + continue; } - curRide->breakdownReason = curRide->breakdownReasonPending; + vehicle->restraints_position += 20; } + vehicle->invalidate(); + restraintsOpen = false; } - else + + return restraintsOpen; + } + + void RideUpdateMeasurementsSpecialElements_Default(Ride& ride, const TrackElemType trackType) + { + const auto& ted = GetTrackElementDescriptor(trackType); + if (ted.flags.has(TrackElementFlag::normalToInversion)) { - if (vehicle->restraints_position + 20 > 0xFF) + if (ride.numInversions < Limits::kMaxInversions) + ride.numInversions++; + } + } + + void RideUpdateMeasurementsSpecialElements_WaterCoaster(Ride& ride, const TrackElemType trackType) + { + if (trackType >= TrackElemType::flatCovered && trackType <= TrackElemType::rightQuarterTurn3TilesCovered) + { + ride.specialTrackElements.set(SpecialElement::splash); + } + } + + /** + * + * rct2: 0x006D6D1F + */ + void Vehicle::UpdateMeasurements() + { + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + if (status == Status::travellingBoat) + { + curRide->flags.set(RideFlag::tested, RideFlag::noRawStats); + curRide->flags.unset(RideFlag::testInProgress); + flags.unset(VehicleFlag::testing); + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, ride.ToUnderlying()); + return; + } + + if (curRide->currentTestStation.IsNull()) + return; + + const auto& currentStation = curRide->getStation(curRide->currentTestStation); + if (!currentStation.Entrance.IsNull()) + { + uint8_t test_segment = curRide->currentTestSegment; + StationIndex stationIndex = StationIndex::FromUnderlying(test_segment); + auto& stationForTestSegment = curRide->getStation(stationIndex); + + curRide->averageSpeedTestTimeout++; + if (curRide->averageSpeedTestTimeout >= 32) + curRide->averageSpeedTestTimeout = 0; + + int32_t absVelocity = abs(velocity); + if (absVelocity > curRide->maxSpeed) { - vehicle->restraints_position = 255; - continue; + curRide->maxSpeed = absVelocity; } - vehicle->restraints_position += 20; - } - vehicle->invalidate(); - restraintsOpen = false; - } - return restraintsOpen; -} - -void RideUpdateMeasurementsSpecialElements_Default(Ride& ride, const TrackElemType trackType) -{ - const auto& ted = GetTrackElementDescriptor(trackType); - if (ted.flags.has(TrackElementFlag::normalToInversion)) - { - if (ride.numInversions < Limits::kMaxInversions) - ride.numInversions++; - } -} - -void RideUpdateMeasurementsSpecialElements_WaterCoaster(Ride& ride, const TrackElemType trackType) -{ - if (trackType >= TrackElemType::flatCovered && trackType <= TrackElemType::rightQuarterTurn3TilesCovered) - { - ride.specialTrackElements.set(SpecialElement::splash); - } -} - -/** - * - * rct2: 0x006D6D1F - */ -void Vehicle::UpdateMeasurements() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - if (status == Status::travellingBoat) - { - curRide->flags.set(RideFlag::tested, RideFlag::noRawStats); - curRide->flags.unset(RideFlag::testInProgress); - flags.unset(VehicleFlag::testing); - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, ride.ToUnderlying()); - return; - } - - if (curRide->currentTestStation.IsNull()) - return; - - const auto& currentStation = curRide->getStation(curRide->currentTestStation); - if (!currentStation.Entrance.IsNull()) - { - uint8_t test_segment = curRide->currentTestSegment; - StationIndex stationIndex = StationIndex::FromUnderlying(test_segment); - auto& stationForTestSegment = curRide->getStation(stationIndex); - - curRide->averageSpeedTestTimeout++; - if (curRide->averageSpeedTestTimeout >= 32) - curRide->averageSpeedTestTimeout = 0; - - int32_t absVelocity = abs(velocity); - if (absVelocity > curRide->maxSpeed) - { - curRide->maxSpeed = absVelocity; - } - - if (curRide->averageSpeedTestTimeout == 0 && absVelocity > 0) - { - curRide->averageSpeed = AddClamp(curRide->averageSpeed, absVelocity); - stationForTestSegment.SegmentTime++; - } - - int32_t distance = abs(((velocity + acceleration) >> 10) * 42); - if (NumLaps == 0) - { - stationForTestSegment.SegmentLength = AddClamp(stationForTestSegment.SegmentLength, distance); - } - - if (curRide->getRideTypeDescriptor().flags.has(RtdFlag::hasGForces)) - { - auto gForces = GetGForces(); - gForces.verticalG += curRide->previousVerticalG; - gForces.lateralG += curRide->previousLateralG; - gForces.verticalG /= 2; - gForces.lateralG /= 2; - - curRide->previousVerticalG = gForces.verticalG; - curRide->previousLateralG = gForces.lateralG; - if (gForces.verticalG <= 0) + if (curRide->averageSpeedTestTimeout == 0 && absVelocity > 0) { - curRide->totalAirTime++; + curRide->averageSpeed = AddClamp(curRide->averageSpeed, absVelocity); + stationForTestSegment.SegmentTime++; } - if (gForces.verticalG > curRide->maxPositiveVerticalG) - curRide->maxPositiveVerticalG = gForces.verticalG; + int32_t distance = abs(((velocity + acceleration) >> 10) * 42); + if (NumLaps == 0) + { + stationForTestSegment.SegmentLength = AddClamp(stationForTestSegment.SegmentLength, distance); + } - if (gForces.verticalG < curRide->maxNegativeVerticalG) - curRide->maxNegativeVerticalG = gForces.verticalG; + if (curRide->getRideTypeDescriptor().flags.has(RtdFlag::hasGForces)) + { + auto gForces = GetGForces(); + gForces.verticalG += curRide->previousVerticalG; + gForces.lateralG += curRide->previousLateralG; + gForces.verticalG /= 2; + gForces.lateralG /= 2; - gForces.lateralG = std::abs(gForces.lateralG); - curRide->maxLateralG = std::max(curRide->maxLateralG, static_cast(gForces.lateralG)); + curRide->previousVerticalG = gForces.verticalG; + curRide->previousLateralG = gForces.lateralG; + if (gForces.verticalG <= 0) + { + curRide->totalAirTime++; + } + + if (gForces.verticalG > curRide->maxPositiveVerticalG) + curRide->maxPositiveVerticalG = gForces.verticalG; + + if (gForces.verticalG < curRide->maxNegativeVerticalG) + curRide->maxNegativeVerticalG = gForces.verticalG; + + gForces.lateralG = std::abs(gForces.lateralG); + curRide->maxLateralG = std::max(curRide->maxLateralG, static_cast(gForces.lateralG)); + } } - } - // If we have already evaluated this track piece skip to next section - TileCoordsXYZ curTrackLoc{ TrackLocation }; - if (curTrackLoc != curRide->curTestTrackLocation) - { - curRide->curTestTrackLocation = curTrackLoc; + // If we have already evaluated this track piece skip to next section + TileCoordsXYZ curTrackLoc{ TrackLocation }; + if (curTrackLoc != curRide->curTestTrackLocation) + { + curRide->curTestTrackLocation = curTrackLoc; + + if (currentStation.Entrance.IsNull()) + return; + + auto trackElemType = GetTrackType(); + if (trackElemType == TrackElemType::poweredLift || flags.has(VehicleFlag::onLiftHill)) + { + if (!curRide->testingFlags.has(RideTestingFlag::poweredLift)) + { + curRide->testingFlags.set(RideTestingFlag::poweredLift); + if (curRide->numPoweredLifts < Limits::kRideMaxNumPoweredLiftsCount) + curRide->numPoweredLifts++; + } + } + else + { + curRide->testingFlags.unset(RideTestingFlag::poweredLift); + } + + const auto& rtd = curRide->getRideTypeDescriptor(); + rtd.UpdateMeasurementsSpecialElements(*curRide, trackElemType); + + switch (trackElemType) + { + case TrackElemType::rapids: + curRide->specialTrackElements.set(SpecialElement::rapids); + break; + case TrackElemType::spinningTunnel: + curRide->specialTrackElements.set(SpecialElement::spinningTunnel); + break; + case TrackElemType::waterfall: + curRide->specialTrackElements.set(SpecialElement::waterfall); + break; + case TrackElemType::logFlumeReverser: + curRide->specialTrackElements.set(SpecialElement::reverser); + break; + case TrackElemType::whirlpool: + curRide->specialTrackElements.set(SpecialElement::whirlpool); + break; + case TrackElemType::waterSplash: + if (velocity >= 11.0_mph) + { + curRide->specialTrackElements.set(SpecialElement::splash); + } + break; + default: + break; + } + + const auto& ted = GetTrackElementDescriptor(trackElemType); + auto testingFlags = curRide->testingFlags; + if (testingFlags.has(RideTestingFlag::turnLeft) && ted.flags.has(TrackElementFlag::turnLeft)) + { + // 0x800 as this is masked to kCurrentTurnCountMask + curRide->turnCountDefault += 0x800; + } + else if (testingFlags.has(RideTestingFlag::turnRight) && ted.flags.has(TrackElementFlag::turnRight)) + { + // 0x800 as this is masked to kCurrentTurnCountMask + curRide->turnCountDefault += 0x800; + } + else if (testingFlags.has(RideTestingFlag::turnRight) || testingFlags.has(RideTestingFlag::turnLeft)) + { + curRide->testingFlags.unset( + RideTestingFlag::turnLeft, RideTestingFlag::turnRight, RideTestingFlag::turnBanked, + RideTestingFlag::turnSloped); + + uint8_t turnType = 1; + if (!testingFlags.has(RideTestingFlag::turnBanked)) + { + turnType = 2; + if (!testingFlags.has(RideTestingFlag::turnSloped)) + { + turnType = 0; + } + } + switch (curRide->turnCountDefault >> 11) + { + case 0: + IncrementTurnCount1Element(*curRide, turnType); + break; + case 1: + IncrementTurnCount2Elements(*curRide, turnType); + break; + case 2: + IncrementTurnCount3Elements(*curRide, turnType); + break; + default: + IncrementTurnCount4PlusElements(*curRide, turnType); + break; + } + } + else + { + if (ted.flags.has(TrackElementFlag::turnLeft)) + { + curRide->testingFlags.set(RideTestingFlag::turnLeft); + curRide->turnCountDefault &= ~kCurrentTurnCountMask; + + if (ted.flags.has(TrackElementFlag::turnBanked)) + { + curRide->testingFlags.set(RideTestingFlag::turnBanked); + } + if (ted.flags.has(TrackElementFlag::turnSloped)) + { + curRide->testingFlags.set(RideTestingFlag::turnSloped); + } + } + + if (ted.flags.has(TrackElementFlag::turnRight)) + { + curRide->testingFlags.set(RideTestingFlag::turnRight); + curRide->turnCountDefault &= ~kCurrentTurnCountMask; + + if (ted.flags.has(TrackElementFlag::turnBanked)) + { + curRide->testingFlags.set(RideTestingFlag::turnBanked); + } + if (ted.flags.has(TrackElementFlag::turnSloped)) + { + curRide->testingFlags.set(RideTestingFlag::turnSloped); + } + } + } + + if (testingFlags.has(RideTestingFlag::dropDown)) + { + if (velocity < 0 || !ted.flags.has(TrackElementFlag::down)) + { + curRide->testingFlags.unset(RideTestingFlag::dropDown); + + int16_t curZ = z / kCoordsZStep - curRide->startDropHeight; + if (curZ < 0) + { + curZ = abs(curZ); + if (curZ > curRide->highestDropHeight) + { + curRide->highestDropHeight = static_cast(curZ); + } + } + } + } + else if (ted.flags.has(TrackElementFlag::down) && velocity >= 0) + { + curRide->testingFlags.unset(RideTestingFlag::dropUp); + curRide->testingFlags.set(RideTestingFlag::dropDown); + + if (curRide->numDrops < Limits::kRideMaxDropsCount) + curRide->numDrops++; + + curRide->startDropHeight = z / kCoordsZStep; + testingFlags.unset(RideTestingFlag::dropUp); + } + + if (testingFlags.has(RideTestingFlag::dropUp)) + { + if (velocity > 0 || !ted.flags.has(TrackElementFlag::up)) + { + curRide->testingFlags.unset(RideTestingFlag::dropUp); + + int16_t curZ = z / kCoordsZStep - curRide->startDropHeight; + if (curZ < 0) + { + curZ = abs(curZ); + if (curZ > curRide->highestDropHeight) + { + curRide->highestDropHeight = static_cast(curZ); + } + } + } + } + else if (ted.flags.has(TrackElementFlag::up) && velocity <= 0) + { + curRide->testingFlags.unset(RideTestingFlag::dropDown); + curRide->testingFlags.set(RideTestingFlag::dropUp); + + if (curRide->numDrops < Limits::kRideMaxDropsCount) + curRide->numDrops++; + + curRide->startDropHeight = z / kCoordsZStep; + } + + if (ted.flags.has(TrackElementFlag::helix)) + { + if (curRide->numHelices < Limits::kMaxHelices) + curRide->numHelices++; + } + } if (currentStation.Entrance.IsNull()) return; - auto trackElemType = GetTrackType(); - if (trackElemType == TrackElemType::poweredLift || flags.has(VehicleFlag::onLiftHill)) + if (x == kLocationNull) { - if (!curRide->testingFlags.has(RideTestingFlag::poweredLift)) + curRide->testingFlags.unset(RideTestingFlag::sheltered); + return; + } + + auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); + // If vehicle above ground. + if (surfaceElement != nullptr && surfaceElement->getBaseZ() <= z) + { + if (!TrackGetIsSheltered(CoordsXYZ{ x, y, z })) { - curRide->testingFlags.set(RideTestingFlag::poweredLift); - if (curRide->numPoweredLifts < Limits::kRideMaxNumPoweredLiftsCount) - curRide->numPoweredLifts++; + curRide->testingFlags.unset(RideTestingFlag::sheltered); + return; } } - else + + if (!curRide->testingFlags.has(RideTestingFlag::sheltered)) { - curRide->testingFlags.unset(RideTestingFlag::poweredLift); + curRide->testingFlags.set(RideTestingFlag::sheltered); + + curRide->increaseNumShelteredSections(); + + if (pitch != VehiclePitch::flat) + { + curRide->numShelteredSections |= ShelteredSectionsBits::kRotatingWhileSheltered; + } + + if (roll != VehicleRoll::unbanked) + { + curRide->numShelteredSections |= ShelteredSectionsBits::kBankingWhileSheltered; + } } - const auto& rtd = curRide->getRideTypeDescriptor(); - rtd.UpdateMeasurementsSpecialElements(*curRide, trackElemType); + int32_t distance = ((velocity + acceleration) >> 10) * 42; + if (distance < 0) + return; - switch (trackElemType) + curRide->shelteredLength = AddClamp(curRide->shelteredLength, distance); + } + + /** + * + * rct2: 0x006D77F2 + */ + void Vehicle::Update() + { + if (IsCableLift()) { - case TrackElemType::rapids: - curRide->specialTrackElements.set(SpecialElement::rapids); - break; - case TrackElemType::spinningTunnel: - curRide->specialTrackElements.set(SpecialElement::spinningTunnel); - break; - case TrackElemType::waterfall: - curRide->specialTrackElements.set(SpecialElement::waterfall); - break; - case TrackElemType::logFlumeReverser: - curRide->specialTrackElements.set(SpecialElement::reverser); - break; - case TrackElemType::whirlpool: - curRide->specialTrackElements.set(SpecialElement::whirlpool); - break; - case TrackElemType::waterSplash: - if (velocity >= 11.0_mph) + CableLiftUpdate(); + return; + } + + auto rideEntry = GetRideEntry(); + if (rideEntry == nullptr) + return; + + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + if (curRide->type >= RIDE_TYPE_COUNT) + return; + + if (flags.has(VehicleFlag::testing)) + UpdateMeasurements(); + + _vehicleBreakdown = Breakdown::none; + if (curRide->flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) + { + _vehicleBreakdown = curRide->breakdownReasonPending; + auto carEntry = &rideEntry->Cars[vehicle_type]; + if (carEntry->flags.has(CarEntryFlag::isPowered) && curRide->breakdownReasonPending == Breakdown::safetyCutOut) + { + if (!carEntry->flags.has(CarEntryFlag::isWaterRide) || (pitch == VehiclePitch::up25 && velocity <= 2.0_mph)) { - curRide->specialTrackElements.set(SpecialElement::splash); + flags.set(VehicleFlag::stoppedBySafetyCutout); } + } + } + + switch (status) + { + case Status::movingToEndOfStation: + UpdateMovingToEndOfStation(); + break; + case Status::waitingForPassengers: + UpdateWaitingForPassengers(); + break; + case Status::waitingToDepart: + UpdateWaitingToDepart(); + break; + case Status::crashing: + case Status::crashed: + UpdateCrash(); + break; + case Status::travellingDodgems: + UpdateDodgemsMode(); + break; + case Status::swinging: + UpdateSwinging(); + break; + case Status::simulatorOperating: + UpdateSimulatorOperating(); + break; + case Status::topSpinOperating: + UpdateTopSpinOperating(); + break; + case Status::ferrisWheelRotating: + UpdateFerrisWheelRotating(); + break; + case Status::spaceRingsOperating: + UpdateSpaceRingsOperating(); + break; + case Status::hauntedHouseOperating: + UpdateHauntedHouseOperating(); + break; + case Status::crookedHouseOperating: + UpdateCrookedHouseOperating(); + break; + case Status::rotating: + UpdateRotating(); + break; + case Status::departing: + UpdateDeparting(); + break; + case Status::travelling: + UpdateTravelling(); + break; + case Status::travellingCableLift: + UpdateTravellingCableLift(); + break; + case Status::travellingBoat: + UpdateTravellingBoat(); + break; + case Status::arriving: + UpdateArriving(); + break; + case Status::unloadingPassengers: + UpdateUnloadingPassengers(); + break; + case Status::waitingForCableLift: + UpdateWaitingForCableLift(); + break; + case Status::showingFilm: + UpdateShowingFilm(); + break; + case Status::doingCircusShow: + UpdateDoingCircusShow(); break; default: break; } - const auto& ted = GetTrackElementDescriptor(trackElemType); - auto testingFlags = curRide->testingFlags; - if (testingFlags.has(RideTestingFlag::turnLeft) && ted.flags.has(TrackElementFlag::turnLeft)) - { - // 0x800 as this is masked to kCurrentTurnCountMask - curRide->turnCountDefault += 0x800; - } - else if (testingFlags.has(RideTestingFlag::turnRight) && ted.flags.has(TrackElementFlag::turnRight)) - { - // 0x800 as this is masked to kCurrentTurnCountMask - curRide->turnCountDefault += 0x800; - } - else if (testingFlags.has(RideTestingFlag::turnRight) || testingFlags.has(RideTestingFlag::turnLeft)) - { - curRide->testingFlags.unset( - RideTestingFlag::turnLeft, RideTestingFlag::turnRight, RideTestingFlag::turnBanked, - RideTestingFlag::turnSloped); + UpdateSound(); + } - uint8_t turnType = 1; - if (!testingFlags.has(RideTestingFlag::turnBanked)) + std::optional ride_get_train_index_from_vehicle(const Ride& ride, EntityId spriteIndex) + { + uint32_t trainIndex = 0; + while (ride.vehicles[trainIndex] != spriteIndex) + { + trainIndex++; + if (trainIndex >= ride.numTrains) { - turnType = 2; - if (!testingFlags.has(RideTestingFlag::turnSloped)) + // This should really return nullopt, but doing so + // would break some hacked parks that hide track by setting tracked rides' + // track type to, e.g., Crooked House + break; + } + if (trainIndex >= std::size(ride.vehicles)) + { + return std::nullopt; + } + } + return { trainIndex }; + } + + /** + * + * rct2: 0x006D9EB0 + */ + void Vehicle::PeepEasterEggHereWeAre() const + { + for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + { + for (int32_t i = 0; i < vehicle->num_peeps; ++i) + { + auto* curPeep = getGameState().entities.GetEntity(vehicle->peep[i]); + if (curPeep != nullptr && curPeep->PeepFlags & PEEP_FLAGS_HERE_WE_ARE) { - turnType = 0; + curPeep->insertNewThought(PeepThoughtType::hereWeAre, curPeep->CurrentRide); } } - switch (curRide->turnCountDefault >> 11) + } + } + + /** + * Performed when vehicle has completed a full circuit + * rct2: 0x006D7338 + */ + static void test_finish(Ride& ride) + { + ride.flags.unset(RideFlag::testInProgress); + ride.flags.set(RideFlag::tested); + ride.windowInvalidateFlags.set(RideInvalidateFlag::ratings); + + auto rideStations = ride.getStations(); + for (int32_t i = ride.numStations - 1; i >= 1; i--) + { + if (rideStations[i - 1].SegmentTime != 0) + continue; + + uint16_t oldTime = rideStations[i - 1].SegmentTime; + rideStations[i - 1].SegmentTime = rideStations[i].SegmentTime; + rideStations[i].SegmentTime = oldTime; + + int32_t oldLength = rideStations[i - 1].SegmentLength; + rideStations[i - 1].SegmentLength = rideStations[i].SegmentLength; + rideStations[i].SegmentLength = oldLength; + } + + uint32_t totalTime = 0; + for (uint8_t i = 0; i < ride.numStations; ++i) + { + totalTime += rideStations[i].SegmentTime; + } + + totalTime = std::max(totalTime, 1u); + ride.averageSpeed = ride.averageSpeed / totalTime; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); + } + + void Vehicle::UpdateTestFinish() + { + auto curRide = GetRide(); + if (curRide == nullptr) + return; + test_finish(*curRide); + flags.unset(VehicleFlag::testing); + } + + /** + * + * rct2: 0x006D6BE7 + */ + static void test_reset(Ride& ride, StationIndex curStation) + { + ride.flags.set(RideFlag::testInProgress); + ride.flags.unset(RideFlag::noRawStats); + ride.maxSpeed = 0; + ride.averageSpeed = 0; + ride.currentTestSegment = 0; + ride.averageSpeedTestTimeout = 0; + ride.maxPositiveVerticalG = MakeFixed16_2dp(1, 0); + ride.maxNegativeVerticalG = MakeFixed16_2dp(1, 0); + ride.maxLateralG = 0; + ride.previousVerticalG = 0; + ride.previousLateralG = 0; + ride.testingFlags.clearAll(); + ride.curTestTrackLocation.SetNull(); + ride.turnCountDefault = 0; + ride.turnCountBanked = 0; + ride.turnCountSloped = 0; + ride.numInversions = 0; + ride.numHoles = 0; + ride.shelteredEighths = 0; + ride.numDrops = 0; + ride.numPoweredLifts = 0; + ride.shelteredLength = 0; + ride.var11C = 0; + ride.numShelteredSections = 0; + ride.highestDropHeight = 0; + ride.numHelices = 0; + ride.specialTrackElements.clearAll(); + for (auto& station : ride.getStations()) + { + station.SegmentLength = 0; + station.SegmentTime = 0; + } + ride.totalAirTime = 0; + ride.currentTestStation = curStation; + + auto* windowMgr = Ui::GetWindowManager(); + windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); + } + + void Vehicle::TestReset() + { + flags.set(VehicleFlag::testing); + auto curRide = GetRide(); + if (curRide == nullptr) + return; + test_reset(*curRide, current_station); + } + + // The result of this function is used to decide whether a vehicle on a tower ride should go further up or not. + // Therefore, it will return true if anything is amiss. + bool Vehicle::CurrentTowerElementIsTop() + { + TileElement* tileElement = MapGetTrackElementAtOfType(TrackLocation, GetTrackType()); + if (tileElement == nullptr) + return true; + + while (!tileElement->isLastForTile()) + { + tileElement++; + + if (tileElement->isGhost()) + continue; + + if (tileElement->getType() != TileElementType::track) + continue; + + const auto* trackElement = tileElement->asTrack(); + if (trackElement->GetRideIndex() != ride) + continue; + + if (trackElement->GetTrackType() != TrackElemType::towerSection) + continue; + + return false; + } + + return true; + } + + /** + * + * rct2: 0x006D9CE9 + */ + void Vehicle::UpdateWaitingForCableLift() + { + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + Vehicle* cableLift = getGameState().entities.GetEntity(curRide->cableLift); + if (cableLift == nullptr) + return; + + if (cableLift->status != Status::waitingForPassengers) + return; + + cableLift->SetState(Status::waitingToDepart, sub_state); + cableLift->cable_lift_target = id; + } + + /** + * + * rct2: 0x006D9D21 + */ + void Vehicle::UpdateTravellingCableLift() + { + auto curRide = GetRide(); + if (curRide == nullptr) + return; + + if (sub_state == 0) + { + if (flags.has(VehicleFlag::trainIsBroken)) { - case 0: - IncrementTurnCount1Element(*curRide, turnType); - break; - case 1: - IncrementTurnCount2Elements(*curRide, turnType); - break; - case 2: - IncrementTurnCount3Elements(*curRide, turnType); - break; - default: - IncrementTurnCount4PlusElements(*curRide, turnType); - break; + if (curRide->flags.has(RideFlag::brokenDown)) + return; + + curRide->flags.set(RideFlag::brokenDown); + RideBreakdownAddNewsItem(*curRide); + curRide->windowInvalidateFlags.set( + RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); + + curRide->mechanicStatus = MechanicStatus::calling; + curRide->inspectionStation = current_station; + curRide->breakdownReason = curRide->breakdownReasonPending; + velocity = 0; + return; } + + sub_state = 1; + PeepEasterEggHereWeAre(); + if (!curRide->flags.has(RideFlag::tested)) + { + if (flags.has(VehicleFlag::testing)) + { + if (curRide->currentTestSegment + 1 < curRide->numStations) + { + curRide->currentTestSegment++; + curRide->currentTestStation = current_station; + } + else + { + UpdateTestFinish(); + } + } + else if (!curRide->flags.has(RideFlag::testInProgress) && !isGhost()) + { + TestReset(); + } + } + } + + if (velocity <= 439800) + { + acceleration = 4398; + } + int32_t curFlags = UpdateTrackMotion(nullptr); + + if (curFlags & VEHICLE_UPDATE_MOTION_TRACK_FLAG_11) + { + SetState(Status::travelling, 1); + lost_time_out = 0; + return; + } + + if (sub_state == 2) + return; + + if (curFlags & VEHICLE_UPDATE_MOTION_TRACK_FLAG_3 && current_station == _vehicleStationIndex) + return; + + sub_state = 2; + + if (curRide->isBlockSectioned()) + return; + + // This is slightly different to the vanilla function + auto& currentStation = curRide->getStation(current_station); + currentStation.Depart &= kStationDepartFlag; + uint8_t waitingTime = 3; + if (curRide->departFlags & RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH) + { + waitingTime = std::max(curRide->minWaitingTime, static_cast(3)); + waitingTime = std::min(waitingTime, static_cast(127)); + } + + currentStation.Depart |= waitingTime; + } + + /** + * + * rct2: 0x006D73D0 + * ax: verticalG + * dx: lateralG + * esi: vehicle + */ + GForces Vehicle::GetGForces() const + { + int32_t gForceVert = ((static_cast(0x280000)) * Geometry::getPitchVector32(pitch).x) >> 32; + gForceVert = ((static_cast(gForceVert)) * Geometry::getRollHorizontalComponent(roll)) >> 32; + + const auto& ted = GetTrackElementDescriptor(GetTrackType()); + const int32_t vertFactor = ted.verticalFactor(track_progress); + const int32_t lateralFactor = ted.lateralFactor(track_progress); + + int32_t gForceLateral = 0; + + if (vertFactor != 0) + { + gForceVert += abs(velocity) * 98 / vertFactor; + } + + if (lateralFactor != 0) + { + gForceLateral += abs(velocity) * 98 / lateralFactor; + } + + gForceVert *= 10; + gForceLateral *= 10; + gForceVert >>= 16; + gForceLateral >>= 16; + return { static_cast(gForceVert & 0xFFFF), static_cast(gForceLateral & 0xFFFF) }; + } + + void Vehicle::SetMapToolbar() const + { + auto curRide = GetRide(); + if (curRide != nullptr && curRide->type < RIDE_TYPE_COUNT) + { + const Vehicle* vehicle = GetHead(); + if (vehicle == nullptr) + return; + + size_t vehicleIndex; + for (vehicleIndex = 0; vehicleIndex < std::size(curRide->vehicles); vehicleIndex++) + if (curRide->vehicles[vehicleIndex] == vehicle->id) + break; + + auto ft = Formatter(); + ft.Add(STR_RIDE_MAP_TIP); + ft.Add(STR_MAP_TOOLTIP_STRINGID_STRINGID); + curRide->formatNameTo(ft); + ft.Add(GetRideComponentName(GetRideTypeDescriptor(curRide->type).NameConvention.vehicle).capitalised); + ft.Add(vehicleIndex + 1); + curRide->formatStatusTo(ft); + auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); + intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); + ContextBroadcastIntent(&intent); + } + } + + Vehicle* Vehicle::TrainHead() const + { + const Vehicle* vehicle = this; + Vehicle* prevVehicle; + + for (;;) + { + prevVehicle = getGameState().entities.GetEntity(vehicle->prev_vehicle_on_ride); + if (prevVehicle == nullptr) + return nullptr; + if (prevVehicle->next_vehicle_on_train.IsNull()) + break; + + vehicle = prevVehicle; + } + + return const_cast(vehicle); + } + + Vehicle* Vehicle::TrainTail() const + { + const Vehicle* vehicle = this; + + EntityId spriteIndex = vehicle->next_vehicle_on_train; + while (!spriteIndex.IsNull()) + { + vehicle = getGameState().entities.GetEntity(spriteIndex); + if (vehicle == nullptr) + { + return const_cast(this); + } + spriteIndex = vehicle->next_vehicle_on_train; + } + + return const_cast(vehicle); + } + + int32_t Vehicle::IsUsedInPairs() const + { + return num_seats & kVehicleSeatPairFlag; + } + + bool Vehicle::IsCableLift() const + { + return ride_subtype == kObjectEntryIndexNull; + } + + const RideObjectEntry* Vehicle::GetRideEntry() const + { + return GetRideEntryByIndex(ride_subtype); + } + + const CarEntry* Vehicle::Entry() const + { + const auto* rideEntry = GetRideEntry(); + if (rideEntry == nullptr) + { + return nullptr; + } + return &rideEntry->Cars[vehicle_type]; + } + + Ride* Vehicle::GetRide() const + { + return OpenRCT2::GetRide(ride); + } + + int32_t Vehicle::NumPeepsUntilTrainTail() const + { + int32_t numPeeps = 0; + for (const Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) + { + numPeeps += vehicle->num_peeps; + } + + return numPeeps; + } + + /** + * + * rct2: 0x006DA1EC + */ + void Vehicle::InvalidateWindow() + { + auto intent = Intent(INTENT_ACTION_INVALIDATE_VEHICLE_WINDOW); + intent.PutExtra(INTENT_EXTRA_VEHICLE, this); + ContextBroadcastIntent(&intent); + } + + void Vehicle::UpdateCrossings() const + { + auto curRide = GetRide(); + if (curRide == nullptr) + { + return; + } + + // Parks may have rides hacked into the path. + // Limit path blocking to rides actually supporting level crossings to prevent peeps getting stuck everywhere. + if (!GetRideTypeDescriptor(curRide->type).flags.has(RtdFlag::supportsLevelCrossings)) + { + return; + } + + // In shuttle mode, only the train head is considered to be travelling backwards + // To prevent path getting blocked incorrectly, only update crossings when this is the train head + if (curRide->mode == RideMode::shuttle && TrainHead() != this) + { + return; + } + + const Vehicle* frontVehicle{}; + const Vehicle* backVehicle{}; + + bool travellingForwards = !flags.has(VehicleFlag::poweredCarInReverse); + + if (travellingForwards) + { + frontVehicle = this; + backVehicle = TrainTail(); } else { - if (ted.flags.has(TrackElementFlag::turnLeft)) - { - curRide->testingFlags.set(RideTestingFlag::turnLeft); - curRide->turnCountDefault &= ~kCurrentTurnCountMask; - - if (ted.flags.has(TrackElementFlag::turnBanked)) - { - curRide->testingFlags.set(RideTestingFlag::turnBanked); - } - if (ted.flags.has(TrackElementFlag::turnSloped)) - { - curRide->testingFlags.set(RideTestingFlag::turnSloped); - } - } - - if (ted.flags.has(TrackElementFlag::turnRight)) - { - curRide->testingFlags.set(RideTestingFlag::turnRight); - curRide->turnCountDefault &= ~kCurrentTurnCountMask; - - if (ted.flags.has(TrackElementFlag::turnBanked)) - { - curRide->testingFlags.set(RideTestingFlag::turnBanked); - } - if (ted.flags.has(TrackElementFlag::turnSloped)) - { - curRide->testingFlags.set(RideTestingFlag::turnSloped); - } - } + frontVehicle = TrainTail(); + backVehicle = this; } - if (testingFlags.has(RideTestingFlag::dropDown)) - { - if (velocity < 0 || !ted.flags.has(TrackElementFlag::down)) - { - curRide->testingFlags.unset(RideTestingFlag::dropDown); + TrackBeginEnd output{}; + int32_t direction{}; - int16_t curZ = z / kCoordsZStep - curRide->startDropHeight; - if (curZ < 0) + CoordsXYE xyElement = { frontVehicle->TrackLocation, + MapGetTrackElementAtOfTypeSeq(frontVehicle->TrackLocation, frontVehicle->GetTrackType(), 0) }; + int32_t curZ = frontVehicle->TrackLocation.z; + + if (xyElement.element != nullptr && status != Status::arriving) + { + int16_t autoReserveAhead = 4 + abs(velocity) / 150000; + int16_t crossingBonus = 0; + bool playedClaxon = false; + + // vehicle positions mean we have to take larger + // margins for travelling backwards + if (!travellingForwards) + { + autoReserveAhead += 1; + } + + while (true) + { + auto* pathElement = MapGetPathElementAt(TileCoordsXYZ(CoordsXYZ{ xyElement, xyElement.element->getBaseZ() })); + if (pathElement != nullptr) { - curZ = abs(curZ); - if (curZ > curRide->highestDropHeight) + if (!playedClaxon && !pathElement->IsBlockedByVehicle()) { - curRide->highestDropHeight = static_cast(curZ); + Claxon(); + playedClaxon = true; } - } - } - } - else if (ted.flags.has(TrackElementFlag::down) && velocity >= 0) - { - curRide->testingFlags.unset(RideTestingFlag::dropUp); - curRide->testingFlags.set(RideTestingFlag::dropDown); - - if (curRide->numDrops < Limits::kRideMaxDropsCount) - curRide->numDrops++; - - curRide->startDropHeight = z / kCoordsZStep; - testingFlags.unset(RideTestingFlag::dropUp); - } - - if (testingFlags.has(RideTestingFlag::dropUp)) - { - if (velocity > 0 || !ted.flags.has(TrackElementFlag::up)) - { - curRide->testingFlags.unset(RideTestingFlag::dropUp); - - int16_t curZ = z / kCoordsZStep - curRide->startDropHeight; - if (curZ < 0) - { - curZ = abs(curZ); - if (curZ > curRide->highestDropHeight) - { - curRide->highestDropHeight = static_cast(curZ); - } - } - } - } - else if (ted.flags.has(TrackElementFlag::up) && velocity <= 0) - { - curRide->testingFlags.unset(RideTestingFlag::dropDown); - curRide->testingFlags.set(RideTestingFlag::dropUp); - - if (curRide->numDrops < Limits::kRideMaxDropsCount) - curRide->numDrops++; - - curRide->startDropHeight = z / kCoordsZStep; - } - - if (ted.flags.has(TrackElementFlag::helix)) - { - if (curRide->numHelices < Limits::kMaxHelices) - curRide->numHelices++; - } - } - - if (currentStation.Entrance.IsNull()) - return; - - if (x == kLocationNull) - { - curRide->testingFlags.unset(RideTestingFlag::sheltered); - return; - } - - auto surfaceElement = MapGetSurfaceElementAt(CoordsXY{ x, y }); - // If vehicle above ground. - if (surfaceElement != nullptr && surfaceElement->getBaseZ() <= z) - { - if (!TrackGetIsSheltered(CoordsXYZ{ x, y, z })) - { - curRide->testingFlags.unset(RideTestingFlag::sheltered); - return; - } - } - - if (!curRide->testingFlags.has(RideTestingFlag::sheltered)) - { - curRide->testingFlags.set(RideTestingFlag::sheltered); - - curRide->increaseNumShelteredSections(); - - if (pitch != VehiclePitch::flat) - { - curRide->numShelteredSections |= ShelteredSectionsBits::kRotatingWhileSheltered; - } - - if (roll != VehicleRoll::unbanked) - { - curRide->numShelteredSections |= ShelteredSectionsBits::kBankingWhileSheltered; - } - } - - int32_t distance = ((velocity + acceleration) >> 10) * 42; - if (distance < 0) - return; - - curRide->shelteredLength = AddClamp(curRide->shelteredLength, distance); -} - -/** - * - * rct2: 0x006D77F2 - */ -void Vehicle::Update() -{ - if (IsCableLift()) - { - CableLiftUpdate(); - return; - } - - auto rideEntry = GetRideEntry(); - if (rideEntry == nullptr) - return; - - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - if (curRide->type >= RIDE_TYPE_COUNT) - return; - - if (flags.has(VehicleFlag::testing)) - UpdateMeasurements(); - - _vehicleBreakdown = Breakdown::none; - if (curRide->flags.hasAny(RideFlag::breakdownPending, RideFlag::brokenDown)) - { - _vehicleBreakdown = curRide->breakdownReasonPending; - auto carEntry = &rideEntry->Cars[vehicle_type]; - if (carEntry->flags.has(CarEntryFlag::isPowered) && curRide->breakdownReasonPending == Breakdown::safetyCutOut) - { - if (!carEntry->flags.has(CarEntryFlag::isWaterRide) || (pitch == VehiclePitch::up25 && velocity <= 2.0_mph)) - { - flags.set(VehicleFlag::stoppedBySafetyCutout); - } - } - } - - switch (status) - { - case Status::movingToEndOfStation: - UpdateMovingToEndOfStation(); - break; - case Status::waitingForPassengers: - UpdateWaitingForPassengers(); - break; - case Status::waitingToDepart: - UpdateWaitingToDepart(); - break; - case Status::crashing: - case Status::crashed: - UpdateCrash(); - break; - case Status::travellingDodgems: - UpdateDodgemsMode(); - break; - case Status::swinging: - UpdateSwinging(); - break; - case Status::simulatorOperating: - UpdateSimulatorOperating(); - break; - case Status::topSpinOperating: - UpdateTopSpinOperating(); - break; - case Status::ferrisWheelRotating: - UpdateFerrisWheelRotating(); - break; - case Status::spaceRingsOperating: - UpdateSpaceRingsOperating(); - break; - case Status::hauntedHouseOperating: - UpdateHauntedHouseOperating(); - break; - case Status::crookedHouseOperating: - UpdateCrookedHouseOperating(); - break; - case Status::rotating: - UpdateRotating(); - break; - case Status::departing: - UpdateDeparting(); - break; - case Status::travelling: - UpdateTravelling(); - break; - case Status::travellingCableLift: - UpdateTravellingCableLift(); - break; - case Status::travellingBoat: - UpdateTravellingBoat(); - break; - case Status::arriving: - UpdateArriving(); - break; - case Status::unloadingPassengers: - UpdateUnloadingPassengers(); - break; - case Status::waitingForCableLift: - UpdateWaitingForCableLift(); - break; - case Status::showingFilm: - UpdateShowingFilm(); - break; - case Status::doingCircusShow: - UpdateDoingCircusShow(); - break; - default: - break; - } - - UpdateSound(); -} - -std::optional ride_get_train_index_from_vehicle(const Ride& ride, EntityId spriteIndex) -{ - uint32_t trainIndex = 0; - while (ride.vehicles[trainIndex] != spriteIndex) - { - trainIndex++; - if (trainIndex >= ride.numTrains) - { - // This should really return nullopt, but doing so - // would break some hacked parks that hide track by setting tracked rides' - // track type to, e.g., Crooked House - break; - } - if (trainIndex >= std::size(ride.vehicles)) - { - return std::nullopt; - } - } - return { trainIndex }; -} - -/** - * - * rct2: 0x006D9EB0 - */ -void Vehicle::PeepEasterEggHereWeAre() const -{ - for (Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - for (int32_t i = 0; i < vehicle->num_peeps; ++i) - { - auto* curPeep = getGameState().entities.GetEntity(vehicle->peep[i]); - if (curPeep != nullptr && curPeep->PeepFlags & PEEP_FLAGS_HERE_WE_ARE) - { - curPeep->insertNewThought(PeepThoughtType::hereWeAre, curPeep->CurrentRide); - } - } - } -} - -/** - * Performed when vehicle has completed a full circuit - * rct2: 0x006D7338 - */ -static void test_finish(Ride& ride) -{ - ride.flags.unset(RideFlag::testInProgress); - ride.flags.set(RideFlag::tested); - ride.windowInvalidateFlags.set(RideInvalidateFlag::ratings); - - auto rideStations = ride.getStations(); - for (int32_t i = ride.numStations - 1; i >= 1; i--) - { - if (rideStations[i - 1].SegmentTime != 0) - continue; - - uint16_t oldTime = rideStations[i - 1].SegmentTime; - rideStations[i - 1].SegmentTime = rideStations[i].SegmentTime; - rideStations[i].SegmentTime = oldTime; - - int32_t oldLength = rideStations[i - 1].SegmentLength; - rideStations[i - 1].SegmentLength = rideStations[i].SegmentLength; - rideStations[i].SegmentLength = oldLength; - } - - uint32_t totalTime = 0; - for (uint8_t i = 0; i < ride.numStations; ++i) - { - totalTime += rideStations[i].SegmentTime; - } - - totalTime = std::max(totalTime, 1u); - ride.averageSpeed = ride.averageSpeed / totalTime; - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); -} - -void Vehicle::UpdateTestFinish() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; - test_finish(*curRide); - flags.unset(VehicleFlag::testing); -} - -/** - * - * rct2: 0x006D6BE7 - */ -static void test_reset(Ride& ride, StationIndex curStation) -{ - ride.flags.set(RideFlag::testInProgress); - ride.flags.unset(RideFlag::noRawStats); - ride.maxSpeed = 0; - ride.averageSpeed = 0; - ride.currentTestSegment = 0; - ride.averageSpeedTestTimeout = 0; - ride.maxPositiveVerticalG = MakeFixed16_2dp(1, 0); - ride.maxNegativeVerticalG = MakeFixed16_2dp(1, 0); - ride.maxLateralG = 0; - ride.previousVerticalG = 0; - ride.previousLateralG = 0; - ride.testingFlags.clearAll(); - ride.curTestTrackLocation.SetNull(); - ride.turnCountDefault = 0; - ride.turnCountBanked = 0; - ride.turnCountSloped = 0; - ride.numInversions = 0; - ride.numHoles = 0; - ride.shelteredEighths = 0; - ride.numDrops = 0; - ride.numPoweredLifts = 0; - ride.shelteredLength = 0; - ride.var11C = 0; - ride.numShelteredSections = 0; - ride.highestDropHeight = 0; - ride.numHelices = 0; - ride.specialTrackElements.clearAll(); - for (auto& station : ride.getStations()) - { - station.SegmentLength = 0; - station.SegmentTime = 0; - } - ride.totalAirTime = 0; - ride.currentTestStation = curStation; - - auto* windowMgr = Ui::GetWindowManager(); - windowMgr->InvalidateByNumber(WindowClass::ride, ride.id.ToUnderlying()); -} - -void Vehicle::TestReset() -{ - flags.set(VehicleFlag::testing); - auto curRide = GetRide(); - if (curRide == nullptr) - return; - test_reset(*curRide, current_station); -} - -// The result of this function is used to decide whether a vehicle on a tower ride should go further up or not. -// Therefore, it will return true if anything is amiss. -bool Vehicle::CurrentTowerElementIsTop() -{ - TileElement* tileElement = MapGetTrackElementAtOfType(TrackLocation, GetTrackType()); - if (tileElement == nullptr) - return true; - - while (!tileElement->isLastForTile()) - { - tileElement++; - - if (tileElement->isGhost()) - continue; - - if (tileElement->getType() != TileElementType::track) - continue; - - const auto* trackElement = tileElement->asTrack(); - if (trackElement->GetRideIndex() != ride) - continue; - - if (trackElement->GetTrackType() != TrackElemType::towerSection) - continue; - - return false; - } - - return true; -} - -/** - * - * rct2: 0x006D9CE9 - */ -void Vehicle::UpdateWaitingForCableLift() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - Vehicle* cableLift = getGameState().entities.GetEntity(curRide->cableLift); - if (cableLift == nullptr) - return; - - if (cableLift->status != Status::waitingForPassengers) - return; - - cableLift->SetState(Status::waitingToDepart, sub_state); - cableLift->cable_lift_target = id; -} - -/** - * - * rct2: 0x006D9D21 - */ -void Vehicle::UpdateTravellingCableLift() -{ - auto curRide = GetRide(); - if (curRide == nullptr) - return; - - if (sub_state == 0) - { - if (flags.has(VehicleFlag::trainIsBroken)) - { - if (curRide->flags.has(RideFlag::brokenDown)) - return; - - curRide->flags.set(RideFlag::brokenDown); - RideBreakdownAddNewsItem(*curRide); - curRide->windowInvalidateFlags.set( - RideInvalidateFlag::main, RideInvalidateFlag::list, RideInvalidateFlag::maintenance); - - curRide->mechanicStatus = MechanicStatus::calling; - curRide->inspectionStation = current_station; - curRide->breakdownReason = curRide->breakdownReasonPending; - velocity = 0; - return; - } - - sub_state = 1; - PeepEasterEggHereWeAre(); - if (!curRide->flags.has(RideFlag::tested)) - { - if (flags.has(VehicleFlag::testing)) - { - if (curRide->currentTestSegment + 1 < curRide->numStations) - { - curRide->currentTestSegment++; - curRide->currentTestStation = current_station; + crossingBonus = 4; + pathElement->SetIsBlockedByVehicle(true); } else { - UpdateTestFinish(); + crossingBonus = 0; + } + + if (--autoReserveAhead + crossingBonus <= 0) + { + break; + } + + curZ = xyElement.element->baseHeight; + + if (travellingForwards) + { + if (!trackBlockGetNext(&xyElement, &xyElement, &curZ, &direction)) + { + break; + } + } + else + { + if (!trackBlockGetPrevious(xyElement, &output)) + { + break; + } + xyElement.x = output.begin_x; + xyElement.y = output.begin_y; + xyElement.element = output.begin_element; + } + + // Ensure trains near a station don't block possible crossings after the stop, + // except when they are departing + if (xyElement.element->asTrack()->IsStation() && status != Status::departing) + { + break; } } - else if (!curRide->flags.has(RideFlag::testInProgress) && !isGhost()) - { - TestReset(); - } } - } - if (velocity <= 439800) - { - acceleration = 4398; - } - int32_t curFlags = UpdateTrackMotion(nullptr); - - if (curFlags & VEHICLE_UPDATE_MOTION_TRACK_FLAG_11) - { - SetState(Status::travelling, 1); - lost_time_out = 0; - return; - } - - if (sub_state == 2) - return; - - if (curFlags & VEHICLE_UPDATE_MOTION_TRACK_FLAG_3 && current_station == _vehicleStationIndex) - return; - - sub_state = 2; - - if (curRide->isBlockSectioned()) - return; - - // This is slightly different to the vanilla function - auto& currentStation = curRide->getStation(current_station); - currentStation.Depart &= kStationDepartFlag; - uint8_t waitingTime = 3; - if (curRide->departFlags & RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH) - { - waitingTime = std::max(curRide->minWaitingTime, static_cast(3)); - waitingTime = std::min(waitingTime, static_cast(127)); - } - - currentStation.Depart |= waitingTime; -} - -/** - * - * rct2: 0x006D73D0 - * ax: verticalG - * dx: lateralG - * esi: vehicle - */ -GForces Vehicle::GetGForces() const -{ - int32_t gForceVert = ((static_cast(0x280000)) * Geometry::getPitchVector32(pitch).x) >> 32; - gForceVert = ((static_cast(gForceVert)) * Geometry::getRollHorizontalComponent(roll)) >> 32; - - const auto& ted = GetTrackElementDescriptor(GetTrackType()); - const int32_t vertFactor = ted.verticalFactor(track_progress); - const int32_t lateralFactor = ted.lateralFactor(track_progress); - - int32_t gForceLateral = 0; - - if (vertFactor != 0) - { - gForceVert += abs(velocity) * 98 / vertFactor; - } - - if (lateralFactor != 0) - { - gForceLateral += abs(velocity) * 98 / lateralFactor; - } - - gForceVert *= 10; - gForceLateral *= 10; - gForceVert >>= 16; - gForceLateral >>= 16; - return { static_cast(gForceVert & 0xFFFF), static_cast(gForceLateral & 0xFFFF) }; -} - -void Vehicle::SetMapToolbar() const -{ - auto curRide = GetRide(); - if (curRide != nullptr && curRide->type < RIDE_TYPE_COUNT) - { - const Vehicle* vehicle = GetHead(); - if (vehicle == nullptr) + xyElement = { backVehicle->TrackLocation, + MapGetTrackElementAtOfTypeSeq(backVehicle->TrackLocation, backVehicle->GetTrackType(), 0) }; + if (xyElement.element == nullptr) + { return; - - size_t vehicleIndex; - for (vehicleIndex = 0; vehicleIndex < std::size(curRide->vehicles); vehicleIndex++) - if (curRide->vehicles[vehicleIndex] == vehicle->id) - break; - - auto ft = Formatter(); - ft.Add(STR_RIDE_MAP_TIP); - ft.Add(STR_MAP_TOOLTIP_STRINGID_STRINGID); - curRide->formatNameTo(ft); - ft.Add(GetRideComponentName(GetRideTypeDescriptor(curRide->type).NameConvention.vehicle).capitalised); - ft.Add(vehicleIndex + 1); - curRide->formatStatusTo(ft); - auto intent = Intent(INTENT_ACTION_SET_MAP_TOOLTIP); - intent.PutExtra(INTENT_EXTRA_FORMATTER, &ft); - ContextBroadcastIntent(&intent); - } -} - -Vehicle* Vehicle::TrainHead() const -{ - const Vehicle* vehicle = this; - Vehicle* prevVehicle; - - for (;;) - { - prevVehicle = getGameState().entities.GetEntity(vehicle->prev_vehicle_on_ride); - if (prevVehicle == nullptr) - return nullptr; - if (prevVehicle->next_vehicle_on_train.IsNull()) - break; - - vehicle = prevVehicle; - } - - return const_cast(vehicle); -} - -Vehicle* Vehicle::TrainTail() const -{ - const Vehicle* vehicle = this; - - EntityId spriteIndex = vehicle->next_vehicle_on_train; - while (!spriteIndex.IsNull()) - { - vehicle = getGameState().entities.GetEntity(spriteIndex); - if (vehicle == nullptr) - { - return const_cast(this); - } - spriteIndex = vehicle->next_vehicle_on_train; - } - - return const_cast(vehicle); -} - -int32_t Vehicle::IsUsedInPairs() const -{ - return num_seats & kVehicleSeatPairFlag; -} - -bool Vehicle::IsCableLift() const -{ - return ride_subtype == kObjectEntryIndexNull; -} - -const RideObjectEntry* Vehicle::GetRideEntry() const -{ - return GetRideEntryByIndex(ride_subtype); -} - -const CarEntry* Vehicle::Entry() const -{ - const auto* rideEntry = GetRideEntry(); - if (rideEntry == nullptr) - { - return nullptr; - } - return &rideEntry->Cars[vehicle_type]; -} - -Ride* Vehicle::GetRide() const -{ - return ::GetRide(ride); -} - -int32_t Vehicle::NumPeepsUntilTrainTail() const -{ - int32_t numPeeps = 0; - for (const Vehicle* vehicle = getGameState().entities.GetEntity(id); vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - numPeeps += vehicle->num_peeps; - } - - return numPeeps; -} - -/** - * - * rct2: 0x006DA1EC - */ -void Vehicle::InvalidateWindow() -{ - auto intent = Intent(INTENT_ACTION_INVALIDATE_VEHICLE_WINDOW); - intent.PutExtra(INTENT_EXTRA_VEHICLE, this); - ContextBroadcastIntent(&intent); -} - -void Vehicle::UpdateCrossings() const -{ - auto curRide = GetRide(); - if (curRide == nullptr) - { - return; - } - - // Parks may have rides hacked into the path. - // Limit path blocking to rides actually supporting level crossings to prevent peeps getting stuck everywhere. - if (!GetRideTypeDescriptor(curRide->type).flags.has(RtdFlag::supportsLevelCrossings)) - { - return; - } - - // In shuttle mode, only the train head is considered to be travelling backwards - // To prevent path getting blocked incorrectly, only update crossings when this is the train head - if (curRide->mode == RideMode::shuttle && TrainHead() != this) - { - return; - } - - const Vehicle* frontVehicle{}; - const Vehicle* backVehicle{}; - - bool travellingForwards = !flags.has(VehicleFlag::poweredCarInReverse); - - if (travellingForwards) - { - frontVehicle = this; - backVehicle = TrainTail(); - } - else - { - frontVehicle = TrainTail(); - backVehicle = this; - } - - TrackBeginEnd output{}; - int32_t direction{}; - - CoordsXYE xyElement = { frontVehicle->TrackLocation, - MapGetTrackElementAtOfTypeSeq(frontVehicle->TrackLocation, frontVehicle->GetTrackType(), 0) }; - int32_t curZ = frontVehicle->TrackLocation.z; - - if (xyElement.element != nullptr && status != Status::arriving) - { - int16_t autoReserveAhead = 4 + abs(velocity) / 150000; - int16_t crossingBonus = 0; - bool playedClaxon = false; - - // vehicle positions mean we have to take larger - // margins for travelling backwards - if (!travellingForwards) - { - autoReserveAhead += 1; } - while (true) + // Ensure departing trains don't clear blocked crossings behind them that might already be blocked by another incoming + // train + uint8_t freeCount = travellingForwards && status != Status::departing ? 3 : 1; + while (freeCount-- > 0) { + if (travellingForwards) + { + if (trackBlockGetPrevious(xyElement, &output)) + { + xyElement.x = output.begin_x; + xyElement.y = output.begin_y; + xyElement.element = output.begin_element; + } + } + auto* pathElement = MapGetPathElementAt(TileCoordsXYZ(CoordsXYZ{ xyElement, xyElement.element->getBaseZ() })); if (pathElement != nullptr) { - if (!playedClaxon && !pathElement->IsBlockedByVehicle()) - { - Claxon(); - playedClaxon = true; - } - crossingBonus = 4; - pathElement->SetIsBlockedByVehicle(true); - } - else - { - crossingBonus = 0; - } - - if (--autoReserveAhead + crossingBonus <= 0) - { - break; - } - - curZ = xyElement.element->baseHeight; - - if (travellingForwards) - { - if (!trackBlockGetNext(&xyElement, &xyElement, &curZ, &direction)) - { - break; - } - } - else - { - if (!trackBlockGetPrevious(xyElement, &output)) - { - break; - } - xyElement.x = output.begin_x; - xyElement.y = output.begin_y; - xyElement.element = output.begin_element; - } - - // Ensure trains near a station don't block possible crossings after the stop, - // except when they are departing - if (xyElement.element->asTrack()->IsStation() && status != Status::departing) - { - break; + pathElement->SetIsBlockedByVehicle(false); } } } - xyElement = { backVehicle->TrackLocation, - MapGetTrackElementAtOfTypeSeq(backVehicle->TrackLocation, backVehicle->GetTrackType(), 0) }; - if (xyElement.element == nullptr) + Vehicle* Vehicle::GetHead() { - return; - } - - // Ensure departing trains don't clear blocked crossings behind them that might already be blocked by another incoming train - uint8_t freeCount = travellingForwards && status != Status::departing ? 3 : 1; - while (freeCount-- > 0) - { - if (travellingForwards) + auto v = this; + while (v != nullptr && !v->IsHead()) { - if (trackBlockGetPrevious(xyElement, &output)) + v = getGameState().entities.GetEntity(v->prev_vehicle_on_ride); + } + return v; + } + + const Vehicle* Vehicle::GetHead() const + { + return (const_cast(this)->GetHead()); + } + + Vehicle* Vehicle::GetCar(size_t carIndex) const + { + auto car = const_cast(this); + for (; carIndex != 0; carIndex--) + { + car = getGameState().entities.GetEntity(car->next_vehicle_on_train); + if (car == nullptr) { - xyElement.x = output.begin_x; - xyElement.y = output.begin_y; - xyElement.element = output.begin_element; + LOG_ERROR("Tried to get non-existent car from index!"); + return nullptr; } } + return car; + } - auto* pathElement = MapGetPathElementAt(TileCoordsXYZ(CoordsXYZ{ xyElement, xyElement.element->getBaseZ() })); - if (pathElement != nullptr) + void Vehicle::SetState(Status vehicleStatus, uint8_t subState) + { + status = vehicleStatus; + sub_state = subState; + InvalidateWindow(); + } + + bool Vehicle::isGhost() const + { + auto r = GetRide(); + return r != nullptr && r->status == RideStatus::simulating; + } + + void Vehicle::EnableCollisionsForTrain() + { + assert(this->IsHead()); + for (auto vehicle = this; vehicle != nullptr; + vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) { - pathElement->SetIsBlockedByVehicle(false); + vehicle->flags.unset(VehicleFlag::collisionDisabled); } } -} -Vehicle* Vehicle::GetHead() -{ - auto v = this; - while (v != nullptr && !v->IsHead()) + void Vehicle::serialise(DataSerialiser& stream) { - v = getGameState().entities.GetEntity(v->prev_vehicle_on_ride); + EntityBase::serialise(stream); + stream << SubType; + stream << pitch; + stream << roll; + stream << remaining_distance; + stream << velocity; + stream << acceleration; + stream << ride; + stream << vehicle_type; + stream << colours; + stream << track_progress; + stream << TrackTypeAndDirection; + stream << TrackLocation; + stream << next_vehicle_on_train; + stream << prev_vehicle_on_ride; + stream << next_vehicle_on_ride; + stream << var_44; + stream << mass; + stream << flags.holder; + stream << SwingSprite; + stream << current_station; + stream << SwingPosition; + stream << SwingSpeed; + stream << status; + stream << sub_state; + stream << peep; + stream << peep_tshirt_colours; + stream << num_seats; + stream << num_peeps; + stream << next_free_seat; + stream << restraints_position; + stream << spin_speed; + stream << sound2_flags; + stream << spin_sprite; + stream << sound1_id; + stream << sound1_volume; + stream << sound2_id; + stream << sound2_volume; + stream << dopplerShift; + stream << var_C0; + stream << speed; + stream << powered_acceleration; + stream << DodgemsCollisionDirection; + stream << animation_frame; + stream << animationState; + stream << scream_sound_id; + stream << TrackSubposition; + stream << NumLaps; + stream << brake_speed; + stream << lost_time_out; + stream << vertical_drop_countdown; + stream << var_D3; + stream << mini_golf_current_animation; + stream << miniGolfFlags.holder; + stream << ride_subtype; + stream << seat_rotation; + stream << target_seat_rotation; + stream << BoatLocation; + stream << BlockBrakeSpeed; } - return v; -} -const Vehicle* Vehicle::GetHead() const -{ - return (const_cast(this)->GetHead()); -} - -Vehicle* Vehicle::GetCar(size_t carIndex) const -{ - auto car = const_cast(this); - for (; carIndex != 0; carIndex--) + bool Vehicle::IsOnCoveredTrack() const { - car = getGameState().entities.GetEntity(car->next_vehicle_on_train); - if (car == nullptr) - { - LOG_ERROR("Tried to get non-existent car from index!"); - return nullptr; - } + return trackTypeIsCovered(GetTrackType()); } - return car; -} - -void Vehicle::SetState(Status vehicleStatus, uint8_t subState) -{ - status = vehicleStatus; - sub_state = subState; - InvalidateWindow(); -} - -bool Vehicle::isGhost() const -{ - auto r = GetRide(); - return r != nullptr && r->status == RideStatus::simulating; -} - -void Vehicle::EnableCollisionsForTrain() -{ - assert(this->IsHead()); - for (auto vehicle = this; vehicle != nullptr; - vehicle = getGameState().entities.GetEntity(vehicle->next_vehicle_on_train)) - { - vehicle->flags.unset(VehicleFlag::collisionDisabled); - } -} - -void Vehicle::serialise(DataSerialiser& stream) -{ - EntityBase::serialise(stream); - stream << SubType; - stream << pitch; - stream << roll; - stream << remaining_distance; - stream << velocity; - stream << acceleration; - stream << ride; - stream << vehicle_type; - stream << colours; - stream << track_progress; - stream << TrackTypeAndDirection; - stream << TrackLocation; - stream << next_vehicle_on_train; - stream << prev_vehicle_on_ride; - stream << next_vehicle_on_ride; - stream << var_44; - stream << mass; - stream << flags.holder; - stream << SwingSprite; - stream << current_station; - stream << SwingPosition; - stream << SwingSpeed; - stream << status; - stream << sub_state; - stream << peep; - stream << peep_tshirt_colours; - stream << num_seats; - stream << num_peeps; - stream << next_free_seat; - stream << restraints_position; - stream << spin_speed; - stream << sound2_flags; - stream << spin_sprite; - stream << sound1_id; - stream << sound1_volume; - stream << sound2_id; - stream << sound2_volume; - stream << dopplerShift; - stream << var_C0; - stream << speed; - stream << powered_acceleration; - stream << DodgemsCollisionDirection; - stream << animation_frame; - stream << animationState; - stream << scream_sound_id; - stream << TrackSubposition; - stream << NumLaps; - stream << brake_speed; - stream << lost_time_out; - stream << vertical_drop_countdown; - stream << var_D3; - stream << mini_golf_current_animation; - stream << miniGolfFlags.holder; - stream << ride_subtype; - stream << seat_rotation; - stream << target_seat_rotation; - stream << BoatLocation; - stream << BlockBrakeSpeed; -} - -bool Vehicle::IsOnCoveredTrack() const -{ - return trackTypeIsCovered(GetTrackType()); -} +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/Vehicle.h b/src/openrct2/ride/Vehicle.h index 0ba31ea1d7..f339865415 100644 --- a/src/openrct2/ride/Vehicle.h +++ b/src/openrct2/ride/Vehicle.h @@ -16,564 +16,538 @@ #include "../world/Location.hpp" #include "Angles.h" #include "VehicleColour.h" +#include "VehicleFlags.h" #include "VehicleSubpositionData.h" #include "ted/PitchAndRoll.h" #include #include -struct Ride; struct RideObjectEntry; struct CarEntry; -enum class Breakdown : uint8_t; - namespace OpenRCT2 { + enum class Breakdown : uint8_t; + class DataSerialiser; + struct Ride; struct TrackElement; + + struct GForces + { + int32_t verticalG{}; + int32_t lateralG{}; + }; + + // Size: 0x09 + struct VehicleInfo + { + int16_t x; // 0x00 + int16_t y; // 0x02 + int16_t z; // 0x04 + uint8_t yaw; // 0x06 + VehiclePitch pitch; // 0x07 + VehicleRoll roll; // 0x08 + + bool isInvalid() const + { + return x == 0 && y == 0 && z == 0 && yaw == 0 && pitch == VehiclePitch::flat && roll == VehicleRoll::unbanked; + } + }; + + struct SoundIdVolume + { + Audio::SoundId id; + uint8_t volume; + }; + + static constexpr uint16_t kVehicleTrackDirectionMask = 0b0000000000000011; + static constexpr uint16_t kVehicleTrackTypeMask = 0b1111111111111100; + + enum class MiniGolfAnimation : uint8_t; + + enum class MiniGolfFlag : uint8_t + { + flag0, + flag1, + flag2, + flag3, + flag4, + flag5, // transitioning between hole + }; + + using MiniGolfFlags = FlagHolder; + + struct Vehicle : EntityBase + { + static constexpr auto cEntityType = EntityType::vehicle; + + enum class Type : uint8_t + { + head, + tail, + }; + + enum class Status : uint8_t + { + movingToEndOfStation, + waitingForPassengers, + waitingToDepart, + departing, + travelling, + arriving, + unloadingPassengers, + travellingBoat, + crashing, + crashed, + travellingDodgems, + swinging, + rotating, + ferrisWheelRotating, + simulatorOperating, + showingFilm, + spaceRingsOperating, + topSpinOperating, + hauntedHouseOperating, + doingCircusShow, + crookedHouseOperating, + waitingForCableLift, + travellingCableLift, + stopping, + waitingForPassengers17, + waitingToStart, + starting, + operating1A, + stopping1B, + unloadingPassengers1C, + stoppedByBlockBrakes, + }; + + Type SubType; + union + { + VehiclePitch pitch; + uint8_t flatRideAnimationFrame; + }; + union + { + VehicleRoll roll; + uint8_t flatRideSecondaryAnimationFrame; + }; + int32_t remaining_distance; + int32_t velocity; + int32_t acceleration; + RideId ride; + uint8_t vehicle_type; + VehicleColour colours; + union + { + uint16_t track_progress; + struct + { + int8_t var_34; + uint8_t var_35; + }; + }; + uint16_t TrackTypeAndDirection; + CoordsXYZ TrackLocation; + EntityId next_vehicle_on_train; + + // The previous vehicle on the same train or the last vehicle on the previous or only train. + EntityId prev_vehicle_on_ride; + + // The next vehicle on the same train or the first vehicle on the next or only train + EntityId next_vehicle_on_ride; + + uint16_t var_44; + uint16_t mass; + VehicleFlags flags; + uint8_t SwingSprite; + StationIndex current_station; + union + { + int16_t SwingPosition; + int16_t current_time; + struct + { + int8_t ferris_wheel_var_0; + int8_t ferris_wheel_var_1; + }; + int16_t rider_speed_preference; + }; + union + { + int16_t SwingSpeed; + int16_t crash_z; + }; + Status status; + uint8_t sub_state; + EntityId peep[32]; + Drawing::Colour peep_tshirt_colours[32]; + uint8_t num_seats; + uint8_t num_peeps; + uint8_t next_free_seat; + uint8_t restraints_position; // 0 == Close, 255 == Open + union + { + int16_t spin_speed; + int16_t crash_x; + }; + uint16_t sound2_flags; + uint8_t spin_sprite; // lowest 3 bits not used for sprite selection (divide by 8 to use) + Audio::SoundId sound1_id; + uint8_t sound1_volume; + Audio::SoundId sound2_id; + uint8_t sound2_volume; + int8_t dopplerShift; + union + { + uint16_t var_C0; + int16_t crash_y; + uint16_t time_waiting; + EntityId cable_lift_target; + }; + uint8_t speed; + uint8_t powered_acceleration; + union + { + uint8_t DodgemsCollisionDirection; + uint8_t CollisionDetectionTimer; + }; + uint8_t animation_frame; + uint8_t PadC6[0x2]; + uint32_t animationState; + Audio::SoundId scream_sound_id; + VehicleTrackSubposition TrackSubposition; + union + { + uint8_t NumLaps; + uint8_t NumSwings; + uint8_t NumLaunches; + uint8_t NumRotations; + uint8_t TimeActive; + }; + uint8_t brake_speed; + uint16_t lost_time_out; + int8_t vertical_drop_countdown; + uint8_t var_D3; + MiniGolfAnimation mini_golf_current_animation; + MiniGolfFlags miniGolfFlags; + ObjectEntryIndex ride_subtype; + uint8_t seat_rotation; + uint8_t target_seat_rotation; + CoordsXY BoatLocation; + uint8_t BlockBrakeSpeed; + + constexpr bool IsHead() const + { + return SubType == Type::head; + } + void Update(); + Vehicle* GetHead(); + const Vehicle* GetHead() const; + Vehicle* GetCar(size_t carIndex) const; + void SetState(Status vehicleStatus, uint8_t subState = 0); + bool isGhost() const; + std::optional DodgemsCarWouldCollideAt(const CoordsXY& coords) const; + int32_t UpdateTrackMotion(int32_t* outStation); + int32_t CableLiftUpdateTrackMotion(); + GForces GetGForces() const; + void SetMapToolbar() const; + int32_t IsUsedInPairs() const; + const RideObjectEntry* GetRideEntry() const; + const CarEntry* Entry() const; + Ride* GetRide() const; + Vehicle* TrainHead() const; + Vehicle* TrainTail() const; + uint16_t GetTrackProgress() const; + void UpdateAnimationAnimalFlying(); + void EnableCollisionsForTrain(); + /** + * Instantly moves the specific car forward or backwards along the track. + */ + void MoveRelativeDistance(int32_t distance); + void UpdateTrackChange(); + TrackElemType GetTrackType() const + { + return static_cast(TrackTypeAndDirection >> 2); + } + bool IsOnCoveredTrack() const; + uint8_t GetTrackDirection() const + { + return TrackTypeAndDirection & kVehicleTrackDirectionMask; + } + void SetTrackType(TrackElemType trackType) + { + // set the upper 14 bits to 0, then set track type + TrackTypeAndDirection &= ~kVehicleTrackTypeMask; + TrackTypeAndDirection |= EnumValue(trackType) << 2; + } + void SetTrackDirection(uint8_t trackDirection) + { + // set the lower 2 bits only + TrackTypeAndDirection &= ~kVehicleTrackDirectionMask; + TrackTypeAndDirection |= trackDirection & kVehicleTrackDirectionMask; + } + void ApplyMass(int16_t appliedMass); + void serialise(DataSerialiser& stream); + bool IsCableLift() const; + + friend void UpdateRotatingDefault(Vehicle& vehicle); + friend void UpdateRotatingEnterprise(Vehicle& vehicle); + + private: + const VehicleInfo* GetMoveInfo() const; + void CableLiftUpdate(); + bool CableLiftUpdateTrackMotionForwards(); + bool CableLiftUpdateTrackMotionBackwards(); + void CableLiftUpdateMovingToEndOfStation(); + void CableLiftUpdateWaitingToDepart(); + void CableLiftUpdateDeparting(); + void CableLiftUpdateTravelling(); + void CableLiftUpdateArriving(); + void Sub6DBF3E(); + void UpdateMeasurements(); + void UpdateMovingToEndOfStation(); + void UpdateWaitingForPassengers(); + void UpdateWaitingToDepart(); + void UpdateCrash(); + void UpdateDodgemsMode(); + void UpdateSwinging(); + void UpdateSimulatorOperating(); + void UpdateTopSpinOperating(); + void UpdateFerrisWheelRotating(); + void UpdateSpaceRingsOperating(); + void UpdateHauntedHouseOperating(); + void UpdateCrookedHouseOperating(); + void UpdateRotating(); + void UpdateDeparting(); + void FinishDeparting(); + void UpdateTravelling(); + void UpdateTravellingCableLift(); + void UpdateTravellingBoat(); + void UpdateMotionBoatHire(); + void TryReconnectBoatToTrack(const CoordsXY& currentBoatLocation, const CoordsXY& trackCoords); + void UpdateDepartingBoatHire(); + void UpdateTravellingBoatHireSetup(); + void UpdateBoatLocation(); + void UpdateArrivingPassThroughStation(const Ride& curRide, const CarEntry& carEntry, bool stationBrakesWork); + void UpdateArriving(); + void UpdateUnloadingPassengers(); + void UpdateWaitingForCableLift(); + void UpdateShowingFilm(); + void UpdateDoingCircusShow(); + void UpdateCrossings() const; + void UpdateSound(); + void GetLiftHillSound(const Ride& curRide, SoundIdVolume& curSound); + Audio::SoundId UpdateScreamSound(); + Audio::SoundId ProduceScreamSound(int32_t totalNumPeeps); + void UpdateCrashSetup(); + void UpdateCollisionSetup(); + int32_t UpdateMotionDodgems(); + void UpdateAdditionalAnimation(); + void CheckIfMissing(); + bool CurrentTowerElementIsTop(); + bool UpdateTrackMotionForwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry); + bool UpdateTrackMotionBackwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry); + int32_t UpdateTrackMotionPoweredRideAcceleration(const CarEntry* carEntry, uint32_t totalMass, int32_t curAcceleration); + int32_t NumPeepsUntilTrainTail() const; + void InvalidateWindow(); + void TestReset(); + void UpdateTestFinish(); + void PeepEasterEggHereWeAre() const; + bool CanDepartSynchronised() const; + void ReverseReverserCar(); + void UpdateReverserCarBogies(); + void UpdateHandleWaterSplash() const; + void Claxon() const; + void UpdateTrackMotionUpStopCheck() const; + void ApplyNonStopBlockBrake(); + void ApplyStopBlockBrake(); + void ApplyCableLiftBlockBrake(bool brakeClosed); + void CheckAndApplyBlockSectionStopSite(); + void UpdateVelocity(); + void UpdateSpinningCar(); + void UpdateSwingingCar(); + int32_t GetSwingAmount() const; + bool OpenRestraints(); + bool CloseRestraints(); + void CrashOnWater(); + void CrashOnLand(); + void SimulateCrash() const; + void KillAllPassengersInTrain(); + void KillPassengers(const Ride& curRide); + void TrainReadyToDepart(uint8_t num_peeps_on_train, uint8_t num_used_seats); + int32_t UpdateTrackMotionMiniGolfCalculateAcceleration(const CarEntry& carEntry); + int32_t UpdateTrackMotionMiniGolf(int32_t* outStation); + void UpdateTrackMotionMiniGolfVehicle(const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry); + bool UpdateTrackMotionForwardsGetNewTrack( + TrackElemType trackType, const Ride& curRide, const RideObjectEntry& rideEntry); + bool UpdateTrackMotionBackwardsGetNewTrack(TrackElemType trackType, const Ride& curRide, uint16_t* progress); + bool UpdateMotionCollisionDetection(const CoordsXYZ& loc, EntityId* otherVehicleIndex); + void UpdateGoKartAttemptSwitchLanes(); + void UpdateSceneryDoor() const; + void UpdateSceneryDoorBackwards() const; + void UpdateLandscapeDoors(int32_t previousTrackHeight) const; + int32_t CalculateRiderBraking() const; + uint8_t ChooseBrakeSpeed() const; + void PopulateBrakeSpeed(const CoordsXYZ& vehicleTrackLocation, TrackElement& brake); + + void Loc6DCE02(const Ride& curRide); + void Loc6DCDE4(const Ride& curRide); + + enum class UpdateMiniGolfSubroutineStatus + { + carryOn, + restart, + stop, + }; + [[nodiscard]] UpdateMiniGolfSubroutineStatus UpdateTrackMotionMiniGolfFlagsStatus(const Ride& curRide); + /** + * @return UpdateMiniGolfSubroutineStatus::stop or UpdateMiniGolfSubroutineStatus::carryOn + */ + [[nodiscard]] UpdateMiniGolfSubroutineStatus Loc6DC462(const Ride& curRide); + /** + * @return UpdateMiniGolfSubroutineStatus::stop or UpdateMiniGolfSubroutineStatus::restart + */ + [[nodiscard]] UpdateMiniGolfSubroutineStatus Loc6DCA9A(const Ride& curRide); + void UpdateTrackMotionPreUpdate( + Vehicle& car, const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry); + }; + static_assert(sizeof(Vehicle) <= 512); + + void UpdateRotatingDefault(Vehicle& vehicle); + void UpdateRotatingEnterprise(Vehicle& vehicle); + + struct TrainReference + { + Vehicle* head; + Vehicle* tail; + }; + + enum class MiniGolfState : int16_t + { + unk0, + unk1, // Unused + unk2, + unk3, + unk4, + unk5, + unk6, + }; + + enum class MiniGolfAnimation : uint8_t + { + walk, + placeBallDown, + swingLeft, + pickupBall, + jump, + placeBallUp, + puttLeft, + swing, + putt, + }; + + enum BoatHireSubState : uint8_t + { + rowing, + enteringReturnPosition, + }; + + enum + { + VEHICLE_VISUAL_DEFAULT, + VEHICLE_VISUAL_FLAT_RIDE_OR_CAR_RIDE, + VEHICLE_VISUAL_LAUNCHED_FREEFALL, + VEHICLE_VISUAL_OBSERVATION_TOWER, + VEHICLE_VISUAL_RIVER_RAPIDS, + VEHICLE_VISUAL_MINI_GOLF_PLAYER, + VEHICLE_VISUAL_MINI_GOLF_BALL, + VEHICLE_VISUAL_REVERSER, + VEHICLE_VISUAL_SPLASH_BOATS_OR_WATER_COASTER, + VEHICLE_VISUAL_ROTO_DROP, + VEHICLE_VISUAL_SPLASH1_EFFECT, + VEHICLE_VISUAL_SPLASH2_EFFECT, + VEHICLE_VISUAL_SPLASH3_EFFECT, + VEHICLE_VISUAL_SPLASH4_EFFECT, + VEHICLE_VISUAL_SPLASH5_EFFECT, + VEHICLE_VISUAL_VIRGINIA_REEL, + VEHICLE_VISUAL_SUBMARINE, + VEHICLE_VISUAL_SPINNING_CARS, + }; + + enum : uint32_t + { + VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION = 1 << 0, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_1 = 1 << 1, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_2 = 1 << 2, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_3 = 1 << 3, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_ON_LIFT_HILL = 1 << 4, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_5 = 1 << 5, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED = 1 << 6, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION = 1 << 7, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_8 = 1 << 8, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_9 = 1 << 9, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE = 1 << 10, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_11 = 1 << 11, + VEHICLE_UPDATE_MOTION_TRACK_FLAG_12 = 1 << 12, + }; + + enum + { + VEHICLE_SOUND2_FLAGS_LIFT_HILL = 1 << 1 // When on a lift hill generate sound + }; + + enum + { + FRICTION_SOUND_WOOD_SMALL = 1, + FRICTION_SOUND_STEEL = 2, + FRICTION_SOUND_PETROL = 21, + FRICTION_SOUND_TRAIN = 31, + FRICTION_SOUND_WATERSLIDE = 32, + FRICTION_SOUND_WOOD_LARGE = 54, + FRICTION_SOUND_STEEL_SMOOTH = 57, + FRICTION_SOUND_HYBRID = 65, + FRICTION_SOUND_NONE = 255 + }; + + enum class SoundRange : uint8_t + { + screamsMisc = 0, // Used by rides where the screams should not include rolling sounds. + screamsWoodenRollerCoaster = 1, + screamSteelRollerCoaster = 2, + steamWhistle = 3, + tramBell = 4, + none = 255, + }; + + constexpr uint8_t kVehicleSeatPairFlag = 0x80; + constexpr uint8_t kVehicleSeatNumMask = 0x7F; + + TrackMetadata::PitchAndRoll PitchAndRollStart(bool useInvertedSprites, TileElement* tileElement); + int32_t GetAccelerationDecrease2(const int32_t velocity, const int32_t totalMass); + + Vehicle* TryGetVehicle(EntityId spriteIndex); + void VehicleUpdateAll(); + void VehicleSoundsUpdate(); + std::optional ride_get_train_index_from_vehicle(const Ride& ride, EntityId spriteIndex); + uint16_t VehicleGetMoveInfoSize(VehicleTrackSubposition trackSubposition, TrackElemType type, uint8_t direction); + + void RideUpdateMeasurementsSpecialElements_Default(Ride& ride, TrackElemType trackType); + void RideUpdateMeasurementsSpecialElements_MiniGolf(Ride& ride, TrackElemType trackType); + void RideUpdateMeasurementsSpecialElements_WaterCoaster(Ride& ride, TrackElemType trackType); + + extern Vehicle* gCurrentVehicle; + extern Breakdown _vehicleBreakdown; + extern StationIndex _vehicleStationIndex; + extern uint32_t _vehicleMotionTrackFlags; + extern int32_t _vehicleVelocityF64E08; + extern int32_t _vehicleVelocityF64E0C; + extern int32_t _vehicleUnkF64E10; + extern uint8_t _vehicleF64E2C; + extern Vehicle* _vehicleFrontVehicle; + extern CoordsXYZ _vehicleCurPosition; } // namespace OpenRCT2 - -struct GForces -{ - int32_t verticalG{}; - int32_t lateralG{}; -}; - -// Size: 0x09 -struct VehicleInfo -{ - int16_t x; // 0x00 - int16_t y; // 0x02 - int16_t z; // 0x04 - uint8_t yaw; // 0x06 - VehiclePitch pitch; // 0x07 - VehicleRoll roll; // 0x08 - - bool isInvalid() const - { - return x == 0 && y == 0 && z == 0 && yaw == 0 && pitch == VehiclePitch::flat && roll == VehicleRoll::unbanked; - } -}; - -struct SoundIdVolume -{ - OpenRCT2::Audio::SoundId id; - uint8_t volume; -}; - -static constexpr uint16_t kVehicleTrackDirectionMask = 0b0000000000000011; -static constexpr uint16_t kVehicleTrackTypeMask = 0b1111111111111100; - -enum class VehicleFlag : uint8_t -{ - onLiftHill, - collisionDisabled, - waitingOnAdjacentStation, - poweredCarInReverse, - readyToDepart, - testing, - // When go-karts are colliding, they have a higher chance of changing lanes - currentlyColliding, - // Used on vehicles when a safety cut-out stops them, such as RCs on a lift hill and powered rides - stoppedBySafetyCutout, - carIsBroken, - trainIsBroken, - stoppedOnHoldingBrake, - // Used on vehicles that can run inverted for extended periods of time, i.e. the Flying, Lay-down and Multi-Dimension trains - carIsInverted, - // Set when the vehicle travels backwards through the station for the first time - reverseInclineCompletedLap, - spinningIsLocked, // After passing a rotation toggle track piece this will enable - // OpenRCT2 Flag: Used to override UpdateMotion to move the position of an individual car on a train - moveSingleCar, - crashed, // Car displays as smoke plume - carIsReversed, // Car is displayed running backwards -}; -using VehicleFlags = FlagHolder; - -enum class MiniGolfAnimation : uint8_t; - -enum class MiniGolfFlag : uint8_t -{ - flag0, - flag1, - flag2, - flag3, - flag4, - flag5, // transitioning between hole -}; - -using MiniGolfFlags = FlagHolder; - -struct Vehicle : OpenRCT2::EntityBase -{ - static constexpr auto cEntityType = OpenRCT2::EntityType::vehicle; - - enum class Type : uint8_t - { - head, - tail, - }; - - enum class Status : uint8_t - { - movingToEndOfStation, - waitingForPassengers, - waitingToDepart, - departing, - travelling, - arriving, - unloadingPassengers, - travellingBoat, - crashing, - crashed, - travellingDodgems, - swinging, - rotating, - ferrisWheelRotating, - simulatorOperating, - showingFilm, - spaceRingsOperating, - topSpinOperating, - hauntedHouseOperating, - doingCircusShow, - crookedHouseOperating, - waitingForCableLift, - travellingCableLift, - stopping, - waitingForPassengers17, - waitingToStart, - starting, - operating1A, - stopping1B, - unloadingPassengers1C, - stoppedByBlockBrakes, - }; - - Type SubType; - union - { - VehiclePitch pitch; - uint8_t flatRideAnimationFrame; - }; - union - { - VehicleRoll roll; - uint8_t flatRideSecondaryAnimationFrame; - }; - int32_t remaining_distance; - int32_t velocity; - int32_t acceleration; - RideId ride; - uint8_t vehicle_type; - VehicleColour colours; - union - { - uint16_t track_progress; - struct - { - int8_t var_34; - uint8_t var_35; - }; - }; - uint16_t TrackTypeAndDirection; - CoordsXYZ TrackLocation; - EntityId next_vehicle_on_train; - - // The previous vehicle on the same train or the last vehicle on the previous or only train. - EntityId prev_vehicle_on_ride; - - // The next vehicle on the same train or the first vehicle on the next or only train - EntityId next_vehicle_on_ride; - - uint16_t var_44; - uint16_t mass; - VehicleFlags flags; - uint8_t SwingSprite; - StationIndex current_station; - union - { - int16_t SwingPosition; - int16_t current_time; - struct - { - int8_t ferris_wheel_var_0; - int8_t ferris_wheel_var_1; - }; - int16_t rider_speed_preference; - }; - union - { - int16_t SwingSpeed; - int16_t crash_z; - }; - Status status; - uint8_t sub_state; - EntityId peep[32]; - OpenRCT2::Drawing::Colour peep_tshirt_colours[32]; - uint8_t num_seats; - uint8_t num_peeps; - uint8_t next_free_seat; - uint8_t restraints_position; // 0 == Close, 255 == Open - union - { - int16_t spin_speed; - int16_t crash_x; - }; - uint16_t sound2_flags; - uint8_t spin_sprite; // lowest 3 bits not used for sprite selection (divide by 8 to use) - OpenRCT2::Audio::SoundId sound1_id; - uint8_t sound1_volume; - OpenRCT2::Audio::SoundId sound2_id; - uint8_t sound2_volume; - int8_t dopplerShift; - union - { - uint16_t var_C0; - int16_t crash_y; - uint16_t time_waiting; - EntityId cable_lift_target; - }; - uint8_t speed; - uint8_t powered_acceleration; - union - { - uint8_t DodgemsCollisionDirection; - uint8_t CollisionDetectionTimer; - }; - uint8_t animation_frame; - uint8_t PadC6[0x2]; - uint32_t animationState; - OpenRCT2::Audio::SoundId scream_sound_id; - VehicleTrackSubposition TrackSubposition; - union - { - uint8_t NumLaps; - uint8_t NumSwings; - uint8_t NumLaunches; - uint8_t NumRotations; - uint8_t TimeActive; - }; - uint8_t brake_speed; - uint16_t lost_time_out; - int8_t vertical_drop_countdown; - uint8_t var_D3; - MiniGolfAnimation mini_golf_current_animation; - MiniGolfFlags miniGolfFlags; - OpenRCT2::ObjectEntryIndex ride_subtype; - uint8_t seat_rotation; - uint8_t target_seat_rotation; - CoordsXY BoatLocation; - uint8_t BlockBrakeSpeed; - - constexpr bool IsHead() const - { - return SubType == Type::head; - } - void Update(); - Vehicle* GetHead(); - const Vehicle* GetHead() const; - Vehicle* GetCar(size_t carIndex) const; - void SetState(Status vehicleStatus, uint8_t subState = 0); - bool isGhost() const; - std::optional DodgemsCarWouldCollideAt(const CoordsXY& coords) const; - int32_t UpdateTrackMotion(int32_t* outStation); - int32_t CableLiftUpdateTrackMotion(); - GForces GetGForces() const; - void SetMapToolbar() const; - int32_t IsUsedInPairs() const; - const RideObjectEntry* GetRideEntry() const; - const CarEntry* Entry() const; - Ride* GetRide() const; - Vehicle* TrainHead() const; - Vehicle* TrainTail() const; - uint16_t GetTrackProgress() const; - void UpdateAnimationAnimalFlying(); - void EnableCollisionsForTrain(); - /** - * Instantly moves the specific car forward or backwards along the track. - */ - void MoveRelativeDistance(int32_t distance); - void UpdateTrackChange(); - OpenRCT2::TrackElemType GetTrackType() const - { - return static_cast(TrackTypeAndDirection >> 2); - } - bool IsOnCoveredTrack() const; - uint8_t GetTrackDirection() const - { - return TrackTypeAndDirection & kVehicleTrackDirectionMask; - } - void SetTrackType(OpenRCT2::TrackElemType trackType) - { - // set the upper 14 bits to 0, then set track type - TrackTypeAndDirection &= ~kVehicleTrackTypeMask; - TrackTypeAndDirection |= EnumValue(trackType) << 2; - } - void SetTrackDirection(uint8_t trackDirection) - { - // set the lower 2 bits only - TrackTypeAndDirection &= ~kVehicleTrackDirectionMask; - TrackTypeAndDirection |= trackDirection & kVehicleTrackDirectionMask; - } - void ApplyMass(int16_t appliedMass); - void serialise(OpenRCT2::DataSerialiser& stream); - bool IsCableLift() const; - - friend void UpdateRotatingDefault(Vehicle& vehicle); - friend void UpdateRotatingEnterprise(Vehicle& vehicle); - -private: - const VehicleInfo* GetMoveInfo() const; - void CableLiftUpdate(); - bool CableLiftUpdateTrackMotionForwards(); - bool CableLiftUpdateTrackMotionBackwards(); - void CableLiftUpdateMovingToEndOfStation(); - void CableLiftUpdateWaitingToDepart(); - void CableLiftUpdateDeparting(); - void CableLiftUpdateTravelling(); - void CableLiftUpdateArriving(); - void Sub6DBF3E(); - void UpdateMeasurements(); - void UpdateMovingToEndOfStation(); - void UpdateWaitingForPassengers(); - void UpdateWaitingToDepart(); - void UpdateCrash(); - void UpdateDodgemsMode(); - void UpdateSwinging(); - void UpdateSimulatorOperating(); - void UpdateTopSpinOperating(); - void UpdateFerrisWheelRotating(); - void UpdateSpaceRingsOperating(); - void UpdateHauntedHouseOperating(); - void UpdateCrookedHouseOperating(); - void UpdateRotating(); - void UpdateDeparting(); - void FinishDeparting(); - void UpdateTravelling(); - void UpdateTravellingCableLift(); - void UpdateTravellingBoat(); - void UpdateMotionBoatHire(); - void TryReconnectBoatToTrack(const CoordsXY& currentBoatLocation, const CoordsXY& trackCoords); - void UpdateDepartingBoatHire(); - void UpdateTravellingBoatHireSetup(); - void UpdateBoatLocation(); - void UpdateArrivingPassThroughStation(const Ride& curRide, const CarEntry& carEntry, bool stationBrakesWork); - void UpdateArriving(); - void UpdateUnloadingPassengers(); - void UpdateWaitingForCableLift(); - void UpdateShowingFilm(); - void UpdateDoingCircusShow(); - void UpdateCrossings() const; - void UpdateSound(); - void GetLiftHillSound(const Ride& curRide, SoundIdVolume& curSound); - OpenRCT2::Audio::SoundId UpdateScreamSound(); - OpenRCT2::Audio::SoundId ProduceScreamSound(int32_t totalNumPeeps); - void UpdateCrashSetup(); - void UpdateCollisionSetup(); - int32_t UpdateMotionDodgems(); - void UpdateAdditionalAnimation(); - void CheckIfMissing(); - bool CurrentTowerElementIsTop(); - bool UpdateTrackMotionForwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry); - bool UpdateTrackMotionBackwards(const CarEntry* carEntry, const Ride& curRide, const RideObjectEntry& rideEntry); - int32_t UpdateTrackMotionPoweredRideAcceleration(const CarEntry* carEntry, uint32_t totalMass, int32_t curAcceleration); - int32_t NumPeepsUntilTrainTail() const; - void InvalidateWindow(); - void TestReset(); - void UpdateTestFinish(); - void PeepEasterEggHereWeAre() const; - bool CanDepartSynchronised() const; - void ReverseReverserCar(); - void UpdateReverserCarBogies(); - void UpdateHandleWaterSplash() const; - void Claxon() const; - void UpdateTrackMotionUpStopCheck() const; - void ApplyNonStopBlockBrake(); - void ApplyStopBlockBrake(); - void ApplyCableLiftBlockBrake(bool brakeClosed); - void CheckAndApplyBlockSectionStopSite(); - void UpdateVelocity(); - void UpdateSpinningCar(); - void UpdateSwingingCar(); - int32_t GetSwingAmount() const; - bool OpenRestraints(); - bool CloseRestraints(); - void CrashOnWater(); - void CrashOnLand(); - void SimulateCrash() const; - void KillAllPassengersInTrain(); - void KillPassengers(const Ride& curRide); - void TrainReadyToDepart(uint8_t num_peeps_on_train, uint8_t num_used_seats); - int32_t UpdateTrackMotionMiniGolfCalculateAcceleration(const CarEntry& carEntry); - int32_t UpdateTrackMotionMiniGolf(int32_t* outStation); - void UpdateTrackMotionMiniGolfVehicle(const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry); - bool UpdateTrackMotionForwardsGetNewTrack( - OpenRCT2::TrackElemType trackType, const Ride& curRide, const RideObjectEntry& rideEntry); - bool UpdateTrackMotionBackwardsGetNewTrack(OpenRCT2::TrackElemType trackType, const Ride& curRide, uint16_t* progress); - bool UpdateMotionCollisionDetection(const CoordsXYZ& loc, EntityId* otherVehicleIndex); - void UpdateGoKartAttemptSwitchLanes(); - void UpdateSceneryDoor() const; - void UpdateSceneryDoorBackwards() const; - void UpdateLandscapeDoors(int32_t previousTrackHeight) const; - int32_t CalculateRiderBraking() const; - uint8_t ChooseBrakeSpeed() const; - void PopulateBrakeSpeed(const CoordsXYZ& vehicleTrackLocation, OpenRCT2::TrackElement& brake); - - void Loc6DCE02(const Ride& curRide); - void Loc6DCDE4(const Ride& curRide); - - enum class UpdateMiniGolfSubroutineStatus - { - carryOn, - restart, - stop, - }; - [[nodiscard]] UpdateMiniGolfSubroutineStatus UpdateTrackMotionMiniGolfFlagsStatus(const Ride& curRide); - /** - * @return UpdateMiniGolfSubroutineStatus::stop or UpdateMiniGolfSubroutineStatus::carryOn - */ - [[nodiscard]] UpdateMiniGolfSubroutineStatus Loc6DC462(const Ride& curRide); - /** - * @return UpdateMiniGolfSubroutineStatus::stop or UpdateMiniGolfSubroutineStatus::restart - */ - [[nodiscard]] UpdateMiniGolfSubroutineStatus Loc6DCA9A(const Ride& curRide); - void UpdateTrackMotionPreUpdate( - Vehicle& car, const Ride& curRide, const RideObjectEntry& rideEntry, const CarEntry* carEntry); -}; -static_assert(sizeof(Vehicle) <= 512); - -void UpdateRotatingDefault(Vehicle& vehicle); -void UpdateRotatingEnterprise(Vehicle& vehicle); - -struct TrainReference -{ - Vehicle* head; - Vehicle* tail; -}; - -enum class MiniGolfState : int16_t -{ - unk0, - unk1, // Unused - unk2, - unk3, - unk4, - unk5, - unk6, -}; - -enum class MiniGolfAnimation : uint8_t -{ - walk, - placeBallDown, - swingLeft, - pickupBall, - jump, - placeBallUp, - puttLeft, - swing, - putt, -}; - -enum BoatHireSubState : uint8_t -{ - rowing, - enteringReturnPosition, -}; - -enum -{ - VEHICLE_VISUAL_DEFAULT, - VEHICLE_VISUAL_FLAT_RIDE_OR_CAR_RIDE, - VEHICLE_VISUAL_LAUNCHED_FREEFALL, - VEHICLE_VISUAL_OBSERVATION_TOWER, - VEHICLE_VISUAL_RIVER_RAPIDS, - VEHICLE_VISUAL_MINI_GOLF_PLAYER, - VEHICLE_VISUAL_MINI_GOLF_BALL, - VEHICLE_VISUAL_REVERSER, - VEHICLE_VISUAL_SPLASH_BOATS_OR_WATER_COASTER, - VEHICLE_VISUAL_ROTO_DROP, - VEHICLE_VISUAL_SPLASH1_EFFECT, - VEHICLE_VISUAL_SPLASH2_EFFECT, - VEHICLE_VISUAL_SPLASH3_EFFECT, - VEHICLE_VISUAL_SPLASH4_EFFECT, - VEHICLE_VISUAL_SPLASH5_EFFECT, - VEHICLE_VISUAL_VIRGINIA_REEL, - VEHICLE_VISUAL_SUBMARINE, - VEHICLE_VISUAL_SPINNING_CARS, -}; - -enum : uint32_t -{ - VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_STATION = 1 << 0, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_1 = 1 << 1, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_2 = 1 << 2, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_3 = 1 << 3, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_ON_LIFT_HILL = 1 << 4, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_5 = 1 << 5, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_DERAILED = 1 << 6, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_COLLISION = 1 << 7, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_8 = 1 << 8, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_9 = 1 << 9, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_VEHICLE_AT_BLOCK_BRAKE = 1 << 10, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_11 = 1 << 11, - VEHICLE_UPDATE_MOTION_TRACK_FLAG_12 = 1 << 12, -}; - -enum -{ - VEHICLE_SOUND2_FLAGS_LIFT_HILL = 1 << 1 // When on a lift hill generate sound -}; - -enum -{ - FRICTION_SOUND_WOOD_SMALL = 1, - FRICTION_SOUND_STEEL = 2, - FRICTION_SOUND_PETROL = 21, - FRICTION_SOUND_TRAIN = 31, - FRICTION_SOUND_WATERSLIDE = 32, - FRICTION_SOUND_WOOD_LARGE = 54, - FRICTION_SOUND_STEEL_SMOOTH = 57, - FRICTION_SOUND_HYBRID = 65, - FRICTION_SOUND_NONE = 255 -}; - -enum class SoundRange : uint8_t -{ - screamsMisc = 0, // Used by rides where the screams should not include rolling sounds. - screamsWoodenRollerCoaster = 1, - screamSteelRollerCoaster = 2, - steamWhistle = 3, - tramBell = 4, - none = 255, -}; - -constexpr uint8_t kVehicleSeatPairFlag = 0x80; -constexpr uint8_t kVehicleSeatNumMask = 0x7F; - -OpenRCT2::TrackMetadata::PitchAndRoll PitchAndRollStart(bool useInvertedSprites, OpenRCT2::TileElement* tileElement); -int32_t GetAccelerationDecrease2(const int32_t velocity, const int32_t totalMass); - -Vehicle* TryGetVehicle(EntityId spriteIndex); -void VehicleUpdateAll(); -void VehicleSoundsUpdate(); -std::optional ride_get_train_index_from_vehicle(const Ride& ride, EntityId spriteIndex); -uint16_t VehicleGetMoveInfoSize(VehicleTrackSubposition trackSubposition, OpenRCT2::TrackElemType type, uint8_t direction); - -void RideUpdateMeasurementsSpecialElements_Default(Ride& ride, OpenRCT2::TrackElemType trackType); -void RideUpdateMeasurementsSpecialElements_MiniGolf(Ride& ride, OpenRCT2::TrackElemType trackType); -void RideUpdateMeasurementsSpecialElements_WaterCoaster(Ride& ride, OpenRCT2::TrackElemType trackType); - -extern Vehicle* gCurrentVehicle; -extern Breakdown _vehicleBreakdown; -extern StationIndex _vehicleStationIndex; -extern uint32_t _vehicleMotionTrackFlags; -extern int32_t _vehicleVelocityF64E08; -extern int32_t _vehicleVelocityF64E0C; -extern int32_t _vehicleUnkF64E10; -extern uint8_t _vehicleF64E2C; -extern Vehicle* _vehicleFrontVehicle; -extern CoordsXYZ _vehicleCurPosition; diff --git a/src/openrct2/ride/VehicleFlags.h b/src/openrct2/ride/VehicleFlags.h new file mode 100644 index 0000000000..ecc8eecfcf --- /dev/null +++ b/src/openrct2/ride/VehicleFlags.h @@ -0,0 +1,45 @@ +/***************************************************************************** + * Copyright (c) 2014-2026 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#pragma once + +#include "../core/FlagHolder.hpp" + +#include + +namespace OpenRCT2 +{ + enum class VehicleFlag : uint8_t + { + onLiftHill, + collisionDisabled, + waitingOnAdjacentStation, + poweredCarInReverse, + readyToDepart, + testing, + // When go-karts are colliding, they have a higher chance of changing lanes + currentlyColliding, + // Used on vehicles when a safety cut-out stops them, such as RCs on a lift hill and powered rides + stoppedBySafetyCutout, + carIsBroken, + trainIsBroken, + stoppedOnHoldingBrake, + // Used on vehicles that can run inverted for extended periods of time, i.e. the Flying, Lay-down and Multi-Dimension + // trains + carIsInverted, + // Set when the vehicle travels backwards through the station for the first time + reverseInclineCompletedLap, + spinningIsLocked, // After passing a rotation toggle track piece this will enable + // OpenRCT2 Flag: Used to override UpdateMotion to move the position of an individual car on a train + moveSingleCar, + crashed, // Car displays as smoke plume + carIsReversed, // Car is displayed running backwards + }; + using VehicleFlags = FlagHolder; +} // namespace OpenRCT2 diff --git a/src/openrct2/ride/VehicleSubpositionData.h b/src/openrct2/ride/VehicleSubpositionData.h index 9921b2548a..280b693dd4 100644 --- a/src/openrct2/ride/VehicleSubpositionData.h +++ b/src/openrct2/ride/VehicleSubpositionData.h @@ -19,7 +19,10 @@ constexpr const size_t VehicleTrackSubpositionSizeDefault = EnumValue(OpenRCT2::TrackElemType::count) * kNumOrthogonalDirections; -struct VehicleInfo; +namespace OpenRCT2 +{ + struct VehicleInfo; +} enum class VehicleTrackSubposition : uint8_t { @@ -50,7 +53,7 @@ enum class VehicleTrackSubposition : uint8_t struct VehicleInfoList { uint16_t size; - const VehicleInfo* info; + const OpenRCT2::VehicleInfo* info; }; extern const VehicleInfoList* const* const gTrackVehicleInfo[EnumValue(VehicleTrackSubposition::count)]; diff --git a/src/openrct2/ride/rtd/coaster/WaterCoaster.h b/src/openrct2/ride/rtd/coaster/WaterCoaster.h index 9255abb37f..8d9aee1504 100644 --- a/src/openrct2/ride/rtd/coaster/WaterCoaster.h +++ b/src/openrct2/ride/rtd/coaster/WaterCoaster.h @@ -105,7 +105,7 @@ constexpr RideTypeDescriptor WaterCoasterRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = nullptr, diff --git a/src/openrct2/ride/rtd/gentle/Circus.h b/src/openrct2/ride/rtd/gentle/Circus.h index 6561840d42..d57789dfbc 100644 --- a/src/openrct2/ride/rtd/gentle/Circus.h +++ b/src/openrct2/ride/rtd/gentle/Circus.h @@ -66,7 +66,7 @@ constexpr RideTypeDescriptor CircusRTD = .MusicUpdateFunction = CircusMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = nullptr, diff --git a/src/openrct2/ride/rtd/gentle/GhostTrain.h b/src/openrct2/ride/rtd/gentle/GhostTrain.h index 69a31bb5ed..0812f377c3 100644 --- a/src/openrct2/ride/rtd/gentle/GhostTrain.h +++ b/src/openrct2/ride/rtd/gentle/GhostTrain.h @@ -89,7 +89,7 @@ constexpr RideTypeDescriptor GhostTrainRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_GhostTrain, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_GhostTrain, }; } // namespace OpenRCT2 // clang-format on diff --git a/src/openrct2/ride/rtd/gentle/Maze.h b/src/openrct2/ride/rtd/gentle/Maze.h index 7811ad0a6b..efb2ceeaef 100644 --- a/src/openrct2/ride/rtd/gentle/Maze.h +++ b/src/openrct2/ride/rtd/gentle/Maze.h @@ -72,7 +72,7 @@ constexpr RideTypeDescriptor MazeRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceMaze, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::maze, .specialType = RtdSpecialType::maze, diff --git a/src/openrct2/ride/rtd/gentle/MiniGolf.h b/src/openrct2/ride/rtd/gentle/MiniGolf.h index cb537724db..2ef4f4e456 100644 --- a/src/openrct2/ride/rtd/gentle/MiniGolf.h +++ b/src/openrct2/ride/rtd/gentle/MiniGolf.h @@ -78,7 +78,7 @@ constexpr RideTypeDescriptor MiniGolfRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = nullptr, diff --git a/src/openrct2/ride/rtd/gentle/SpiralSlide.h b/src/openrct2/ride/rtd/gentle/SpiralSlide.h index 2ebf5e3d11..6d14a871b3 100644 --- a/src/openrct2/ride/rtd/gentle/SpiralSlide.h +++ b/src/openrct2/ride/rtd/gentle/SpiralSlide.h @@ -76,7 +76,7 @@ constexpr RideTypeDescriptor SpiralSlideRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceSpiralSlide, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = updateSpiralSlide, diff --git a/src/openrct2/ride/rtd/thrill/Enterprise.h b/src/openrct2/ride/rtd/thrill/Enterprise.h index 55e4c22ecb..03922f079a 100644 --- a/src/openrct2/ride/rtd/thrill/Enterprise.h +++ b/src/openrct2/ride/rtd/thrill/Enterprise.h @@ -70,7 +70,7 @@ constexpr RideTypeDescriptor EnterpriseRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationEnterprise, .specialType = RtdSpecialType::enterprise, }; diff --git a/src/openrct2/ride/rtd/thrill/MotionSimulator.h b/src/openrct2/ride/rtd/thrill/MotionSimulator.h index 73b4227533..09e909c9eb 100644 --- a/src/openrct2/ride/rtd/thrill/MotionSimulator.h +++ b/src/openrct2/ride/rtd/thrill/MotionSimulator.h @@ -68,7 +68,7 @@ constexpr RideTypeDescriptor MotionSimulatorRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = nullptr, diff --git a/src/openrct2/ride/rtd/transport/Chairlift.h b/src/openrct2/ride/rtd/transport/Chairlift.h index 19255eb02b..28cb5518f1 100644 --- a/src/openrct2/ride/rtd/transport/Chairlift.h +++ b/src/openrct2/ride/rtd/transport/Chairlift.h @@ -87,7 +87,7 @@ constexpr RideTypeDescriptor ChairliftRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_Default, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_Default, .GetGuestWaypointLocation = GetGuestWaypointLocationDefault, .ConstructionWindowContext = RideConstructionWindowContext::standard, .RideUpdate = updateChairlift, diff --git a/src/openrct2/ride/rtd/water/LogFlume.h b/src/openrct2/ride/rtd/water/LogFlume.h index 910c5b88ae..30f9cb262e 100644 --- a/src/openrct2/ride/rtd/water/LogFlume.h +++ b/src/openrct2/ride/rtd/water/LogFlume.h @@ -84,7 +84,7 @@ constexpr RideTypeDescriptor LogFlumeRTD = .MusicUpdateFunction = DefaultMusicUpdate, .Classification = RideClassification::ride, .UpdateLeaveEntrance = PeepUpdateRideLeaveEntranceDefault, - .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAjustment_LogFlume, + .SpecialElementRatingAdjustment = SpecialTrackElementRatingsAdjustment_LogFlume, }; } // namespace OpenRCT2 // clang-format on diff --git a/src/openrct2/scripting/bindings/ride/ScRide.cpp b/src/openrct2/scripting/bindings/ride/ScRide.cpp index d0cc7d78b5..0b04b64997 100644 --- a/src/openrct2/scripting/bindings/ride/ScRide.cpp +++ b/src/openrct2/scripting/bindings/ride/ScRide.cpp @@ -102,7 +102,7 @@ namespace OpenRCT2::Scripting Ride* ScRide::GetRide(JSValue thisVal) { RideData* data = GetRideData(thisVal); - return ::GetRide(data->_rideId); + return OpenRCT2::GetRide(data->_rideId); } JSValue ScRide::id_get(JSContext* ctx, JSValue thisVal) diff --git a/src/openrct2/scripting/bindings/ride/ScRideStation.cpp b/src/openrct2/scripting/bindings/ride/ScRideStation.cpp index 11f9ef247e..79981bf2a0 100644 --- a/src/openrct2/scripting/bindings/ride/ScRideStation.cpp +++ b/src/openrct2/scripting/bindings/ride/ScRideStation.cpp @@ -49,7 +49,7 @@ namespace OpenRCT2::Scripting RideStation* ScRideStation::GetRideStation(JSValue thisVal) { RideStationData* data = GetRideStationData(thisVal); - auto ride = ::GetRide(data->_rideId); + auto ride = OpenRCT2::GetRide(data->_rideId); if (ride != nullptr) { if (data->_stationIndex.ToUnderlying() < std::size(ride->getStations())) diff --git a/src/openrct2/scripting/bindings/ride/ScTrackSegment.cpp b/src/openrct2/scripting/bindings/ride/ScTrackSegment.cpp index 8d49943bca..9926b697f4 100644 --- a/src/openrct2/scripting/bindings/ride/ScTrackSegment.cpp +++ b/src/openrct2/scripting/bindings/ride/ScTrackSegment.cpp @@ -22,7 +22,7 @@ using namespace OpenRCT2::Scripting; using namespace OpenRCT2::TrackMetadata; -static JSValue VehicleInfoToJSValue(JSContext* ctx, const VehicleInfo& value) +static JSValue VehicleInfoToJSValue(JSContext* ctx, const OpenRCT2::VehicleInfo& value) { JSValue obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "x", JS_NewInt32(ctx, value.x)); diff --git a/src/openrct2/world/Entrance.cpp b/src/openrct2/world/Entrance.cpp index 5ade4db5d9..060b5f91de 100644 --- a/src/openrct2/world/Entrance.cpp +++ b/src/openrct2/world/Entrance.cpp @@ -87,7 +87,7 @@ void ParkEntranceReset() getGameState().park.entrances.clear(); } -void RideEntranceExitPlaceProvisionalGhost() +void OpenRCT2::RideEntranceExitPlaceProvisionalGhost() { if (_currentTrackSelectionFlags.has(TrackSelectionFlag::entranceOrExit)) { @@ -97,7 +97,7 @@ void RideEntranceExitPlaceProvisionalGhost() } } -void RideEntranceExitRemoveGhost() +void OpenRCT2::RideEntranceExitRemoveGhost() { if (_currentTrackSelectionFlags.has(TrackSelectionFlag::entranceOrExit)) { @@ -114,7 +114,7 @@ void RideEntranceExitRemoveGhost() * * rct2: 0x006CA28C */ -money64 RideEntranceExitPlaceGhost( +money64 OpenRCT2::RideEntranceExitPlaceGhost( const Ride& ride, const CoordsXY& entranceExitCoords, Direction direction, int32_t placeType, StationIndex stationNum) { RideConstructionRemoveGhosts();