diff --git a/src/cargotype.cpp b/src/cargotype.cpp index 3b5bad3205..2e232d6ed9 100644 --- a/src/cargotype.cpp +++ b/src/cargotype.cpp @@ -19,6 +19,8 @@ #include "table/strings.h" #include "table/cargo_const.h" +#include + #include "safeguards.h" CargoSpec CargoSpec::array[NUM_CARGO]; @@ -257,3 +259,39 @@ uint64_t CargoSpec::WeightOfNUnitsInTrain(uint32_t n) const if (this->is_freight) n *= _settings_game.vehicle.freight_trains; return this->WeightOfNUnits(n); } + +/** + * Build comma-separated cargo acceptance string. + * @param acceptance CargoArray filled with accepted cargo. + * @param label Label to prefix cargo acceptance list. + * @return String of accepted cargo, or nullopt if no cargo is accepted. + */ +std::optional BuildCargoAcceptanceString(const CargoArray &acceptance, StringID label) +{ + /* Cargo acceptance is displayed in a extra multiline */ + std::stringstream line; + line << GetString(label); + + bool found = false; + for (const CargoSpec *cs : _sorted_cargo_specs) { + CargoID cid = cs->Index(); + if (acceptance[cid] > 0) { + /* Add a comma between each item. */ + if (found) line << ", "; + found = true; + + /* If the accepted value is less than 8, show it in 1/8:ths */ + if (acceptance[cid] < 8) { + SetDParam(0, acceptance[cid]); + SetDParam(1, cs->name); + line << GetString(STR_LAND_AREA_INFORMATION_CARGO_EIGHTS); + } else { + line << GetString(cs->name); + } + } + } + + if (found) return line.str(); + + return std::nullopt; +} diff --git a/src/cargotype.h b/src/cargotype.h index b204a5c60c..335d531798 100644 --- a/src/cargotype.h +++ b/src/cargotype.h @@ -214,6 +214,8 @@ void SetupCargoForClimate(LandscapeID l); bool IsDefaultCargo(CargoID cid); void BuildCargoLabelMap(); +std::optional BuildCargoAcceptanceString(const CargoArray &acceptance, StringID label); + inline CargoID GetCargoIDByLabel(CargoLabel label) { auto found = CargoSpec::label_map.find(label); diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index f77caa42e0..9cd2714b0b 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -307,29 +307,9 @@ public: } /* Cargo acceptance is displayed in a extra multiline */ - std::stringstream line; - line << GetString(STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED); - - bool found = false; - for (const CargoSpec *cs : _sorted_cargo_specs) { - CargoID cid = cs->Index(); - if (acceptance[cid] > 0) { - /* Add a comma between each item. */ - if (found) line << ", "; - found = true; - - /* If the accepted value is less than 8, show it in 1/8:ths */ - if (acceptance[cid] < 8) { - SetDParam(0, acceptance[cid]); - SetDParam(1, cs->name); - line << GetString(STR_LAND_AREA_INFORMATION_CARGO_EIGHTS); - } else { - line << GetString(cs->name); - } - } - } - if (found) { - this->cargo_acceptance = line.str(); + auto line = BuildCargoAcceptanceString(acceptance, STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED); + if (line.has_value()) { + this->cargo_acceptance = std::move(*line); } else { this->cargo_acceptance.clear(); }