OpenTTD Source 20261112-master-gbcbec5e63f
vehicle_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "debug.h"
12#include "company_func.h"
13#include "gui.h"
14#include "textbuf_gui.h"
15#include "command_func.h"
16#include "vehicle_gui.h"
17#include "vehicle_gui_base.h"
18#include "viewport_func.h"
19#include "newgrf_text.h"
20#include "newgrf_debug.h"
21#include "roadveh.h"
22#include "train.h"
23#include "aircraft.h"
24#include "depot_map.h"
25#include "group_gui.h"
26#include "strings_func.h"
27#include "vehicle_func.h"
28#include "autoreplace_gui.h"
29#include "string_func.h"
30#include "dropdown_type.h"
31#include "dropdown_func.h"
32#include "timetable.h"
36#include "company_base.h"
37#include "engine_func.h"
38#include "station_base.h"
39#include "tilehighlight_func.h"
40#include "zoom_func.h"
41#include "depot_cmd.h"
42#include "vehicle_cmd.h"
43#include "order_cmd.h"
44#include "roadveh_cmd.h"
45#include "train_cmd.h"
46#include "hotkeys.h"
47#include "group_cmd.h"
48
49#include "table/strings.h"
50
51#include "safeguards.h"
52
53
55static std::array<Sorting, BaseVehicleListWindow::GB_END> _sorting{};
56
57static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNumberSorter;
58static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNameSorter;
59static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleAgeSorter;
60static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitThisYearSorter;
61static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitLastYearSorter;
62static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleCargoSorter;
63static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleReliabilitySorter;
64static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleMaxSpeedSorter;
65static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleModelSorter;
66static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleValueSorter;
67static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleLengthSorter;
68static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimeToLiveSorter;
69static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimetableDelaySorter;
70static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupLengthSorter;
71static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitThisYearSorter;
72static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitLastYearSorter;
73static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitThisYearSorter;
74static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitLastYearSorter;
75
77template <BaseVehicleListWindow::VehicleIndividualSortFunction func>
79{
80 return func(*(a.vehicles_begin), *(b.vehicles_begin));
81}
82
83const std::initializer_list<BaseVehicleListWindow::VehicleGroupSortFunction * const> BaseVehicleListWindow::vehicle_group_none_sorter_funcs = {
97};
98
99const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_none_sorter_names_calendar = {
100 STR_SORT_BY_NUMBER,
101 STR_SORT_BY_NAME,
102 STR_SORT_BY_AGE,
103 STR_SORT_BY_PROFIT_THIS_YEAR,
104 STR_SORT_BY_PROFIT_LAST_YEAR,
105 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
106 STR_SORT_BY_RELIABILITY,
107 STR_SORT_BY_MAX_SPEED,
108 STR_SORT_BY_MODEL,
109 STR_SORT_BY_VALUE,
110 STR_SORT_BY_LENGTH,
111 STR_SORT_BY_LIFE_TIME,
112 STR_SORT_BY_TIMETABLE_DELAY,
113};
114
115const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_none_sorter_names_wallclock = {
116 STR_SORT_BY_NUMBER,
117 STR_SORT_BY_NAME,
118 STR_SORT_BY_AGE,
119 STR_SORT_BY_PROFIT_THIS_PERIOD,
120 STR_SORT_BY_PROFIT_LAST_PERIOD,
121 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
122 STR_SORT_BY_RELIABILITY,
123 STR_SORT_BY_MAX_SPEED,
124 STR_SORT_BY_MODEL,
125 STR_SORT_BY_VALUE,
126 STR_SORT_BY_LENGTH,
127 STR_SORT_BY_LIFE_TIME,
128 STR_SORT_BY_TIMETABLE_DELAY,
129};
130
131const std::initializer_list<BaseVehicleListWindow::VehicleGroupSortFunction * const> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_funcs = {
132 &VehicleGroupLengthSorter,
133 &VehicleGroupTotalProfitThisYearSorter,
134 &VehicleGroupTotalProfitLastYearSorter,
135 &VehicleGroupAverageProfitThisYearSorter,
136 &VehicleGroupAverageProfitLastYearSorter,
137};
138
139const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names_calendar = {
140 STR_SORT_BY_NUM_VEHICLES,
141 STR_SORT_BY_TOTAL_PROFIT_THIS_YEAR,
142 STR_SORT_BY_TOTAL_PROFIT_LAST_YEAR,
143 STR_SORT_BY_AVERAGE_PROFIT_THIS_YEAR,
144 STR_SORT_BY_AVERAGE_PROFIT_LAST_YEAR,
145};
146
147const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names_wallclock = {
148 STR_SORT_BY_NUM_VEHICLES,
149 STR_SORT_BY_TOTAL_PROFIT_THIS_PERIOD,
150 STR_SORT_BY_TOTAL_PROFIT_LAST_PERIOD,
151 STR_SORT_BY_AVERAGE_PROFIT_THIS_PERIOD,
152 STR_SORT_BY_AVERAGE_PROFIT_LAST_PERIOD,
153};
154
155const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_by_names = {
156 STR_GROUP_BY_NONE,
157 STR_GROUP_BY_SHARED_ORDERS,
158};
159
162 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
163 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
164 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
165 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
166};
167
168BaseVehicleListWindow::BaseVehicleListWindow(WindowDesc &desc, const VehicleListIdentifier &vli) : Window(desc), vli(vli)
169{
170 this->vehicle_sel = VehicleID::Invalid();
171 this->grouping = _grouping[vli.type][vli.vtype];
172 this->UpdateSortingFromGrouping();
173}
174
175std::span<const StringID> BaseVehicleListWindow::GetVehicleSorterNames() const
176{
177 switch (this->grouping) {
178 case GB_NONE:
179 return TimerGameEconomy::UsingWallclockUnits() ? vehicle_group_none_sorter_names_wallclock : vehicle_group_none_sorter_names_calendar;
180 case GB_SHARED_ORDERS:
181 return TimerGameEconomy::UsingWallclockUnits() ? vehicle_group_shared_orders_sorter_names_wallclock : vehicle_group_shared_orders_sorter_names_calendar;
182 default:
183 NOT_REACHED();
184 }
185}
186
193{
194 if (number >= 10000) return 5;
195 if (number >= 1000) return 4;
196 if (number >= 100) return 3;
197
198 /*
199 * When the smallest unit number is less than 10, it is
200 * quite likely that it will expand to become more than
201 * 10 quite soon.
202 */
203 return 2;
204}
205
212{
213 uint unitnumber = 0;
214 for (const Vehicle *v : vehicles) {
215 unitnumber = std::max<uint>(unitnumber, v->unitnumber);
216 }
217
218 return CountDigitsForAllocatingSpace(unitnumber);
219}
220
221void BaseVehicleListWindow::BuildVehicleList()
222{
223 if (!this->vehgroups.NeedRebuild()) return;
224
225 Debug(Facility::Misc, Severity::Notice, "Building vehicle list type {} for company {} given index {}", this->vli.type, this->vli.company, this->vli.index);
226
227 this->vehgroups.clear();
228
229 GenerateVehicleSortList(&this->vehicles, this->vli);
230
231 CargoTypes used{};
232 for (const Vehicle *v : this->vehicles) {
233 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
234 if (u->cargo_cap > 0) used.Set(u->cargo_type);
235 }
236 }
237 this->used_cargoes = used;
238
239 if (this->grouping == GB_NONE) {
240 uint max_unitnumber = 0;
241 for (auto it = this->vehicles.begin(); it != this->vehicles.end(); ++it) {
242 this->vehgroups.emplace_back(it, it + 1);
243
244 max_unitnumber = std::max<uint>(max_unitnumber, (*it)->unitnumber);
245 }
246 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_unitnumber);
247 } else {
248 /* Sort by the primary vehicle; we just want all vehicles that share the same orders to form a contiguous range. */
249 std::stable_sort(this->vehicles.begin(), this->vehicles.end(), [](const Vehicle * const &u, const Vehicle * const &v) {
250 return u->FirstShared() < v->FirstShared();
251 });
252
253 uint max_num_vehicles = 0;
254
255 VehicleList::const_iterator begin = this->vehicles.begin();
256 while (begin != this->vehicles.end()) {
257 VehicleList::const_iterator end = std::find_if_not(begin, this->vehicles.cend(), [first_shared = (*begin)->FirstShared()](const Vehicle * const &v) {
258 return v->FirstShared() == first_shared;
259 });
260
261 this->vehgroups.emplace_back(begin, end);
262
263 max_num_vehicles = std::max<uint>(max_num_vehicles, static_cast<uint>(end - begin));
264
265 begin = end;
266 }
267
268 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_num_vehicles);
269 }
270 this->FilterVehicleList();
271
272 this->vehgroups.RebuildDone();
273 this->vscroll->SetCount(this->vehgroups.size());
274}
275
283static bool CargoFilterSingle(const Vehicle *v, const CargoType cargo_type)
284{
285 if (cargo_type == CargoFilterCriteria::CF_ANY) {
286 return true;
287 } else if (cargo_type == CargoFilterCriteria::CF_NONE) {
288 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
289 if (w->cargo_cap > 0) {
290 return false;
291 }
292 }
293 return true;
294 } else if (cargo_type == CargoFilterCriteria::CF_FREIGHT) {
295 bool have_capacity = false;
296 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
297 if (w->cargo_cap > 0) {
298 if (IsCargoInClass(w->cargo_type, CargoClass::Passengers)) {
299 return false;
300 } else {
301 have_capacity = true;
302 }
303 }
304 }
305 return have_capacity;
306 } else {
307 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
308 if (w->cargo_cap > 0 && w->cargo_type == cargo_type) {
309 return true;
310 }
311 }
312 return false;
313 }
314}
315
323static bool CargoFilter(const GUIVehicleGroup *vehgroup, const CargoType cargo_type)
324{
325 auto it = vehgroup->vehicles_begin;
326
327 /* Check if any vehicle in the group matches; if so, the whole group does. */
328 for (; it != vehgroup->vehicles_end; it++) {
329 if (CargoFilterSingle(*it, cargo_type)) return true;
330 }
331
332 return false;
333}
334
340{
341 return IsShiftPressed() && IsCtrlPressed();
342}
343
351void AddCargoIconOverlay(std::vector<CargoIconOverlay> &overlays, int x, int width, const Vehicle *v)
352{
353 bool rtl = _current_text_dir == TD_RTL;
354 if (!v->IsArticulatedPart() || v->cargo_type != v->Previous()->cargo_type) {
355 /* Add new overlay slot. */
356 overlays.emplace_back(rtl ? x - width : x, rtl ? x : x + width, v->cargo_type, v->cargo_cap);
357 } else {
358 /* This is an articulated part with the same cargo type, adjust left or right of last overlay slot. */
359 if (rtl) {
360 overlays.back().left -= width;
361 } else {
362 overlays.back().right += width;
363 }
364 overlays.back().cargo_cap += v->cargo_cap;
365 }
366}
367
374void DrawCargoIconOverlay(int x, int y, CargoType cargo_type)
375{
376 if (!ShowCargoIconOverlay()) return;
377 if (!IsValidCargoType(cargo_type)) return;
378
379 const CargoSpec *cs = CargoSpec::Get(cargo_type);
380
381 SpriteID spr = cs->GetCargoIcon();
382 if (spr == 0) return;
383
384 Dimension d = GetSpriteSize(spr);
385 d.width /= 2;
386 d.height /= 2;
387 int one = ScaleGUITrad(1);
388
389 /* Draw the cargo icon in black shifted 4 times to create the outline. */
390 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width - one, y - d.height);
391 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width + one, y - d.height);
392 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width, y - d.height - one);
393 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width, y - d.height + one);
394 /* Draw the cargo icon normally. */
395 DrawSprite(spr, PAL_NONE, x - d.width, y - d.height);
396}
397
403void DrawCargoIconOverlays(std::span<const CargoIconOverlay> overlays, int y)
404{
405 for (const auto &cio : overlays) {
406 if (cio.cargo_cap == 0) continue;
407 DrawCargoIconOverlay((cio.left + cio.right) / 2, y, cio.cargo_type);
408 }
409}
410
411static GUIVehicleGroupList::FilterFunction * const _vehicle_group_filter_funcs[] = {
413};
414
420{
421 if (this->cargo_filter_criteria != cargo_type) {
422 this->cargo_filter_criteria = cargo_type;
423 /* Deactivate filter if criteria is 'Show All', activate it otherwise. */
424 this->vehgroups.SetFilterState(this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY);
425 this->vehgroups.SetFilterType(0);
426 this->vehgroups.ForceRebuild();
427 }
428}
429
434{
436 this->vehgroups.SetFilterFuncs(_vehicle_group_filter_funcs);
437 this->vehgroups.SetFilterState(this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY);
438}
439
444{
445 this->vehgroups.Filter(this->cargo_filter_criteria);
446 if (this->vehicles.empty()) {
447 /* No vehicle passed through the filter, invalidate the previously selected vehicle */
448 this->vehicle_sel = VehicleID::Invalid();
449 } else if (this->vehicle_sel != VehicleID::Invalid() && std::ranges::find(this->vehicles, Vehicle::Get(this->vehicle_sel)) == this->vehicles.end()) { // previously selected engine didn't pass the filter, remove selection
450 this->vehicle_sel = VehicleID::Invalid();
451 }
452}
453
461Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_create)
462{
463 Dimension d = {0, 0};
464
465 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
466 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
467 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
468
469 if (show_group) {
470 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
471 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
472 } else if (show_create) {
473 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_CREATE_GROUP));
474 }
475
476 return d;
477}
478
480{
481 this->order_arrow_width = std::max(GetStringBoundingBox(STR_JUST_LEFT_ARROW, FontSize::Small).width, GetStringBoundingBox(STR_JUST_RIGHT_ARROW, FontSize::Small).width);
482 this->SetCargoFilterArray();
483}
484
485StringID BaseVehicleListWindow::GetCargoFilterLabel(CargoType cargo_type) const
486{
487 switch (cargo_type) {
488 case CargoFilterCriteria::CF_ANY: return STR_CARGO_TYPE_FILTER_ALL;
489 case CargoFilterCriteria::CF_FREIGHT: return STR_CARGO_TYPE_FILTER_FREIGHT;
490 case CargoFilterCriteria::CF_NONE: return STR_CARGO_TYPE_FILTER_NONE;
491 default: return CargoSpec::Get(cargo_type)->name;
492 }
493}
494
501{
502 DropDownList list;
503
504 /* Add item for disabling filtering. */
506 /* Add item for freight (i.e. vehicles with cargo capacity and with no passenger capacity). */
508 /* Add item for vehicles not carrying anything, e.g. train engines. */
510
511 /* Add cargos */
513 for (const CargoSpec *cs : _sorted_cargo_specs) {
514 if (!full && !this->used_cargoes.Test(cs->Index())) continue;
515 list.push_back(MakeDropDownListIconItem(d, cs->GetCargoIcon(), PAL_NONE, cs->name, cs->Index(), false, !this->used_cargoes.Test(cs->Index())));
516 }
517
518 return list;
519}
520
528DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_create)
529{
530 DropDownList list;
531
532 /* Autoreplace actions. */
533 if (show_autoreplace) {
534 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE));
535 list.push_back(MakeDropDownListDividerItem());
536 }
537
538 /* Group actions. */
539 if (show_group) {
540 list.push_back(MakeDropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED));
541 list.push_back(MakeDropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL));
542 list.push_back(MakeDropDownListDividerItem());
543 } else if (show_create) {
544 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_CREATE_GROUP, ADI_CREATE_GROUP));
545 list.push_back(MakeDropDownListDividerItem());
546 }
547
548 /* Depot actions. */
549 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE));
550 list.push_back(MakeDropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT));
551
552 return list;
553}
554
556static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
557
558void BaseVehicleListWindow::SortVehicleList()
559{
560 if (this->vehgroups.Sort()) return;
561
562 /* invalidate cached values for name sorter - vehicle names could change */
563 _last_vehicle[0] = _last_vehicle[1] = nullptr;
564}
565
566void DepotSortList(VehicleList *list)
567{
568 if (list->size() < 2) return;
569 std::sort(list->begin(), list->end(), &VehicleNumberSorter);
570}
571
580static void DrawVehicleProfitButton(TimerGameEconomy::Date age, Money display_profit_last_year, uint num_vehicles, int x, int y)
581{
582 SpriteID spr;
583
584 /* draw profit-based coloured icons */
585 if (age <= VEHICLE_PROFIT_MIN_AGE) {
586 spr = SPR_PROFIT_NA;
587 } else if (display_profit_last_year < 0) {
588 spr = SPR_PROFIT_NEGATIVE;
589 } else if (display_profit_last_year < VEHICLE_PROFIT_THRESHOLD * num_vehicles) {
590 spr = SPR_PROFIT_SOME;
591 } else {
592 spr = SPR_PROFIT_LOT;
593 }
594 DrawSprite(spr, PAL_NONE, x, y);
595}
596
598static const uint MAX_REFIT_CYCLE = 256;
599
609uint8_t GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoType dest_cargo_type)
610{
611 v_from = v_from->GetFirstEnginePart();
612 v_for = v_for->GetFirstEnginePart();
613
614 /* Create a list of subtypes used by the various parts of v_for */
615 static std::vector<StringID> subtypes;
616 subtypes.clear();
617 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
618 const Engine *e_from = v_from->GetEngine();
619 if (!e_from->CanCarryCargo() || !e_from->info.callback_mask.Test(VehicleCallbackMask::CargoSuffix)) continue;
620 include(subtypes, GetCargoSubtypeText(v_from));
621 }
622
623 uint8_t ret_refit_cyc = 0;
624 bool success = false;
625 if (!subtypes.empty()) {
626 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
627 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
628 const Engine *e = v->GetEngine();
629 if (!e->CanCarryCargo() || !e->info.callback_mask.Test(VehicleCallbackMask::CargoSuffix)) continue;
630 if (!e->info.refit_mask.Test(dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
631
632 CargoType old_cargo_type = v->cargo_type;
633 uint8_t old_cargo_subtype = v->cargo_subtype;
634
635 /* Set the 'destination' cargo */
636 v->cargo_type = dest_cargo_type;
637
638 /* Cycle through the refits */
639 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
640 v->cargo_subtype = refit_cyc;
641
642 /* Make sure we don't pick up anything cached. */
643 v->First()->InvalidateNewGRFCache();
644 v->InvalidateNewGRFCache();
645
646 StringID subtype = GetCargoSubtypeText(v);
647 if (subtype == STR_EMPTY) break;
648
649 if (std::ranges::find(subtypes, subtype) == subtypes.end()) continue;
650
651 /* We found something matching. */
652 ret_refit_cyc = refit_cyc;
653 success = true;
654 break;
655 }
656
657 /* Reset the vehicle's cargo type */
658 v->cargo_type = old_cargo_type;
659 v->cargo_subtype = old_cargo_subtype;
660
661 /* Make sure we don't taint the vehicle. */
662 v->First()->InvalidateNewGRFCache();
663 v->InvalidateNewGRFCache();
664
665 if (success) break;
666 }
667 }
668
669 return ret_refit_cyc;
670}
671
675 uint8_t subtype;
677
683 inline bool operator == (const RefitOption &other) const
684 {
685 return other.cargo == this->cargo && other.string == this->string;
686 }
687};
688
689using RefitOptions = std::map<CargoType, std::vector<RefitOption>, CargoTypeComparator>;
690
700static void DrawVehicleRefitWindow(const RefitOptions &refits, const RefitOption *sel, uint pos, uint rows, uint delta, const Rect &r)
701{
702 Rect ir = r.Shrink(WidgetDimensions::scaled.matrix);
703 uint current = 0;
704
705 bool rtl = _current_text_dir == TD_RTL;
706 uint iconwidth = std::max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
707 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
709
710 int iconleft = rtl ? ir.right - iconwidth : ir.left;
711 int iconcenter = rtl ? ir.right - iconwidth / 2 : ir.left + iconwidth / 2;
712 int iconinner = rtl ? ir.right - iconwidth : ir.left + iconwidth;
713
714 Rect tr = ir.Indent(iconwidth + WidgetDimensions::scaled.hsep_wide, rtl);
715
716 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
717 for (const auto &pair : refits) {
718 bool has_subtypes = pair.second.size() > 1;
719 for (const RefitOption &refit : pair.second) {
720 if (current >= pos + rows) break;
721
722 /* Hide subtypes if selected cargo type does not match */
723 if ((sel == nullptr || sel->cargo != refit.cargo) && refit.subtype != UINT8_MAX) continue;
724
725 /* Refit options with a position smaller than pos don't have to be drawn. */
726 if (current < pos) {
727 current++;
728 continue;
729 }
730
731 if (has_subtypes) {
732 if (refit.subtype != UINT8_MAX) {
733 /* Draw tree lines */
734 int ycenter = tr.top + GetCharacterHeight(FontSize::Normal) / 2;
735 GfxDrawLine(iconcenter, tr.top - WidgetDimensions::scaled.matrix.top, iconcenter, (&refit == &pair.second.back()) ? ycenter : tr.top - WidgetDimensions::scaled.matrix.top + delta - 1, linecolour);
736 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
737 } else {
738 /* Draw expand/collapse icon */
739 DrawSprite((sel != nullptr && sel->cargo == refit.cargo) ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, tr.top + (GetCharacterHeight(FontSize::Normal) - iconheight) / 2);
740 }
741 }
742
743 TextColour colour = (sel != nullptr && sel->cargo == refit.cargo && sel->subtype == refit.subtype) ? TextColour::White : TextColour::Black;
744 /* Get the cargo name. */
745 DrawString(tr, GetString(STR_JUST_STRING_STRING, CargoSpec::Get(refit.cargo)->name, refit.string), colour);
746
747 tr.top += delta;
748 current++;
749 }
750 }
751}
752
754struct RefitWindow : public Window {
755 const RefitOption *selected_refit = nullptr;
759 Scrollbar *vscroll = nullptr;
760 Scrollbar *hscroll = nullptr;
762 int sprite_left = 0;
763 int sprite_right = 0;
764 uint vehicle_margin = 0;
765 int click_x = 0;
767 uint8_t num_vehicles = 0;
768 bool auto_refit = false;
769
774 {
775 /* Store the currently selected RefitOption. */
776 std::optional<RefitOption> current_refit_option;
777 if (this->selected_refit != nullptr) current_refit_option = *(this->selected_refit);
778 this->selected_refit = nullptr;
779
780 this->refit_list.clear();
782
783 /* Check only the selected vehicles. */
784 VehicleSet vehicles_to_refit;
785 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
786
787 do {
788 if (v->type == VehicleType::Train && std::ranges::find(vehicles_to_refit, v->index) == vehicles_to_refit.end()) continue;
789 const Engine *e = v->GetEngine();
790 CargoTypes cmask = e->info.refit_mask;
791 VehicleCallbackMasks callback_mask = e->info.callback_mask;
792
793 /* Skip this engine if it does not carry anything */
794 if (!e->CanCarryCargo()) continue;
795 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
796 if (this->auto_refit && !e->info.misc_flags.Test(EngineMiscFlag::AutoRefit)) continue;
797
798 /* Loop through all cargoes in the refit mask */
799 for (const auto &cs : _sorted_cargo_specs) {
800 CargoType cargo_type = cs->Index();
801 /* Skip cargo type if it's not listed */
802 if (!cmask.Test(cargo_type)) continue;
803
804 auto &list = this->refit_list[cargo_type];
805 bool first_vehicle = list.empty();
806 if (first_vehicle) {
807 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
808 list.emplace_back(cargo_type, UINT8_MAX, STR_EMPTY);
809 }
810
811 /* Check the vehicle's callback mask for cargo suffixes.
812 * This is not supported for ordered refits, since subtypes only have a meaning
813 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
814 * autoreplace, autorenew, clone, order restoration, ... */
815 if (this->order == INVALID_VEH_ORDER_ID && callback_mask.Test(VehicleCallbackMask::CargoSuffix)) {
816 /* Make a note of the original cargo type. It has to be
817 * changed to test the cargo & subtype... */
818 CargoType temp_cargo = v->cargo_type;
819 uint8_t temp_subtype = v->cargo_subtype;
820
821 v->cargo_type = cargo_type;
822
823 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
824 v->cargo_subtype = refit_cyc;
825
826 /* Make sure we don't pick up anything cached. */
829
830 StringID subtype = GetCargoSubtypeText(v);
831
832 if (first_vehicle) {
833 /* Append new subtype (don't add duplicates though) */
834 if (subtype == STR_EMPTY) break;
835
836 RefitOption option{cargo_type, static_cast<uint8_t>(refit_cyc), subtype};
837 include(list, option);
838 } else {
839 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
840 if (subtype == STR_EMPTY) {
841 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
842 /* UINT8_MAX item is in front, other subtypes are sorted. So just truncate the list in the right spot */
843 for (uint i = 1; i < list.size(); i++) {
844 if (list[i].subtype >= refit_cyc) {
845 list.erase(list.begin() + i, list.end());
846 break;
847 }
848 }
849 break;
850 } else {
851 /* Check whether the subtype matches with the subtype of earlier vehicles. */
852 uint pos = 1;
853 while (pos < list.size() && list[pos].subtype != refit_cyc) pos++;
854 if (pos < list.size() && list[pos].string != subtype) {
855 /* String mismatch, remove item keeping the order */
856 list.erase(list.begin() + pos);
857 }
858 }
859 }
860 }
861
862 /* Reset the vehicle's cargo type */
863 v->cargo_type = temp_cargo;
864 v->cargo_subtype = temp_subtype;
865
866 /* And make sure we haven't tainted the cache */
869 }
870 }
871 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
872
873 /* Restore the previously selected RefitOption. */
874 if (current_refit_option.has_value()) {
875 for (const auto &pair : this->refit_list) {
876 for (const auto &refit : pair.second) {
877 if (refit.cargo == current_refit_option->cargo && refit.subtype == current_refit_option->subtype) {
878 this->selected_refit = &refit;
879 break;
880 }
881 }
882 if (this->selected_refit != nullptr) break;
883 }
884 }
885
886 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
887 }
888
893 {
894 size_t scroll_row = 0;
895 size_t rows = 0;
896 CargoType cargo = this->selected_refit == nullptr ? INVALID_CARGO : this->selected_refit->cargo;
897
898 for (const auto &pair : this->refit_list) {
899 if (pair.first == cargo) {
900 /* selected_refit points to an element in the vector so no need to search for it. */
901 scroll_row = rows + (this->selected_refit - pair.second.data());
902 rows += pair.second.size();
903 } else {
904 rows++; /* Unselected cargo type is collapsed into one row. */
905 }
906 }
907
908 this->vscroll->SetCount(rows);
909 this->vscroll->ScrollTowards(static_cast<int>(scroll_row));
910 }
911
916 void SetSelection(uint click_row)
917 {
918 uint row = 0;
919
920 for (const auto &pair : refit_list) {
921 for (const RefitOption &refit : pair.second) {
922 if (row == click_row) {
923 this->selected_refit = &refit;
924 return;
925 }
926 row++;
927 /* If this cargo type is not already selected then its subtypes are not visible, so skip the rest. */
928 if (this->selected_refit == nullptr || this->selected_refit->cargo != refit.cargo) break;
929 }
930 }
931
932 /* No selection made */
933 this->selected_refit = nullptr;
934 }
935
936 RefitWindow(WindowDesc &desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
937 {
938 this->auto_refit = auto_refit;
939 this->order = order;
940 this->CreateNestedTree();
941
942 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
943 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
944 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->SetToolTip(STR_REFIT_TRAIN_LIST_TOOLTIP + to_underlying(v->type));
945 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->SetToolTip(STR_REFIT_TRAIN_LIST_TOOLTIP + to_underlying(v->type));
947 nwi->SetStringTip(STR_REFIT_TRAIN_REFIT_BUTTON + to_underlying(v->type), STR_REFIT_TRAIN_REFIT_TOOLTIP + to_underlying(v->type));
949 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->SetToolTip((v->type == VehicleType::Train) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL);
950
951 this->FinishInitNested(v->index);
952 this->owner = v->owner;
953
954 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
955 }
956
957 void OnInit() override
958 {
959 if (this->hscroll != nullptr) {
960 this->hscroll->SetStepSize(GetCharacterHeight(FontSize::Normal)); // Speed up horizontal scrollbar
961 }
962
963 /* (Re)build the refit list */
965 }
966
967 void OnPaint() override
968 {
969 /* Determine amount of items for scroller. */
970 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
971
972 /* Calculate sprite position. */
974 int sprite_width = std::max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
975 this->sprite_left = vehicle_panel_display->pos_x;
976 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
977 if (_current_text_dir == TD_RTL) {
978 this->sprite_right -= sprite_width;
979 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
980 } else {
981 this->sprite_left += sprite_width;
982 this->vehicle_margin = sprite_left;
983 }
984
985 this->DrawWidgets();
986 }
987
988 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
989 {
990 switch (widget) {
991 case WID_VR_MATRIX:
992 fill.height = resize.height = GetCharacterHeight(FontSize::Normal) + padding.height;
993 size.height = resize.height * 8;
994 break;
995
998 break;
999
1000 case WID_VR_INFO:
1001 size.width = this->information_width + padding.height;
1002 break;
1003 }
1004 }
1005
1006 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1007 {
1008 if (widget == WID_VR_CAPTION) return GetString(STR_REFIT_CAPTION, Vehicle::Get(this->window_number)->index);
1009
1010 return this->Window::GetWidgetString(widget, stringid);
1011 }
1012
1019 std::string GetCapacityString(const RefitOption &option) const
1020 {
1022 auto [cost, refit_capacity, mail_capacity, cargo_capacities] = Command<Commands::RefitVehicle>::Do(DoCommandFlag::QueryCost, this->selected_vehicle, option.cargo, option.subtype, this->auto_refit, false, this->num_vehicles);
1023
1024 if (cost.Failed()) return {};
1025
1026 Money money = cost.GetCost();
1027 if (mail_capacity > 0) {
1028 if (this->order != INVALID_VEH_ORDER_ID) {
1029 /* No predictable cost */
1030 return GetString(STR_PURCHASE_INFO_AIRCRAFT_CAPACITY, option.cargo, refit_capacity, GetCargoTypeByLabel(CT_MAIL), mail_capacity);
1031 }
1032
1033 if (money <= 0) {
1034 return GetString(STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT, option.cargo, refit_capacity, GetCargoTypeByLabel(CT_MAIL), mail_capacity, -money);
1035 }
1036
1037 return GetString(STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT, option.cargo, refit_capacity, GetCargoTypeByLabel(CT_MAIL), mail_capacity, money);
1038 }
1039
1040 if (this->order != INVALID_VEH_ORDER_ID) {
1041 /* No predictable cost */
1042 return GetString(STR_PURCHASE_INFO_CAPACITY, option.cargo, refit_capacity, STR_EMPTY);
1043 }
1044
1045 if (money <= 0) {
1046 return GetString(STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT, option.cargo, refit_capacity, -money);
1047 }
1048
1049 return GetString(STR_REFIT_NEW_CAPACITY_COST_OF_REFIT, option.cargo, refit_capacity, money);
1050 }
1051
1052 void DrawWidget(const Rect &r, WidgetID widget) const override
1053 {
1054 switch (widget) {
1057 DrawVehicleImage(v, r.WithX(this->sprite_left, this->sprite_right),
1058 VehicleID::Invalid(), EngineImageType::InDetails, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
1059
1060 /* Highlight selected vehicles. */
1061 if (this->order != INVALID_VEH_ORDER_ID) break;
1062 int x = 0;
1063 switch (v->type) {
1064 case VehicleType::Train: {
1065 VehicleSet vehicles_to_refit;
1066 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
1067
1068 int left = INT32_MIN;
1069 int width = 0;
1070
1071 /* Determine top & bottom position of the highlight.*/
1072 const int height = ScaleSpriteTrad(12);
1073 const int highlight_top = CentreBounds(r.top, r.bottom, height);
1074 const int highlight_bottom = highlight_top + height - 1;
1075
1076 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
1077 /* Start checking. */
1078 const bool contained = std::ranges::find(vehicles_to_refit, u->index) != vehicles_to_refit.end();
1079 if (contained && left == INT32_MIN) {
1080 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
1081 width = 0;
1082 }
1083
1084 /* Draw a selection. */
1085 if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
1086 if (u->Next() == nullptr && contained) {
1087 int current_width = u->GetDisplayImageWidth();
1088 width += current_width;
1089 x += current_width;
1090 }
1091
1092 int right = Clamp(left + width, 0, r.right);
1093 left = std::max(0, left);
1094
1095 if (_current_text_dir == TD_RTL) {
1096 right = r.Width() - left;
1097 left = right - width;
1098 }
1099
1100 if (left != right) {
1101 Rect hr = {left, highlight_top, right, highlight_bottom};
1103 }
1104
1105 left = INT32_MIN;
1106 }
1107
1108 int current_width = u->GetDisplayImageWidth();
1109 width += current_width;
1110 x += current_width;
1111 }
1112 break;
1113 }
1114
1115 default: break;
1116 }
1117 break;
1118 }
1119
1120 case WID_VR_MATRIX:
1121 DrawVehicleRefitWindow(this->refit_list, this->selected_refit, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
1122 break;
1123
1124 case WID_VR_INFO:
1125 if (this->selected_refit != nullptr) {
1126 std::string string = this->GetCapacityString(*this->selected_refit);
1127 if (!string.empty()) {
1129 }
1130 }
1131 break;
1132 }
1133 }
1134
1140 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1141 {
1142 switch (data) {
1143 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
1144 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
1145 /* Clear the selection. */
1147 this->selected_vehicle = v->index;
1148 this->num_vehicles = UINT8_MAX;
1149 [[fallthrough]];
1150 }
1151
1152 case 2: { // The vehicle selection has changed; rebuild the entire list.
1153 if (!gui_scope) break;
1154 this->BuildRefitList();
1155
1156 /* The vehicle width has changed too. */
1158 uint max_width = 0;
1159
1160 /* Check the width of all cargo information strings. */
1161 for (const auto &list : this->refit_list) {
1162 for (const RefitOption &refit : list.second) {
1163 std::string string = this->GetCapacityString(refit);
1164 if (!string.empty()) {
1165 Dimension dim = GetStringBoundingBox(string);
1166 max_width = std::max(dim.width, max_width);
1167 }
1168 }
1169 }
1170
1171 if (this->information_width < max_width) {
1172 this->information_width = max_width;
1173 this->ReInit();
1174 }
1175 [[fallthrough]];
1176 }
1177
1178 case 1: // A new cargo has been selected.
1179 if (!gui_scope) break;
1180 this->RefreshScrollbar();
1181 break;
1182 }
1183 }
1184
1185 int GetClickPosition(int click_x)
1186 {
1188 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
1189 click_x -= this->vehicle_margin;
1190 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
1191
1192 return click_x;
1193 }
1194
1195 void SetSelectedVehicles(int drag_x)
1196 {
1197 drag_x = GetClickPosition(drag_x);
1198
1199 int left_x = std::min(this->click_x, drag_x);
1200 int right_x = std::max(this->click_x, drag_x);
1201 this->num_vehicles = 0;
1202
1204 /* Find the vehicle part that was clicked. */
1205 switch (v->type) {
1206 case VehicleType::Train: {
1207 /* Don't select anything if we are not clicking in the vehicle. */
1208 if (left_x >= 0) {
1209 const Train *u = Train::From(v);
1210 bool start_counting = false;
1211 for (; u != nullptr; u = u->Next()) {
1212 int current_width = u->GetDisplayImageWidth();
1213 left_x -= current_width;
1214 right_x -= current_width;
1215
1216 if (left_x < 0 && !start_counting) {
1217 this->selected_vehicle = u->index;
1218 start_counting = true;
1219
1220 /* Count the first vehicle, even if articulated part */
1221 this->num_vehicles++;
1222 } else if (start_counting && !u->IsArticulatedPart()) {
1223 /* Do not count articulated parts */
1224 this->num_vehicles++;
1225 }
1226
1227 if (right_x < 0) break;
1228 }
1229 }
1230
1231 /* If the selection is not correct, clear it. */
1232 if (this->num_vehicles != 0) {
1233 if (IsCtrlPressed()) this->num_vehicles = UINT8_MAX;
1234 break;
1235 }
1236 [[fallthrough]];
1237 }
1238
1239 default:
1240 /* Clear the selection. */
1241 this->selected_vehicle = v->index;
1242 this->num_vehicles = UINT8_MAX;
1243 break;
1244 }
1245 }
1246
1247 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1248 {
1249 switch (widget) {
1250 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1251 if (this->order != INVALID_VEH_ORDER_ID) break;
1253 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
1254 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1256 if (!IsCtrlPressed()) {
1258 } else {
1259 /* The vehicle selection has changed. */
1260 this->InvalidateData(2);
1261 }
1262 break;
1263 }
1264
1265 case WID_VR_MATRIX: { // listbox
1266 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
1267 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
1268 this->InvalidateData(1);
1269
1270 if (click_count == 1) break;
1271 [[fallthrough]];
1272 }
1273
1274 case WID_VR_REFIT: // refit button
1275 if (this->selected_refit != nullptr) {
1276 const Vehicle *v = Vehicle::Get(this->window_number);
1277
1278 if (this->order == INVALID_VEH_ORDER_ID) {
1279 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1280 if (Command<Commands::RefitVehicle>::Post(GetCmdRefitVehMsg(v), v->tile, this->selected_vehicle, this->selected_refit->cargo, this->selected_refit->subtype, false, false, this->num_vehicles) && delete_window) this->Close();
1281 } else {
1282 if (Command<Commands::OrderRefit>::Post(v->tile, v->index, this->order, this->selected_refit->cargo)) this->Close();
1283 }
1284 }
1285 break;
1286 }
1287 }
1288
1289 void OnMouseDrag(Point pt, WidgetID widget) override
1290 {
1291 switch (widget) {
1292 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1293 if (this->order != INVALID_VEH_ORDER_ID) break;
1295 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1297 break;
1298 }
1299 }
1300 }
1301
1302 void OnDragDrop(Point pt, WidgetID widget) override
1303 {
1304 switch (widget) {
1305 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1306 if (this->order != INVALID_VEH_ORDER_ID) break;
1308 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1309 this->InvalidateData(2);
1310 break;
1311 }
1312 }
1313 }
1314
1315 void OnResize() override
1316 {
1318 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1319 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1320 }
1321};
1322
1323static constexpr std::initializer_list<NWidgetPart> _nested_vehicle_refit_widgets = {
1328 EndContainer(),
1329 /* Vehicle display + scrollbar. */
1334 EndContainer(),
1335 EndContainer(),
1337 /* Matrix + scrollbar. */
1341 EndContainer(),
1346 EndContainer(),
1347};
1348
1351 WindowPosition::Automatic, "view_vehicle_refit", 240, 174,
1352 WindowClass::VehicleRefit, WindowClass::VehicleView,
1354 _nested_vehicle_refit_widgets
1355);
1356
1364void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1365{
1366 CloseWindowById(WindowClass::VehicleRefit, v->index);
1367 RefitWindow *w = new RefitWindow(_vehicle_refit_desc, v, order, auto_refit);
1368 w->parent = parent;
1369}
1370
1379uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1380{
1381 /* List of cargo types of this engine */
1382 CargoTypes present = GetUnionOfArticulatedRefitMasks(engine, false);
1383
1384 /* Draw nothing if the engine is not refittable */
1385 if (HasAtMostOneBit(present.base())) return y;
1386
1387 std::string str;
1388 if (present == _cargo_mask) {
1389 /* Engine can be refitted to all types in this climate */
1390 str = GetString(STR_PURCHASE_INFO_REFITTABLE_TO, STR_PURCHASE_INFO_ALL_TYPES, std::monostate{});
1391 } else {
1392 /* Check if we are able to refit to more cargo types and unable to. If
1393 * so, invert the cargo types to list those that we can't refit to. */
1394 CargoTypes excluded = CargoTypes{present}.Flip(_cargo_mask);
1395 uint num_excluded = excluded.Count();
1396 if (num_excluded < present.Count() && num_excluded <= 7) {
1397 str = GetString(STR_PURCHASE_INFO_REFITTABLE_TO, STR_PURCHASE_INFO_ALL_BUT, excluded);
1398 } else {
1399 str = GetString(STR_PURCHASE_INFO_REFITTABLE_TO, STR_JUST_CARGO_LIST, present);
1400 }
1401 }
1402
1403 return DrawStringMultiLine(left, right, y, INT32_MAX, str);
1404}
1405
1412{
1413 if (!EngInfo(v->engine_type)->callback_mask.Test(VehicleCallbackMask::CargoSuffix)) return STR_EMPTY;
1414 std::array<int32_t, 1> regs100;
1415 uint16_t cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v, regs100);
1416 if (v->GetGRF()->grf_version < 8 && cb == 0xFF) return STR_EMPTY;
1417 if (cb == CALLBACK_FAILED || cb == 0x400) return STR_EMPTY;
1418 if (cb == 0x40F) {
1419 return GetGRFStringID(v->GetGRFID(), static_cast<GRFStringID>(regs100[0]));
1420 }
1421 if (cb > 0x400) {
1423 return STR_EMPTY;
1424 }
1425 return GetGRFStringID(v->GetGRFID(), GRFSTR_MISC_GRF_TEXT + cb);
1426}
1427
1429static bool VehicleGroupLengthSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1430{
1431 return a.NumVehicles() < b.NumVehicles();
1432}
1433
1435static bool VehicleGroupTotalProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1436{
1437 return a.GetDisplayProfitThisYear() < b.GetDisplayProfitThisYear();
1438}
1439
1441static bool VehicleGroupTotalProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1442{
1443 return a.GetDisplayProfitLastYear() < b.GetDisplayProfitLastYear();
1444}
1445
1447static bool VehicleGroupAverageProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1448{
1449 return a.GetDisplayProfitThisYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitThisYear() * static_cast<uint>(a.NumVehicles());
1450}
1451
1453static bool VehicleGroupAverageProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1454{
1455 return a.GetDisplayProfitLastYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitLastYear() * static_cast<uint>(a.NumVehicles());
1456}
1457
1459static bool VehicleNumberSorter(const Vehicle * const &a, const Vehicle * const &b)
1460{
1461 return a->unitnumber < b->unitnumber;
1462}
1463
1465static bool VehicleNameSorter(const Vehicle * const &a, const Vehicle * const &b)
1466{
1467 static std::string last_name[2] = { {}, {} };
1468
1469 if (a != _last_vehicle[0]) {
1470 _last_vehicle[0] = a;
1471 last_name[0] = GetString(STR_VEHICLE_NAME, a->index);
1472 }
1473
1474 if (b != _last_vehicle[1]) {
1475 _last_vehicle[1] = b;
1476 last_name[1] = GetString(STR_VEHICLE_NAME, b->index);
1477 }
1478
1479 int r = StrNaturalCompare(last_name[0], last_name[1]); // Sort by name (natural sorting).
1480 return (r != 0) ? r < 0: VehicleNumberSorter(a, b);
1481}
1482
1484static bool VehicleAgeSorter(const Vehicle * const &a, const Vehicle * const &b)
1485{
1486 auto r = a->age - b->age;
1487 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1488}
1489
1491static bool VehicleProfitThisYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1492{
1494 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1495}
1496
1498static bool VehicleProfitLastYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1499{
1501 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1502}
1503
1505static bool VehicleCargoSorter(const Vehicle * const &a, const Vehicle * const &b)
1506{
1507 const Vehicle *v;
1508 CargoArray diff{};
1509
1510 /* Append the cargo of the connected waggons */
1511 for (v = a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1512 for (v = b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1513
1514 int r = 0;
1515 for (uint d : diff) {
1516 r = d;
1517 if (r != 0) break;
1518 }
1519
1520 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1521}
1522
1524static bool VehicleReliabilitySorter(const Vehicle * const &a, const Vehicle * const &b)
1525{
1526 int r = a->reliability - b->reliability;
1527 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1528}
1529
1531static bool VehicleMaxSpeedSorter(const Vehicle * const &a, const Vehicle * const &b)
1532{
1534 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1535}
1536
1538static bool VehicleModelSorter(const Vehicle * const &a, const Vehicle * const &b)
1539{
1540 int r = a->engine_type.base() - b->engine_type.base();
1541 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1542}
1543
1545static bool VehicleValueSorter(const Vehicle * const &a, const Vehicle * const &b)
1546{
1547 const Vehicle *u;
1548 Money diff = 0;
1549
1550 for (u = a; u != nullptr; u = u->Next()) diff += u->value;
1551 for (u = b; u != nullptr; u = u->Next()) diff -= u->value;
1552
1553 int r = ClampTo<int32_t>(diff);
1554 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1555}
1556
1558static bool VehicleLengthSorter(const Vehicle * const &a, const Vehicle * const &b)
1559{
1561 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1562}
1563
1565static bool VehicleTimeToLiveSorter(const Vehicle * const &a, const Vehicle * const &b)
1566{
1567 int r = ClampTo<int32_t>((a->max_age - a->age) - (b->max_age - b->age));
1568 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1569}
1570
1572static bool VehicleTimetableDelaySorter(const Vehicle * const &a, const Vehicle * const &b)
1573{
1574 int r = a->lateness_counter - b->lateness_counter;
1575 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1576}
1577
1578void InitializeGUI()
1579{
1580 _grouping = {};
1581 _sorting = {};
1582}
1583
1590static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1591{
1592 Window *w = FindWindowById(window_class, from_index);
1593 if (w != nullptr) {
1594 /* Update window_number */
1595 w->window_number = to_index;
1596 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1597
1598 /* Update vehicle drag data */
1599 if (_thd.window_class == window_class && _thd.window_number == from_index) {
1600 _thd.window_number = to_index;
1601 }
1602
1603 /* Notify the window. */
1605 }
1606}
1607
1614{
1615 ChangeVehicleWindow(WindowClass::VehicleView, from_index, to_index);
1616 ChangeVehicleWindow(WindowClass::VehicleOrders, from_index, to_index);
1617 ChangeVehicleWindow(WindowClass::VehicleRefit, from_index, to_index);
1618 ChangeVehicleWindow(WindowClass::VehicleDetails, from_index, to_index);
1619 ChangeVehicleWindow(WindowClass::VehicleTimetable, from_index, to_index);
1620}
1621
1622static constexpr std::initializer_list<NWidgetPart> _nested_vehicle_list = {
1629 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_VL_ORDER_VIEW), SetMinimalSize(61, 14), SetStringTip(STR_GOTO_ORDER_VIEW, STR_GOTO_ORDER_VIEW_TOOLTIP),
1630 EndContainer(),
1631 EndContainer(),
1635 EndContainer(),
1636
1639 NWidget(WWT_TEXTBTN, Colours::Grey, WID_VL_GROUP_ORDER), SetMinimalSize(0, 12), SetFill(1, 1), SetStringTip(STR_STATION_VIEW_GROUP, STR_TOOLTIP_GROUP_ORDER),
1640 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_VL_SORT_ORDER), SetMinimalSize(0, 12), SetFill(1, 1), SetStringTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1641 EndContainer(),
1644 NWidget(WWT_DROPDOWN, Colours::Grey, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(0, 12), SetFill(1, 1), SetToolTip(STR_TOOLTIP_SORT_CRITERIA),
1645 EndContainer(),
1650 NWidget(WWT_DROPDOWN, Colours::Grey, WID_VL_FILTER_BY_CARGO), SetMinimalSize(0, 12), SetFill(0, 1), SetToolTip(STR_TOOLTIP_FILTER_CRITERIA),
1651 EndContainer(),
1653 EndContainer(),
1654 EndContainer(),
1655 EndContainer(),
1656
1660 EndContainer(),
1661
1666 SetToolTip(STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1669 SetStringTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1670 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_VL_STOP_ALL), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1),
1671 SetSpriteTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1672 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_VL_START_ALL), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1),
1673 SetSpriteTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1674 EndContainer(),
1675 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1677 EndContainer(),
1679 EndContainer(),
1680};
1681
1682static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, uint order_arrow_width, VehicleOrderID start)
1683{
1684 auto orders = v->Orders();
1685 if (orders.empty()) return;
1686
1687 bool rtl = _current_text_dir == TD_RTL;
1688 int l_offset = rtl ? 0 : order_arrow_width;
1689 int r_offset = rtl ? order_arrow_width : 0;
1690 int i = 0;
1691 VehicleOrderID oid = start;
1692
1693 do {
1694 if (oid == v->cur_real_order_index) DrawString(left, right, y, rtl ? STR_JUST_LEFT_ARROW : STR_JUST_RIGHT_ARROW, TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1695
1696 if (orders[oid].IsType(OT_GOTO_STATION)) {
1697 DrawString(left + l_offset, right - r_offset, y, GetString(STR_STATION_NAME, orders[oid].GetDestination()), TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1698
1700 if (++i == 4) break;
1701 }
1702
1703 oid = v->orders->GetNext(oid);
1704 } while (oid != start);
1705}
1706
1715static void DrawSmallOrderList(const OrderList *orderlist, int left, int right, int y, uint order_arrow_width)
1716{
1717 if (orderlist == nullptr) return;
1718
1719 bool rtl = _current_text_dir == TD_RTL;
1720 int l_offset = rtl ? 0 : order_arrow_width;
1721 int r_offset = rtl ? order_arrow_width : 0;
1722 int i = 0;
1723
1724 for (const Order &order : orderlist->GetOrders()) {
1725 if (order.IsType(OT_GOTO_STATION)) {
1726 DrawString(left + l_offset, right - r_offset, y, GetString(STR_STATION_NAME, order.GetDestination()), TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1727
1729 if (++i == 4) break;
1730 }
1731 }
1732}
1733
1742void DrawVehicleImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip)
1743{
1744 switch (v->type) {
1745 case VehicleType::Train: DrawTrainImage(Train::From(v), r, selection, image_type, skip); break;
1746 case VehicleType::Road: DrawRoadVehImage(v, r, selection, image_type, skip); break;
1747 case VehicleType::Ship: DrawShipImage(v, r, selection, image_type); break;
1748 case VehicleType::Aircraft: DrawAircraftImage(v, r, selection, image_type); break;
1749 default: NOT_REACHED();
1750 }
1751}
1752
1759uint GetVehicleListHeight(VehicleType type, uint divisor)
1760{
1761 /* Name + vehicle + profit */
1762 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.matrix.Vertical();
1763 /* Drawing of the 4 small orders + profit*/
1764 if (type >= VehicleType::Ship) base = std::max(base, 6U * GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.matrix.Vertical());
1765
1766 if (divisor == 1) return base;
1767
1768 /* Make sure the height is dividable by divisor */
1769 uint rem = base % divisor;
1770 return base + (rem == 0 ? 0 : divisor - rem);
1771}
1772
1778static int GetUnitNumberWidth(int digits)
1779{
1780 return GetStringBoundingBox(GetString(STR_JUST_COMMA, GetParamMaxDigits(digits))).width;
1781}
1782
1789void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1790{
1791 Rect ir = r.WithHeight(line_height).Shrink(WidgetDimensions::scaled.matrix, RectPadding::zero);
1792 bool rtl = _current_text_dir == TD_RTL;
1793
1794 Dimension profit = GetSpriteSize(SPR_PROFIT_LOT);
1795 int text_offset = std::max<int>(profit.width, GetUnitNumberWidth(this->unitnumber_digits)) + WidgetDimensions::scaled.hsep_normal;
1796 Rect tr = ir.Indent(text_offset, rtl);
1797
1798 bool show_orderlist = this->vli.vtype >= VehicleType::Ship;
1799 Rect olr = ir.Indent(std::max(ScaleGUITrad(100) + text_offset, ir.Width() / 2), rtl);
1800
1801 int image_left = (rtl && show_orderlist) ? olr.right : tr.left;
1802 int image_right = (!rtl && show_orderlist) ? olr.left : tr.right;
1803
1804 int vehicle_button_x = rtl ? ir.right - profit.width : ir.left;
1805
1806 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->vehgroups);
1807 for (auto it = first; it != last; ++it) {
1808 const GUIVehicleGroup &vehgroup = *it;
1809
1810 DrawString(tr.left, tr.right, ir.bottom - GetCharacterHeight(FontSize::Small) - WidgetDimensions::scaled.framerect.bottom,
1811 GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_LIST_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR,
1812 vehgroup.GetDisplayProfitThisYear(),
1813 vehgroup.GetDisplayProfitLastYear()));
1814
1815 DrawVehicleProfitButton(vehgroup.GetOldestVehicleAge(), vehgroup.GetDisplayProfitLastYear(), vehgroup.NumVehicles(), vehicle_button_x, ir.top + GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal);
1816
1817 switch (this->grouping) {
1818 case GB_NONE: {
1819 const Vehicle *v = vehgroup.GetSingleVehicle();
1820
1822 DrawSprite(SPR_WARNING_SIGN, PAL_NONE, vehicle_button_x, ir.top + GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal + profit.height);
1823 }
1824
1825 DrawVehicleImage(v, ir.WithX(image_left, image_right), selected_vehicle, EngineImageType::InList, 0);
1826
1827 if (_settings_client.gui.show_cargo_in_vehicle_lists) {
1828 /* Get the cargoes the vehicle can carry */
1829 CargoTypes vehicle_cargoes{};
1830
1831 for (auto u = v; u != nullptr; u = u->Next()) {
1832 if (u->cargo_cap == 0) continue;
1833
1834 vehicle_cargoes.Set(u->cargo_type);
1835 }
1836
1837 if (!v->name.empty()) {
1838 /* The vehicle got a name so we will print it and the cargoes */
1839 DrawString(tr.left, tr.right, ir.top,
1840 GetString(STR_VEHICLE_LIST_NAME_AND_CARGO, STR_VEHICLE_NAME, v->index, STR_VEHICLE_LIST_CARGO, vehicle_cargoes),
1842 } else if (v->group_id != DEFAULT_GROUP) {
1843 /* The vehicle has no name, but is member of a group, so print group name and the cargoes */
1844 DrawString(tr.left, tr.right, ir.top,
1845 GetString(STR_VEHICLE_LIST_NAME_AND_CARGO, STR_GROUP_NAME, v->group_id, STR_VEHICLE_LIST_CARGO, vehicle_cargoes),
1847 } else {
1848 /* The vehicle has no name, and is not a member of a group, so just print the cargoes */
1849 DrawString(tr.left, tr.right, ir.top, GetString(STR_VEHICLE_LIST_CARGO, vehicle_cargoes), TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1850 }
1851 } else if (!v->name.empty()) {
1852 /* The vehicle got a name so we will print it */
1853 DrawString(tr.left, tr.right, ir.top, GetString(STR_VEHICLE_NAME, v->index), TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1854 } else if (v->group_id != DEFAULT_GROUP) {
1855 /* The vehicle has no name, but is member of a group, so print group name */
1856 DrawString(tr.left, tr.right, ir.top, GetString(STR_GROUP_NAME, v->group_id), TextColour::Black, AlignmentH::Start, false, FontSize::Small);
1857 }
1858
1859 if (show_orderlist) DrawSmallOrderList(v, olr.left, olr.right, ir.top + GetCharacterHeight(FontSize::Small), this->order_arrow_width, v->cur_real_order_index);
1860
1861 TextColour tc;
1862 if (v->IsChainInDepot()) {
1863 tc = TextColour::Blue;
1864 } else {
1866 }
1867
1868 DrawString(ir.left, ir.right, ir.top + WidgetDimensions::scaled.framerect.top, GetString(STR_JUST_COMMA, v->unitnumber), tc);
1869 break;
1870 }
1871
1872 case GB_SHARED_ORDERS:
1873 assert(vehgroup.NumVehicles() > 0);
1874
1875 for (int i = 0; i < static_cast<int>(vehgroup.NumVehicles()); ++i) {
1876 if (image_left + WidgetDimensions::scaled.hsep_wide * i >= image_right) break; // Break if there is no more space to draw any more vehicles anyway.
1877 DrawVehicleImage(vehgroup.vehicles_begin[i], ir.WithX(image_left + WidgetDimensions::scaled.hsep_wide * i, image_right), selected_vehicle, EngineImageType::InList, 0);
1878 }
1879
1880 if (show_orderlist) DrawSmallOrderList(vehgroup.vehicles_begin[0]->orders, olr.left, olr.right, ir.top + GetCharacterHeight(FontSize::Small), this->order_arrow_width);
1881
1882 DrawString(ir.left, ir.right, ir.top + WidgetDimensions::scaled.framerect.top, GetString(STR_JUST_COMMA, vehgroup.NumVehicles()), TextColour::Black);
1883 break;
1884
1885 default:
1886 NOT_REACHED();
1887 }
1888
1889 ir = ir.Translate(0, line_height);
1890 }
1891}
1892
1893void BaseVehicleListWindow::UpdateSortingFromGrouping()
1894{
1895 /* Set up sorting. Make the window-specific _sorting variable
1896 * point to the correct global _sorting struct so we are freed
1897 * from having conditionals during window operation */
1898 switch (this->vli.vtype) {
1899 case VehicleType::Train: this->sorting = &_sorting[this->grouping].train; break;
1900 case VehicleType::Road: this->sorting = &_sorting[this->grouping].roadveh; break;
1901 case VehicleType::Ship: this->sorting = &_sorting[this->grouping].ship; break;
1902 case VehicleType::Aircraft: this->sorting = &_sorting[this->grouping].aircraft; break;
1903 default: NOT_REACHED();
1904 }
1905 this->vehgroups.SetSortFuncs(this->GetVehicleSorterFuncs());
1906 this->vehgroups.SetListing(*this->sorting);
1907 this->vehgroups.ForceRebuild();
1908 this->vehgroups.NeedResort();
1909}
1910
1911void BaseVehicleListWindow::UpdateVehicleGroupBy(GroupBy group_by)
1912{
1913 if (this->grouping != group_by) {
1914 /* Save the old sorting option, so that if we change the grouping option back later on,
1915 * UpdateSortingFromGrouping() will automatically restore the saved sorting option. */
1916 *this->sorting = this->vehgroups.GetListing();
1917
1918 this->grouping = group_by;
1919 _grouping[this->vli.type][this->vli.vtype] = group_by;
1920 this->UpdateSortingFromGrouping();
1921 }
1922}
1923
1928struct VehicleListWindow : public BaseVehicleListWindow {
1929private:
1935
1941
1942public:
1944 {
1945 this->CreateNestedTree();
1946
1948
1949 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1950
1951 /* Set up the window widgets */
1952 this->GetWidget<NWidgetCore>(WID_VL_LIST)->SetToolTip(STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + to_underlying(this->vli.vtype));
1953
1955 if (this->vli.type == VehicleListType::VehicleSharedOrders) {
1956 this->GetWidget<NWidgetCore>(WID_VL_CAPTION_SHARED_ORDERS)->SetString(STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION);
1957 /* If we are in the shared orders window, then disable the group-by dropdown menu.
1958 * Remove this when the group-by dropdown menu has another option apart from grouping by shared orders. */
1962 } else {
1963 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->SetString(STR_VEHICLE_LIST_TRAIN_CAPTION + to_underlying(this->vli.vtype));
1965 }
1966
1968 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1969
1970 this->BuildVehicleList();
1971 this->SortVehicleList();
1972 }
1973
1976 {
1977 *this->sorting = this->vehgroups.GetListing();
1978 }
1979
1980 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1981 {
1982 switch (widget) {
1983 case WID_VL_LIST:
1984 fill.height = resize.height = GetVehicleListHeight(this->vli.vtype, 1);
1985
1986 switch (this->vli.vtype) {
1987 case VehicleType::Train:
1988 case VehicleType::Road:
1989 size.height = 6 * resize.height;
1990 break;
1991 case VehicleType::Ship:
1993 size.height = 4 * resize.height;
1994 break;
1995 default: NOT_REACHED();
1996 }
1997 break;
1998
1999 case WID_VL_SORT_ORDER: {
2001 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
2002 d.height += padding.height;
2003 size = maxdim(size, d);
2004 break;
2005 }
2006
2008 size.width = GetStringListWidth(this->vehicle_group_by_names) + padding.width;
2009 break;
2010
2012 size.width = GetStringListWidth(this->vehicle_group_none_sorter_names_calendar);
2013 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_none_sorter_names_wallclock));
2014 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_shared_orders_sorter_names_calendar));
2015 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_shared_orders_sorter_names_wallclock));
2016 size.width += padding.width;
2017 break;
2018
2020 size.width = std::max(size.width, GetDropDownListDimension(this->BuildCargoDropDownList(true)).width + padding.width);
2021 break;
2022
2024 Dimension d = this->GetActionDropdownSize(this->vli.type == VehicleListType::Company, false, true);
2025 d.height += padding.height;
2026 d.width += padding.width;
2027 size = maxdim(size, d);
2028 break;
2029 }
2030 }
2031 }
2032
2033 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2034 {
2035 switch (widget) {
2037 return GetString(STR_VEHICLE_LIST_AVAILABLE_TRAINS + to_underlying(this->vli.vtype));
2038
2040 return GetString(std::data(this->vehicle_group_by_names)[this->grouping]);
2041
2043 return GetString(this->GetVehicleSorterNames()[this->vehgroups.SortType()]);
2044
2046 return GetString(this->GetCargoFilterLabel(this->cargo_filter_criteria));
2047
2048 case WID_VL_CAPTION:
2050 switch (this->vli.type) {
2051 case VehicleListType::VehicleSharedOrders: // Shared Orders
2052 return GetString(stringid, this->vehicles.size());
2053
2054 case VehicleListType::Company: // Company Name
2055 return GetString(stringid, STR_COMPANY_NAME, this->vli.ToCompanyID(), std::monostate{}, this->vehicles.size());
2056
2057 case VehicleListType::Station: // Station/Waypoint Name
2058 return GetString(stringid, Station::IsExpected(BaseStation::Get(this->vli.ToStationID())) ? STR_STATION_NAME : STR_WAYPOINT_NAME, this->vli.ToStationID(), std::monostate{}, this->vehicles.size());
2059
2061 return GetString(stringid, STR_DEPOT_CAPTION, this->vli.vtype, this->vli.ToDestinationID(), this->vehicles.size());
2062
2063 default: NOT_REACHED();
2064 }
2065 }
2066
2067 default:
2068 return this->Window::GetWidgetString(widget, stringid);
2069 }
2070 }
2071
2072 void DrawWidget(const Rect &r, WidgetID widget) const override
2073 {
2074 switch (widget) {
2075 case WID_VL_SORT_ORDER:
2076 /* draw arrow pointing up/down for ascending/descending sorting */
2077 this->DrawSortButton(widget, this->vehgroups.IsDescSortOrder());
2078 break;
2079
2080 case WID_VL_LIST:
2081 this->DrawVehicleListItems(VehicleID::Invalid(), this->resize.step_height, r);
2082 break;
2083 }
2084 }
2085
2086 void OnPaint() override
2087 {
2088 this->BuildVehicleList();
2089 this->SortVehicleList();
2090
2091 if (this->vehicles.empty() && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
2092 this->CloseChildWindows(WindowClass::DropdownMenu);
2093 }
2094
2095 /* Hide the widgets that we will not use in this window
2096 * Some windows contains actions only fit for the owner */
2097 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
2099 if (plane_to_show != nwi->shown_plane) {
2100 nwi->SetDisplayedPlane(plane_to_show);
2101 nwi->SetDirty(this);
2102 }
2103 if (this->owner == _local_company) {
2105 this->SetWidgetsDisabledState(this->vehicles.empty(),
2109 }
2110
2111 this->DrawWidgets();
2112 }
2113
2114 bool last_overlay_state = false;
2115 void OnMouseLoop() override
2116 {
2117 if (last_overlay_state != ShowCargoIconOverlay()) {
2118 last_overlay_state = ShowCargoIconOverlay();
2119 this->SetDirty();
2120 }
2121 }
2122
2123 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2124 {
2125 switch (widget) {
2126 case WID_VL_ORDER_VIEW: // Open the shared orders window
2127 assert(this->vli.type == VehicleListType::VehicleSharedOrders);
2128 assert(!this->vehicles.empty());
2129 ShowOrdersWindow(this->vehicles[0]);
2130 break;
2131
2132 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
2133 this->vehgroups.ToggleSortOrder();
2134 this->SetDirty();
2135 break;
2136
2137 case WID_VL_GROUP_BY_PULLDOWN: // Select sorting criteria dropdown menu
2138 ShowDropDownMenu(this, this->vehicle_group_by_names, this->grouping, WID_VL_GROUP_BY_PULLDOWN, 0, 0);
2139 return;
2140
2141 case WID_VL_SORT_BY_PULLDOWN: // Select sorting criteria dropdown menu
2142 ShowDropDownMenu(this, this->GetVehicleSorterNames(), this->vehgroups.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
2143 (this->vli.vtype == VehicleType::Train || this->vli.vtype == VehicleType::Road) ? 0 : (1 << 10));
2144 return;
2145
2146 case WID_VL_FILTER_BY_CARGO: { // Cargo filter dropdown
2147 static std::string cargo_filter;
2148 ShowDropDownList(this, this->BuildCargoDropDownList(false), this->cargo_filter_criteria, widget, 0, DropDownOption::Filterable, &cargo_filter);
2149 break;
2150 }
2151
2152 case WID_VL_LIST: { // Matrix to show vehicles
2153 auto it = this->vscroll->GetScrolledItemFromWidget(this->vehgroups, pt.y, this, WID_VL_LIST);
2154 if (it == this->vehgroups.end()) return; // click out of list bound
2155
2156 const GUIVehicleGroup &vehgroup = *it;
2157 switch (this->grouping) {
2158 case GB_NONE: {
2159 const Vehicle *v = vehgroup.GetSingleVehicle();
2160 if (!VehicleClicked(v)) {
2161 if (IsCtrlPressed()) {
2163 } else {
2165 }
2166 }
2167 break;
2168 }
2169
2170 case GB_SHARED_ORDERS: {
2171 assert(vehgroup.NumVehicles() > 0);
2172 if (!VehicleClicked(vehgroup)) {
2173 const Vehicle *v = vehgroup.vehicles_begin[0];
2174 if (IsCtrlPressed()) {
2175 ShowOrdersWindow(v);
2176 } else {
2177 if (vehgroup.NumVehicles() == 1) {
2179 } else {
2180 ShowVehicleListWindow(v);
2181 }
2182 }
2183 }
2184 break;
2185 }
2186
2187 default: NOT_REACHED();
2188 }
2189
2190 break;
2191 }
2192
2194 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
2195 break;
2196
2199 break;
2200 }
2201
2202 case WID_VL_STOP_ALL:
2203 case WID_VL_START_ALL:
2204 Command<Commands::MassStartStop>::Post(TileIndex{}, widget == WID_VL_START_ALL, true, this->vli);
2205 break;
2206 }
2207 }
2208
2209 void OnDropdownSelect(WidgetID widget, int index, int) override
2210 {
2211 switch (widget) {
2213 this->UpdateVehicleGroupBy(static_cast<GroupBy>(index));
2214 break;
2215
2217 this->vehgroups.SetSortType(index);
2218 break;
2219
2221 this->SetCargoFilter(static_cast<CargoType>(index));
2222 break;
2223
2225 assert(!this->vehicles.empty());
2226
2227 switch (index) {
2228 case ADI_REPLACE: // Replace window
2230 break;
2231 case ADI_SERVICE: // Send for servicing
2232 case ADI_DEPOT: // Send to Depots
2233 Command<Commands::SendVehicleToDepot>::Post(GetCmdSendToDepotMsg(this->vli.vtype), VehicleID::Invalid(), (index == ADI_SERVICE ? DepotCommandFlag::Service : DepotCommandFlags{}) | DepotCommandFlag::MassSend, this->vli);
2234 break;
2235
2236 case ADI_CREATE_GROUP: // Create group
2237 Command<Commands::AddVehicleToGroup>::Post(CcAddVehicleNewGroup, NEW_GROUP, VehicleID::Invalid(), false, this->vli);
2238 break;
2239
2240 default: NOT_REACHED();
2241 }
2242 break;
2243
2244 default: NOT_REACHED();
2245 }
2246 this->SetDirty();
2247 }
2248
2249 void OnGameTick() override
2250 {
2251 if (this->vehgroups.NeedResort()) {
2252 StationID station = (this->vli.type == VehicleListType::Station) ? this->vli.ToStationID() : StationID::Invalid();
2253
2254 Debug(Facility::Misc, Severity::Notice, "Periodic resort {} list company {} at station {}", this->vli.vtype, this->owner, station);
2255 this->SetDirty();
2256 }
2257 }
2258
2259 void OnResize() override
2260 {
2261 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
2262 }
2263
2269 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2270 {
2271 if (!gui_scope && HasBit(data, 31) && this->vli.type == VehicleListType::VehicleSharedOrders) {
2272 /* Needs to be done in command-scope, so everything stays valid */
2273 this->vli.SetIndex(GB(data, 0, 20));
2274 this->window_number = this->vli.ToWindowNumber();
2275 this->vehgroups.ForceRebuild();
2276 return;
2277 }
2278
2279 if (data == 0) {
2280 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
2281 this->vehgroups.ForceRebuild();
2282 } else {
2283 this->vehgroups.ForceResort();
2284 }
2285 }
2286};
2287
2290 WindowDesc{
2291 WindowPosition::Automatic, "list_vehicles_train", 325, 246,
2292 WindowClass::TrainList, WindowClass::None,
2293 {},
2294 _nested_vehicle_list
2295 },
2296 WindowDesc{
2297 WindowPosition::Automatic, "list_vehicles_roadveh", 260, 246,
2298 WindowClass::RoadVehicleList, WindowClass::None,
2299 {},
2300 _nested_vehicle_list
2301 },
2302 WindowDesc{
2303 WindowPosition::Automatic, "list_vehicles_ship", 260, 246,
2304 WindowClass::ShipList, WindowClass::None,
2305 {},
2306 _nested_vehicle_list
2307 },
2308 WindowDesc{
2309 WindowPosition::Automatic, "list_vehicles_aircraft", 260, 246,
2310 WindowClass::AircraftList, WindowClass::None,
2311 {},
2312 _nested_vehicle_list
2313 }
2314}};
2315
2316static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32_t unique_number)
2317{
2318 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
2319
2320 assert(IsCompanyBuildableVehicleType(vehicle_type));
2321 VehicleListIdentifier vli(vlt, vehicle_type, company, unique_number);
2323}
2324
2325void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
2326{
2327 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
2328 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
2329 * if IsCtrlPressed(), do the opposite action (Advanced list x Normal list)
2330 */
2331
2332 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != IsCtrlPressed()) {
2333 ShowCompanyGroup(company, vehicle_type);
2334 } else {
2335 ShowVehicleListWindowLocal(company, VehicleListType::Company, vehicle_type, company.base());
2336 }
2337}
2338
2339void ShowVehicleListWindow(const Vehicle *v)
2340{
2341 ShowVehicleListWindowLocal(v->owner, VehicleListType::VehicleSharedOrders, v->type, v->FirstShared()->index.base());
2342}
2343
2344void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
2345{
2346 ShowVehicleListWindowLocal(company, VehicleListType::Station, vehicle_type, station.base());
2347}
2348
2349void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
2350{
2351 ShowVehicleListWindowLocal(company, VehicleListType::Depot, vehicle_type, GetDepotDestinationIndex(depot_tile).base());
2352}
2353
2354
2355/* Unified vehicle GUI - Vehicle Details Window */
2356
2360
2383
2385static constexpr std::initializer_list<NWidgetPart> _nested_train_vehicle_details_widgets = {
2388 NWidget(WWT_CAPTION, Colours::Grey, WID_VD_CAPTION), SetStringTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2392 EndContainer(),
2397 EndContainer(),
2404 SetStringTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2406 EndContainer(),
2409 SetStringTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2411 SetStringTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2413 SetStringTip(STR_VEHICLE_DETAIL_TAB_TOTALS, STR_VEHICLE_DETAILS_TRAIN_TOTALS_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2415 EndContainer(),
2416};
2417
2418
2420extern void DrawTrainDetails(const Train *v, const Rect &r, int vscroll_pos, uint16_t vscroll_cap, TrainDetailsWindowTabs det_tab);
2421extern void DrawRoadVehDetails(const Vehicle *v, const Rect &r);
2422extern void DrawShipDetails(const Vehicle *v, const Rect &r);
2423extern void DrawAircraftDetails(const Aircraft *v, const Rect &r);
2424
2425static const StringID _service_interval_dropdown_calendar[] = {
2426 STR_VEHICLE_DETAILS_DEFAULT,
2427 STR_VEHICLE_DETAILS_DAYS,
2428 STR_VEHICLE_DETAILS_PERCENT,
2429};
2430
2431static const StringID _service_interval_dropdown_wallclock[] = {
2432 STR_VEHICLE_DETAILS_DEFAULT,
2433 STR_VEHICLE_DETAILS_MINUTES,
2434 STR_VEHICLE_DETAILS_PERCENT,
2435};
2436
2440 Scrollbar *vscroll = nullptr;
2441
2448 {
2450
2451 this->CreateNestedTree();
2452 this->vscroll = (v->type == VehicleType::Train ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
2453 this->FinishInitNested(window_number);
2454
2455 this->owner = v->owner;
2456 }
2457
2463 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2464 {
2465 if (data == VIWD_AUTOREPLACE) {
2466 /* Autoreplace replaced the vehicle.
2467 * Nothing to do for this window. */
2468 return;
2469 }
2470 if (!gui_scope) return;
2471 const Vehicle *v = Vehicle::Get(this->window_number);
2472 if (v->type == VehicleType::Road) {
2474 uint aimed_height = this->GetRoadVehDetailsHeight(v);
2475 /* If the number of articulated parts changes, the size of the window must change too. */
2476 if (aimed_height != nwid_info->current_y) {
2477 this->ReInit();
2478 }
2479 }
2480 }
2481
2488 {
2489 uint desired_height;
2490 if (v->HasArticulatedPart()) {
2491 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2492 desired_height = ScaleGUITrad(15) + 3 * GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal * 2;
2493 /* Add space for the cargo amount for each part. */
2494 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2495 if (u->cargo_cap != 0) desired_height += GetCharacterHeight(FontSize::Normal);
2496 }
2497 } else {
2498 desired_height = 4 * GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal * 2;
2499 }
2500 return desired_height;
2501 }
2502
2503 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2504 {
2505 switch (widget) {
2506 case WID_VD_TOP_DETAILS: {
2507 Dimension dim = { 0, 0 };
2508 size.height = 4 * GetCharacterHeight(FontSize::Normal) + padding.height;
2509
2510 uint64_t max_value = GetParamMaxValue(INT16_MAX);
2511 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_MAX_SPEED, max_value)));
2512 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED, max_value, max_value, max_value)));
2513 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE, max_value, max_value, max_value, max_value)));
2514 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_MIN_PERFORMANCE, max_value, max_value, max_value)));
2515 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD_MIN_PERFORMANCE, max_value, max_value, max_value)));
2516 dim = maxdim(dim, GetStringBoundingBox(GetString(STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS, max_value, max_value, max_value)));
2517 dim = maxdim(dim, GetStringBoundingBox(GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_AGE_RUNNING_COST_PERIOD : STR_VEHICLE_INFO_AGE_RUNNING_COST_YR, STR_VEHICLE_INFO_AGE, max_value, max_value, max_value)));
2518 size.width = dim.width + padding.width;
2519 break;
2520 }
2521
2522 case WID_VD_MIDDLE_DETAILS: {
2523 const Vehicle *v = Vehicle::Get(this->window_number);
2524 switch (v->type) {
2525 case VehicleType::Road:
2526 size.height = this->GetRoadVehDetailsHeight(v) + padding.height;
2527 break;
2528
2529 case VehicleType::Ship:
2530 size.height = 4 * GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal * 2 + padding.height;
2531 break;
2532
2534 size.height = 5 * GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal * 2 + padding.height;
2535 break;
2536
2537 default:
2538 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2539 }
2540 break;
2541 }
2542
2543 case WID_VD_MATRIX:
2544 fill.height = resize.height = std::max<uint>(ScaleGUITrad(14), GetCharacterHeight(FontSize::Normal) + padding.height);
2545 size.height = 4 * resize.height;
2546 break;
2547
2549 Dimension d = maxdim(GetStringListBoundingBox(_service_interval_dropdown_calendar), GetStringListBoundingBox(_service_interval_dropdown_wallclock));
2550 d.width += padding.width;
2551 d.height += padding.height;
2552 size = maxdim(size, d);
2553 break;
2554 }
2555
2557 /* Do we show the last serviced value as a date or minutes since service? */
2559 ? MakeParameters(GetParamMaxValue(MAX_SERVINT_DAYS), STR_VEHICLE_DETAILS_LAST_SERVICE_MINUTES_AGO, EconomyTime::MAX_DATE)
2560 : MakeParameters(GetParamMaxValue(MAX_SERVINT_DAYS), STR_VEHICLE_DETAILS_LAST_SERVICE_DATE, TimerGameEconomy::DateAtStartOfYear(EconomyTime::MAX_YEAR));
2561
2562 size.width = std::max(size.width, GetStringBoundingBox(GetStringWithArgs(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT, params)).width);
2563 PrepareArgsForNextRun(params);
2564 size.width = std::max(size.width, GetStringBoundingBox(GetStringWithArgs(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS, params)).width);
2565
2566 size.width += padding.width;
2567 size.height = GetCharacterHeight(FontSize::Normal) + padding.height;
2568 break;
2569 }
2570 }
2571
2578 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2579 {
2580 if (_local_company != company_id) return false;
2581
2582 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2583 switch (vehicle_type) {
2584 default: NOT_REACHED();
2585 case VehicleType::Train: return vds->servint_trains != 0;
2586 case VehicleType::Road: return vds->servint_roadveh != 0;
2587 case VehicleType::Ship: return vds->servint_ships != 0;
2588 case VehicleType::Aircraft: return vds->servint_aircraft != 0;
2589 }
2590 }
2591
2601 static void DrawVehicleDetails(const Vehicle *v, const Rect &r, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2602 {
2603 switch (v->type) {
2604 case VehicleType::Train: DrawTrainDetails(Train::From(v), r, vscroll_pos, vscroll_cap, det_tab); break;
2605 case VehicleType::Road: DrawRoadVehDetails(v, r); break;
2606 case VehicleType::Ship: DrawShipDetails(v, r); break;
2608 default: NOT_REACHED();
2609 }
2610 }
2611
2612 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2613 {
2614 if (widget == WID_VD_CAPTION) return GetString(STR_VEHICLE_DETAILS_CAPTION, Vehicle::Get(this->window_number)->index);
2615
2616 return this->Window::GetWidgetString(widget, stringid);
2617 }
2618
2619 void DrawWidget(const Rect &r, WidgetID widget) const override
2620 {
2621 const Vehicle *v = Vehicle::Get(this->window_number);
2622
2623 switch (widget) {
2624 case WID_VD_TOP_DETAILS: {
2625 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2626
2627 /* Draw running cost */
2628 DrawString(tr,
2629 GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_AGE_RUNNING_COST_PERIOD : STR_VEHICLE_INFO_AGE_RUNNING_COST_YR,
2630 (v->age + CalendarTime::DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED,
2633 v->GetDisplayRunningCost()));
2635
2636 /* Draw max speed */
2637 uint64_t max_speed = PackVelocity(v->GetDisplayMaxSpeed(), v->type);
2638 if (v->type == VehicleType::Train ||
2639 (v->type == VehicleType::Road && _settings_game.vehicle.roadveh_acceleration_model != AccelerationModel::Original)) {
2640 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2641 if (v->type == VehicleType::Train && (_settings_game.vehicle.train_acceleration_model == AccelerationModel::Original ||
2642 Train::From(v)->GetAccelerationType() == VehicleAccelerationModel::Maglev)) {
2643 DrawString(tr, GetString(STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED, gcache->cached_weight, gcache->cached_power, max_speed));
2644 } else {
2645 DrawString(tr, GetString(STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE, gcache->cached_weight, gcache->cached_power, max_speed, gcache->cached_max_te));
2646 }
2647 } else if (v->type == VehicleType::Aircraft) {
2648 StringID type = v->GetEngine()->GetAircraftTypeText();
2649 if (Aircraft::From(v)->GetRange() > 0) {
2650 DrawString(tr, GetString(STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE, max_speed, type, Aircraft::From(v)->GetRange()));
2651 } else {
2652 DrawString(tr, GetString(STR_VEHICLE_INFO_MAX_SPEED_TYPE, max_speed, type));
2653 }
2654 } else {
2655 DrawString(tr, GetString(STR_VEHICLE_INFO_MAX_SPEED, max_speed));
2656 }
2658
2659 /* Draw profit */
2660 if (v->IsGroundVehicle()) {
2661 DrawString(tr,
2662 GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD_MIN_PERFORMANCE : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_MIN_PERFORMANCE,
2666 } else {
2667 DrawString(tr,
2668 GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
2671 }
2673
2674 /* Draw breakdown & reliability */
2675 DrawString(tr, GetString(STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS, ToPercent16(v->reliability), ToPercent16(v->GetEngine()->reliability), v->breakdowns_since_last_service));
2676 break;
2677 }
2678
2679 case WID_VD_MATRIX: {
2680 /* For trains only. */
2681 DrawVehicleDetails(v, r.Shrink(WidgetDimensions::scaled.matrix, RectPadding::zero).WithHeight(this->resize.step_height), this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->tab);
2682 break;
2683 }
2684
2685 case WID_VD_MIDDLE_DETAILS: {
2686 /* For other vehicles, at the place of the matrix. */
2687 bool rtl = _current_text_dir == TD_RTL;
2688 uint sprite_width = GetSingleVehicleWidth(v, EngineImageType::InDetails) + WidgetDimensions::scaled.framerect.Horizontal();
2689 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2690
2691 /* Articulated road vehicles use a complete line. */
2692 if (v->type == VehicleType::Road && v->HasArticulatedPart()) {
2693 DrawVehicleImage(v, tr.WithHeight(ScaleGUITrad(GetVehicleHeight(v->type)), false), VehicleID::Invalid(), EngineImageType::InDetails, 0);
2694 } else {
2695 Rect sr = tr.WithWidth(sprite_width, rtl);
2696 DrawVehicleImage(v, sr.WithHeight(ScaleGUITrad(GetVehicleHeight(v->type)), false), VehicleID::Invalid(), EngineImageType::InDetails, 0);
2697 }
2698
2699 DrawVehicleDetails(v, tr.Indent(sprite_width, rtl), 0, 0, this->tab);
2700 break;
2701 }
2702
2704 /* Draw service interval text */
2705 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2706
2707 /* We're using wallclock units. Show minutes since last serviced. */
2709 int minutes_since_serviced = (TimerGameEconomy::date - v->date_of_last_service).base() / EconomyTime::DAYS_IN_ECONOMY_MONTH;
2710 DrawString(tr.left, tr.right, CentreBounds(r.top, r.bottom, GetCharacterHeight(FontSize::Normal)),
2711 GetString(v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_MINUTES,
2712 v->GetServiceInterval(), STR_VEHICLE_DETAILS_LAST_SERVICE_MINUTES_AGO, minutes_since_serviced));
2713 break;
2714 }
2715
2716 /* We're using calendar dates. Show the date of last service. */
2717 DrawString(tr.left, tr.right, CentreBounds(r.top, r.bottom, GetCharacterHeight(FontSize::Normal)),
2718 GetString(v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS,
2719 v->GetServiceInterval(), STR_VEHICLE_DETAILS_LAST_SERVICE_DATE, v->date_of_last_service));
2720 break;
2721 }
2722 }
2723 }
2724
2726 void OnPaint() override
2727 {
2728 const Vehicle *v = Vehicle::Get(this->window_number);
2729
2730 if (v->type == VehicleType::Train) {
2731 this->LowerWidget(WID_VD_DETAILS_CARGO_CARRIED + this->tab);
2732 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2733 }
2734
2735 /* Disable service-scroller when interval is set to disabled */
2739
2740 StringID str =
2741 !v->ServiceIntervalIsCustom() ? STR_VEHICLE_DETAILS_DEFAULT :
2742 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT :
2743 TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_DETAILS_MINUTES : STR_VEHICLE_DETAILS_DAYS;
2746
2747 this->DrawWidgets();
2748 }
2749
2750 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2751 {
2752 switch (widget) {
2753 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2754 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2755 const Vehicle *v = Vehicle::Get(this->window_number);
2756 int mod;
2757 if (!v->ServiceIntervalIsPercent() && TimerGameEconomy::UsingWallclockUnits()) {
2758 mod = IsCtrlPressed() ? 1 : 5;
2759 } else {
2760 mod = IsCtrlPressed() ? 5 : 10;
2761 }
2762
2763 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2764 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2765 if (mod == v->GetServiceInterval()) return;
2766
2767 Command<Commands::ChangeServiceInterval>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, mod, true, v->ServiceIntervalIsPercent());
2768 break;
2769 }
2770
2772 const Vehicle *v = Vehicle::Get(this->window_number);
2773 ShowDropDownMenu(this,
2774 TimerGameEconomy::UsingWallclockUnits() ? _service_interval_dropdown_wallclock : _service_interval_dropdown_calendar,
2775 v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2776 break;
2777 }
2778
2782 this->SetWidgetsLoweredState(false,
2786
2788 this->SetDirty();
2789 break;
2790 }
2791 }
2792
2793 bool OnTooltip([[maybe_unused]] Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
2794 {
2796 const Vehicle *v = Vehicle::Get(this->window_number);
2797 StringID tool_tip;
2798 if (v->ServiceIntervalIsPercent()) {
2799 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_PERCENT : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_PERCENT;
2801 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_MINUTES : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_MINUTES;
2802 } else {
2803 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_DAYS : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_DAYS;
2804 }
2805 GuiShowTooltips(this, GetEncodedString(tool_tip), close_cond);
2806 return true;
2807 }
2808
2809 return false;
2810 }
2811
2812 void OnDropdownSelect(WidgetID widget, int index, int) override
2813 {
2814 switch (widget) {
2816 const Vehicle *v = Vehicle::Get(this->window_number);
2817 bool iscustom = index != 0;
2818 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2819 uint16_t interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2820 Command<Commands::ChangeServiceInterval>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, interval, iscustom, ispercent);
2821 break;
2822 }
2823 }
2824 }
2825
2826 void OnResize() override
2827 {
2829 if (nwi != nullptr) {
2830 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2831 }
2832 }
2833};
2834
2837 WindowPosition::Automatic, "view_vehicle_details_train", 405, 178,
2838 WindowClass::VehicleDetails, WindowClass::VehicleView,
2839 {},
2841);
2842
2845 WindowPosition::Automatic, "view_vehicle_details", 405, 113,
2846 WindowClass::VehicleDetails, WindowClass::VehicleView,
2847 {},
2849);
2850
2856{
2857 CloseWindowById(WindowClass::VehicleOrders, v->index, false);
2858 CloseWindowById(WindowClass::VehicleTimetable, v->index, false);
2860}
2861
2862
2863/* Unified vehicle GUI - Vehicle View Window */
2864
2866static constexpr std::initializer_list<NWidgetPart> _nested_vehicle_view_widgets = {
2869 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_VV_RENAME), SetAspect(WidgetDimensions::ASPECT_RENAME), SetSpriteTip(SPR_RENAME),
2871 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_VV_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION),
2876 EndContainer(),
2881 EndContainer(),
2882 EndContainer(),
2887 EndContainer(),
2888 /* For trains only, 'ignore signal' button. */
2891 SetSpriteTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2892 EndContainer(),
2896 SetSpriteTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2897 EndContainer(),
2901 EndContainer(),
2902 EndContainer(),
2905 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_VV_ORDER_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION, STR_VEHICLE_VIEW_ORDER_LOCATION_TOOLTIP),
2907 EndContainer(),
2908};
2909
2910/* Just to make sure, nobody has changed the vehicle type constants, as we are
2911 using them for array indexing in a number of places here. */
2912static_assert(to_underlying(VehicleType::Train) == 0);
2913static_assert(to_underlying(VehicleType::Road) == 1);
2914static_assert(to_underlying(VehicleType::Ship) == 2);
2915static_assert(to_underlying(VehicleType::Aircraft) == 3);
2916
2924
2927static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2928static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2931
2934 VCT_CMD_START_STOP = 0,
2935 VCT_CMD_CLONE_VEH,
2936 VCT_CMD_TURN_AROUND,
2937};
2938
2941 { // VCT_CMD_START_STOP
2942 STR_ERROR_CAN_T_STOP_START_TRAIN,
2943 STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE,
2944 STR_ERROR_CAN_T_STOP_START_SHIP,
2945 STR_ERROR_CAN_T_STOP_START_AIRCRAFT
2946 },
2947 { // VCT_CMD_CLONE_VEH
2948 STR_ERROR_CAN_T_BUY_TRAIN,
2949 STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
2950 STR_ERROR_CAN_T_BUY_SHIP,
2951 STR_ERROR_CAN_T_BUY_AIRCRAFT
2952 },
2953 { // VCT_CMD_TURN_AROUND
2954 STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN,
2955 STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN,
2956 INVALID_STRING_ID, // invalid for ships
2957 INVALID_STRING_ID // invalid for aircraft
2958 },
2959};
2960
2966void CcStartStopVehicle(Commands, const CommandCost &result, VehicleID veh_id, bool)
2967{
2968 if (result.Failed()) return;
2969
2970 const Vehicle *v = Vehicle::GetIfValid(veh_id);
2971 if (v == nullptr || !IsCompanyBuildableVehicleType(v) || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2972
2973 StringID msg = v->vehstatus.Test(VehState::Stopped) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2974 const Vehicle *moving_front = v->GetMovingFront();
2975 Point pt = RemapCoords(moving_front->x_pos, moving_front->y_pos, moving_front->z_pos);
2976 AddTextEffect(GetEncodedString(msg), pt.x, pt.y, Ticks::DAY_TICKS, TextEffectMode::Rising);
2977}
2978
2984void StartStopVehicle(const Vehicle *v, bool texteffect)
2985{
2986 assert(v->IsPrimaryVehicle());
2987 Command<Commands::StartStopVehicle>::Post(_vehicle_msg_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr, v->tile, v->index, false);
2988}
2989
2995static bool IsVehicleRefittable(const Vehicle *v)
2996{
2997 if (!v->IsStoppedInDepot()) return false;
2998
2999 do {
3000 if (IsEngineRefittable(v->engine_type)) return true;
3001 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
3002
3003 return false;
3004}
3005
3007struct VehicleViewWindow : Window {
3008private:
3020 bool mouse_over_start_stop = false;
3021
3027 {
3028 switch (plane) {
3029 case SEL_DC_GOTO_DEPOT:
3030 case SEL_DC_CLONE:
3031 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
3032 break;
3033
3034 case SEL_RT_REFIT:
3035 case SEL_RT_TURN_AROUND:
3036 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
3037 break;
3038
3039 default:
3040 NOT_REACHED();
3041 }
3042 }
3043
3044public:
3046 {
3048 this->CreateNestedTree();
3049
3050 /* Sprites for the 'send to depot' button indexed by vehicle type. */
3051 static constexpr VehicleTypeIndexArray<const SpriteID> vehicle_view_goto_depot_sprites = {
3056 };
3058 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->SetSprite(vehicle_view_goto_depot_sprites[v->type]);
3059
3060 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
3061 static constexpr VehicleTypeIndexArray<const SpriteID> vehicle_view_clone_sprites = {
3066 };
3067 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->SetSprite(vehicle_view_clone_sprites[v->type]);
3068
3069 switch (v->type) {
3070 case VehicleType::Train:
3071 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP);
3072 this->GetWidget<NWidgetStacked>(WID_VV_FORCE_PROCEED_SEL)->SetDisplayedPlane(0);
3073 break;
3074
3075 case VehicleType::Road:
3077 break;
3078
3079 case VehicleType::Ship:
3083 break;
3084
3085 default: NOT_REACHED();
3086 }
3088 this->owner = v->owner;
3089 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, static_cast<VehicleID>(this->window_number), ScaleZoomGUI(_vehicle_view_zoom_levels[v->type]));
3090
3091 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_STATUS_START_STOP_TOOLTIP + to_underlying(v->type));
3092 this->GetWidget<NWidgetCore>(WID_VV_RENAME)->SetToolTip(STR_VEHICLE_DETAILS_TRAIN_RENAME + to_underlying(v->type));
3093 this->GetWidget<NWidgetCore>(WID_VV_LOCATION)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_CENTER_TOOLTIP + to_underlying(v->type));
3094 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + to_underlying(v->type));
3095 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + to_underlying(v->type));
3096 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + to_underlying(v->type));
3097 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->SetToolTip(STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + to_underlying(v->type));
3098 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->SetToolTip(STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + to_underlying(v->type));
3099
3100 this->UpdatePlanes();
3101 this->UpdateButtons();
3102 }
3103
3104 void Close([[maybe_unused]] int data = 0) override
3105 {
3106 CloseWindowById(WindowClass::VehicleOrders, this->window_number, false);
3107 CloseWindowById(WindowClass::VehicleRefit, this->window_number, false);
3108 CloseWindowById(WindowClass::VehicleDetails, this->window_number, false);
3109 CloseWindowById(WindowClass::VehicleTimetable, this->window_number, false);
3110 this->Window::Close();
3111 }
3112
3113 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
3114 {
3115 const Vehicle *v = Vehicle::Get(this->window_number);
3116 switch (widget) {
3117 case WID_VV_START_STOP:
3119 break;
3120
3122 if (v->type != VehicleType::Train) {
3123 size.height = 0;
3124 size.width = 0;
3125 }
3126 break;
3127
3128 case WID_VV_VIEWPORT:
3131 break;
3132 }
3133 }
3134
3137 {
3138 const Vehicle *v = Vehicle::Get(this->window_number);
3139 bool is_localcompany = v->owner == _local_company;
3140 bool refittable_and_stopped_in_depot = IsVehicleRefittable(v);
3141
3142 this->SetWidgetDisabledState(WID_VV_RENAME, !is_localcompany);
3143 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
3144 this->SetWidgetDisabledState(WID_VV_REFIT, !refittable_and_stopped_in_depot || !is_localcompany);
3145 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
3146
3147 /* Lower the Send To Depot button when clicking it would cause the
3148 * vehicle to NOT go to the depot. */
3150
3151 if (v->type == VehicleType::Train) {
3153 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
3154 }
3155
3156 if (v->type == VehicleType::Train || v->type == VehicleType::Road) {
3157 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
3158 }
3159
3161 }
3162
3163 void OnPaint() override
3164 {
3165 const Vehicle *v = Vehicle::Get(this->window_number);
3166
3167 const Window *mainwindow = GetMainWindow();
3168 if (mainwindow->viewport->follow_vehicle == v->index) {
3170 }
3171
3172 this->DrawWidgets();
3173 }
3174
3175 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
3176 {
3177 if (widget != WID_VV_CAPTION) return this->Window::GetWidgetString(widget, stringid);
3178
3179 const Vehicle *v = Vehicle::Get(this->window_number);
3180 return GetString(STR_VEHICLE_VIEW_CAPTION, v->index);
3181 }
3182
3189 std::string GetVehicleStatusString(const Vehicle *v, ExtendedTextColour &text_colour) const
3190 {
3191 text_colour = TextColour::Black;
3192
3193 if (v->vehstatus.Test(VehState::Crashed)) return GetString(STR_VEHICLE_STATUS_CRASHED);
3194
3195 if (v->type != VehicleType::Aircraft && v->breakdown_ctr == 1) return GetString(STR_VEHICLE_STATUS_BROKEN_DOWN);
3196
3197 if (v->vehstatus.Test(VehState::Stopped) && (!mouse_over_start_stop || v->IsStoppedInDepot())) {
3198 if (v->type != VehicleType::Train) return GetString(STR_VEHICLE_STATUS_STOPPED);
3199 if (v->cur_speed != 0) return GetString(STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL, PackVelocity(v->GetDisplaySpeed(), v->type));
3200 if (Train::From(v)->gcache.cached_power == 0) return GetString(STR_VEHICLE_STATUS_TRAIN_NO_POWER);
3201 return GetString(STR_VEHICLE_STATUS_STOPPED);
3202 }
3203
3204 if (v->IsInDepot() && v->IsWaitingForUnbunching()) return GetString(STR_VEHICLE_STATUS_WAITING_UNBUNCHING);
3205
3206 if (v->type == VehicleType::Train && Train::From(v)->flags.Test(VehicleRailFlag::Stuck) && !v->current_order.IsType(OT_LOADING)) return GetString(STR_VEHICLE_STATUS_TRAIN_STUCK);
3207
3208 if (v->type == VehicleType::Aircraft && Aircraft::From(v)->flags.Test(VehicleAirFlag::DestinationTooFar) && !v->current_order.IsType(OT_LOADING)) return GetString(STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR);
3209
3210 /* Vehicle is in a "normal" state, show current order. */
3211 if (mouse_over_start_stop) {
3214 } else if (v->type == VehicleType::Train && Train::From(v)->flags.Test(VehicleRailFlag::Stuck) && !v->current_order.IsType(OT_LOADING)) {
3216 }
3217 }
3218
3219 switch (v->current_order.GetType()) {
3220 case OT_GOTO_STATION:
3221 return GetString(v->vehicle_flags.Test(VehicleFlag::PathfinderLost) ? STR_VEHICLE_STATUS_CANNOT_REACH_STATION_VEL : STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL,
3223
3224 case OT_GOTO_DEPOT: {
3225 /* This case *only* happens when multiple nearest depot orders
3226 * follow each other (including an order list only one order: a
3227 * nearest depot order) and there are no reachable depots.
3228 * It is primarily to guard for the case that there is no
3229 * depot with index 0, which would be used as fallback for
3230 * evaluating the string in the status bar. */
3231 if (v->current_order.GetDestination() == DepotID::Invalid()) return {};
3232
3235 return GetStringWithArgs(v->vehicle_flags.Test(VehicleFlag::PathfinderLost) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL, params);
3236 }
3237
3239 return GetStringWithArgs(v->vehicle_flags.Test(VehicleFlag::PathfinderLost) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_UNBUNCH_VEL, params);
3240 }
3241
3242 return GetStringWithArgs(v->vehicle_flags.Test(VehicleFlag::PathfinderLost) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL, params);
3243 }
3244
3245 case OT_LOADING:
3246 return GetString(STR_VEHICLE_STATUS_LOADING_UNLOADING);
3247
3248 case OT_GOTO_WAYPOINT:
3249 assert(v->type == VehicleType::Train || v->type == VehicleType::Road || v->type == VehicleType::Ship);
3250 return GetString(v->vehicle_flags.Test(VehicleFlag::PathfinderLost) ? STR_VEHICLE_STATUS_CANNOT_REACH_WAYPOINT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL,
3252
3253 case OT_LEAVESTATION:
3254 if (v->type != VehicleType::Aircraft) {
3255 return GetString(STR_VEHICLE_STATUS_LEAVING);
3256 }
3257 [[fallthrough]];
3258
3259 default:
3260 if (v->GetNumManualOrders() == 0) {
3261 return GetString(STR_VEHICLE_STATUS_NO_ORDERS_VEL, PackVelocity(v->GetDisplaySpeed(), v->type));
3262 }
3263
3264 return {};
3265 }
3266 }
3267
3268 void DrawWidget(const Rect &r, WidgetID widget) const override
3269 {
3270 if (widget != WID_VV_START_STOP) return;
3271
3272 /* Draw the flag plus orders. */
3273 bool rtl = (_current_text_dir == TD_RTL);
3275 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
3276
3277 const Vehicle *v = Vehicle::Get(this->window_number);
3279 DrawSpriteIgnorePadding(image, PAL_NONE, tr.WithWidth(icon_width, rtl), {AlignmentH::Centre, AlignmentV::Middle});
3280
3281 tr = tr.Indent(icon_width + WidgetDimensions::scaled.imgbtn.Horizontal(), rtl);
3282
3284 std::string str = GetVehicleStatusString(v, text_colour);
3285 DrawString(tr.left, tr.right, CentreBounds(tr.top, tr.bottom, GetCharacterHeight(FontSize::Normal)), str, text_colour, AlignmentH::Centre);
3286 }
3287
3288 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
3289 {
3290 const Vehicle *v = Vehicle::Get(this->window_number);
3291
3292 switch (widget) {
3293 case WID_VV_RENAME: { // rename
3294 ShowQueryString(GetString(STR_VEHICLE_NAME, v->index), STR_QUERY_RENAME_TRAIN_CAPTION + to_underlying(v->type),
3295 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
3296 break;
3297 }
3298
3299 case WID_VV_START_STOP: // start stop
3300 StartStopVehicle(v, false);
3301 break;
3302
3303 case WID_VV_ORDER_LOCATION: {
3304 /* Scroll to current order destination */
3305 TileIndex tile = v->current_order.GetLocation(v);
3306 if (tile == INVALID_TILE) break;
3307
3308 if (IsCtrlPressed()) {
3310 } else {
3312 }
3313 break;
3314 }
3315
3316 case WID_VV_LOCATION: // center main view
3317 if (IsCtrlPressed()) {
3319 } else {
3320 const Window *mainwindow = GetMainWindow();
3321 if (click_count > 1) {
3322 /* main window 'follows' vehicle */
3323 mainwindow->viewport->follow_vehicle = v->index;
3324 } else {
3325 if (mainwindow->viewport->follow_vehicle == v->index) mainwindow->viewport->follow_vehicle = VehicleID::Invalid();
3326 const Vehicle *moving_front = v->GetMovingFront();
3327 ScrollMainWindowTo(moving_front->x_pos, moving_front->y_pos, moving_front->z_pos);
3328 }
3329 }
3330 break;
3331
3332 case WID_VV_GOTO_DEPOT: // goto hangar
3333 Command<Commands::SendVehicleToDepot>::Post(GetCmdSendToDepotMsg(v), v->index, IsCtrlPressed() ? DepotCommandFlag::Service : DepotCommandFlags{}, {});
3334 break;
3335 case WID_VV_REFIT: // refit
3337 break;
3338 case WID_VV_SHOW_ORDERS: // show orders
3339 if (IsCtrlPressed()) {
3341 } else {
3342 ShowOrdersWindow(v);
3343 }
3344 break;
3345 case WID_VV_SHOW_DETAILS: // show details
3346 if (IsCtrlPressed()) {
3348 } else {
3350 }
3351 break;
3352 case WID_VV_CLONE: // clone vehicle
3353 /* Suppress the vehicle GUI when share-cloning.
3354 * There is no point to it except for starting the vehicle.
3355 * For starting the vehicle the player has to open the depot GUI, which is
3356 * most likely already open, but is also visible in the vehicle viewport. */
3357 Command<Commands::CloneVehicle>::Post(_vehicle_msg_translation_table[VCT_CMD_CLONE_VEH][v->type],
3358 IsCtrlPressed() ? nullptr : CcCloneVehicle,
3359 v->tile, v->index, IsCtrlPressed());
3360 break;
3361 case WID_VV_TURN_AROUND: // turn around
3362 assert(v->IsGroundVehicle());
3363 if (v->type == VehicleType::Road) {
3364 Command<Commands::TurnRoadVehicle>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index);
3365 } else {
3366 Command<Commands::ReverseTrainDirection>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index, false);
3367 }
3368 break;
3369 case WID_VV_FORCE_PROCEED: // force proceed
3370 assert(v->type == VehicleType::Train);
3371 Command<Commands::ForceTrainProceed>::Post(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL, v->tile, v->index);
3372 break;
3373 }
3374 }
3375
3376 EventState OnHotkey(int hotkey) override
3377 {
3378 /* If the hotkey is not for any widget in the UI (i.e. for honking) */
3379 if (hotkey == WID_VV_HONK_HORN) {
3380 const Window *mainwindow = GetMainWindow();
3382 /* Only play the sound if we're following this vehicle */
3383 if (mainwindow->viewport->follow_vehicle == v->index) {
3384 v->PlayLeaveStationSound(true);
3385 }
3386 }
3387 return Window::OnHotkey(hotkey);
3388 }
3389
3390 void OnQueryTextFinished(std::optional<std::string> str) override
3391 {
3392 if (!str.has_value()) return;
3393
3394 Command<Commands::RenameVehicle>::Post(STR_ERROR_CAN_T_RENAME_TRAIN + to_underlying(Vehicle::Get(this->window_number)->type), static_cast<VehicleID>(this->window_number), *str);
3395 }
3396
3397 void OnMouseOver([[maybe_unused]] Point pt, WidgetID widget) override
3398 {
3399 bool start_stop = widget == WID_VV_START_STOP;
3400 if (start_stop != mouse_over_start_stop) {
3401 mouse_over_start_stop = start_stop;
3403 }
3404 }
3405
3406 void OnMouseWheel(int wheel, WidgetID widget) override
3407 {
3408 if (widget != WID_VV_VIEWPORT) return;
3409 if (_settings_client.gui.scrollwheel_scrolling != ScrollWheelScrolling::Off) {
3410 DoZoomInOutWindow(wheel < 0 ? ZOOM_IN : ZOOM_OUT, this);
3411 }
3412 }
3413
3414 void OnResize() override
3415 {
3416 if (this->viewport != nullptr) {
3418 nvp->UpdateViewportCoordinates(this);
3419 }
3420 }
3421
3424 {
3425 const Vehicle *v = Vehicle::Get(this->window_number);
3426 bool veh_stopped = v->IsStoppedInDepot();
3427
3428 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
3429 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
3430 */
3431 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
3432 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
3433 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
3434 this->SelectPlane(plane);
3435 }
3436 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
3437 if (v->IsGroundVehicle()) {
3438 plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
3440 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
3441 this->SelectPlane(plane);
3442 }
3443 }
3444 }
3445
3451 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
3452 {
3453 if (data == VIWD_AUTOREPLACE) {
3454 /* Autoreplace replaced the vehicle.
3455 * Nothing to do for this window. */
3456 return;
3457 }
3458
3459 this->UpdatePlanes();
3460 this->UpdateButtons();
3461 this->SetDirty();
3462 }
3463
3464 bool IsNewGRFInspectable() const override
3465 {
3466 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3467 }
3468
3469 void ShowNewGRFInspectWindow() const override
3470 {
3471 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3472 }
3473
3474 static inline HotkeyList hotkeys{"vehicleview", {
3475 Hotkey('H', "honk", WID_VV_HONK_HORN),
3476 }};
3477};
3478
3481 WindowPosition::Automatic, "view_vehicle", 250, 116,
3482 WindowClass::VehicleView, WindowClass::None,
3483 {},
3485 &VehicleViewWindow::hotkeys
3486);
3487
3493 WindowPosition::Automatic, "view_vehicle_train", 250, 134,
3494 WindowClass::VehicleView, WindowClass::None,
3495 {},
3497 &VehicleViewWindow::hotkeys
3498);
3499
3508
3515{
3516 assert(v != nullptr);
3517 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3518
3519 v = v->First();
3520 if (!v->IsPrimaryVehicle()) return false;
3521
3522 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
3523}
3524
3531bool VehicleClicked(VehicleList::const_iterator begin, VehicleList::const_iterator end)
3532{
3533 assert(begin != end);
3534 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3535
3536 /* If there is only one vehicle in the group, act as if we clicked a single vehicle */
3537 if (begin + 1 == end) return _thd.GetCallbackWnd()->OnVehicleSelect(*begin);
3538
3539 return _thd.GetCallbackWnd()->OnVehicleSelect(begin, end);
3540}
3541
3547bool VehicleClicked(const GUIVehicleGroup &vehgroup)
3548{
3549 return VehicleClicked(vehgroup.vehicles_begin, vehgroup.vehicles_end);
3550}
3551
3552void StopGlobalFollowVehicle(const Vehicle *v)
3553{
3554 Window *w = GetMainWindow();
3555 if (w->viewport->follow_vehicle == v->index) {
3556 const Vehicle *moving_front = v->GetMovingFront();
3557 ScrollMainWindowTo(moving_front->x_pos, moving_front->y_pos, moving_front->z_pos, true); // lock the main view on the vehicle's last position
3558 w->viewport->CancelFollow(*w);
3559 }
3560}
3561
3562
3568void CcBuildPrimaryVehicle(Commands, const CommandCost &result, VehicleID new_veh_id, uint, uint16_t, CargoArray)
3569{
3570 if (result.Failed()) return;
3571
3572 const Vehicle *v = Vehicle::Get(new_veh_id);
3574}
3575
3583{
3584 switch (v->type) {
3585 case VehicleType::Train:
3586 return Train::From(v)->GetDisplayImageWidth();
3587
3588 case VehicleType::Road:
3590
3591 default:
3592 bool rtl = _current_text_dir == TD_RTL;
3593 VehicleSpriteSeq seq;
3594 v->GetImage(rtl ? Direction::E : Direction::W, image_type, &seq);
3595 Rect rec;
3596 seq.GetBounds(&rec);
3597 return UnScaleGUI(rec.Width());
3598 }
3599}
3600
3607int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
3608{
3609 if (v->type == VehicleType::Train || v->type == VehicleType::Road) {
3610 int vehicle_width = 0;
3611 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
3612 vehicle_width += GetSingleVehicleWidth(u, image_type);
3613 }
3614 return vehicle_width;
3615 } else {
3616 return GetSingleVehicleWidth(v, image_type);
3617 }
3618}
3619
3626{
3627 bool rtl = _current_text_dir == TD_RTL;
3628
3629 _cursor.sprites.clear();
3630 int total_width = 0;
3631 int y_offset = 0;
3632 bool rotor_seq = false; // Whether to draw the rotor of the vehicle in this step.
3633 bool is_ground_vehicle = v->IsGroundVehicle();
3634
3635 while (v != nullptr) {
3636 if (total_width >= ScaleSpriteTrad(2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH)) break;
3637
3639 VehicleSpriteSeq seq;
3640
3641 if (rotor_seq) {
3642 GetCustomRotorSprite(Aircraft::From(v), image_type, &seq);
3643 if (!seq.IsValid()) seq.Set(SPR_ROTOR_STOPPED);
3644 y_offset = -ScaleSpriteTrad(5);
3645 } else {
3646 v->GetImage(rtl ? Direction::E : Direction::W, image_type, &seq);
3647 }
3648
3649 int x_offs = 0;
3650 if (v->type == VehicleType::Train) x_offs = Train::From(v)->GetCursorImageOffset();
3651
3652 for (uint i = 0; i < seq.count; ++i) {
3653 PaletteID pal2 = v->vehstatus.Test(VehState::Crashed) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
3654 _cursor.sprites.emplace_back(seq.seq[i].sprite, pal2, rtl ? (-total_width + x_offs) : (total_width + x_offs), y_offset);
3655 }
3656
3657 if (v->type == VehicleType::Aircraft && v->subtype == AIR_HELICOPTER && !rotor_seq) {
3658 /* Draw rotor part in the next step. */
3659 rotor_seq = true;
3660 } else {
3661 total_width += GetSingleVehicleWidth(v, image_type);
3662 v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
3663 }
3664 }
3665
3666 if (is_ground_vehicle) {
3667 /* Center trains and road vehicles on the front vehicle */
3668 int offs = (ScaleSpriteTrad(VEHICLEINFO_FULL_VEHICLE_WIDTH) - total_width) / 2;
3669 if (rtl) offs = -offs;
3670 for (auto &cs : _cursor.sprites) {
3671 cs.pos.x += offs;
3672 }
3673 }
3674
3676}
Base for aircraft.
@ DestinationTooFar
Next destination is too far away.
Definition aircraft.h:37
@ AIR_HELICOPTER
an helicopter
Definition aircraft.h:29
void DrawAircraftImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type)
Draws an image of an aircraft.
CargoTypes GetUnionOfArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type)
Ors the refit_masks of all articulated parts.
Functions related to articulated vehicles.
void ShowReplaceGroupVehicleWindow(GroupID id_g, VehicleType vehicletype)
Show the autoreplace configuration window for a particular group.
Functions related to the autoreplace GUIs.
@ PathfinderLost
Vehicle's pathfinder is lost.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr bool HasAtMostOneBit(T value)
Test whether value has at most 1 bit set.
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoLabel CT_MAIL
Cargo label for mail.
Definition cargo_type.h:34
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Dimension GetLargestCargoIconSize()
Get dimensions of largest cargo icon.
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition cargotype.cpp:30
CargoType GetCargoTypeByLabel(CargoLabel label)
Get cargo assigned to a label.
Definition cargotype.h:268
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr Timpl & Set()
Set all bits.
Common return value for all commands.
bool Failed() const
Did this command fail?
static constexpr int DAYS_IN_ECONOMY_MONTH
Days in an economy month, when in wallclock timekeeping mode.
StringID GetAircraftTypeText() const
Get the name of the aircraft type for display purposes.
Definition engine.cpp:496
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:51
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition engine.cpp:196
bool(const GUIVehicleGroup *item, CargoType filter) FilterFunction
Baseclass for nested widgets.
virtual void SetDirty(const Window *w) const
Mark the widget as 'dirty' (in need of repaint).
Definition widget.cpp:955
uint current_x
Current horizontal size (after resizing).
int pos_x
Horizontal position of top-left corner of the widget in the window.
uint current_y
Current vertical size (after resizing).
Base class for a 'real' widget.
void SetStringTip(StringID string, StringID tool_tip)
Set string and tool tip of the nested widget.
Definition widget.cpp:1200
Stacked widgets, widgets all occupying the same space in the window.
int shown_plane
Plane being displayed (for NWID_SELECTION only).
bool SetDisplayedPlane(int plane)
Select which plane to show (for NWID_SELECTION only).
Definition widget.cpp:1458
Nested widget to display a viewport in a window.
void UpdateViewportCoordinates(Window *w)
Update the position and size of the viewport (after eg a resize).
Definition widget.cpp:2451
Scrollbar data structure.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
void ScrollTowards(size_type position)
Scroll towards the given position; if the item is visible nothing happens, otherwise it will be shown...
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
void SetStepSize(size_t stepsize)
Set the distance to scroll when using the buttons or the wheel.
size_type GetPosition() const
Gets the position of the first visible element in the list.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGame< struct Economy >::Date MAX_DATE
static constexpr TimerGame< struct Economy >::Year MAX_YEAR
static Date date
Current date in days (day counter).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static constexpr Year DateToYear(Date date)
static constexpr Date DateAtStartOfYear(Year year)
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
Functions related to commands.
@ QueryCost
query cost only, don't build.
Commands
List of commands.
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Notice
Notice.
Definition debug_type.h:18
Command definitions related to depots.
void CcCloneVehicle(Commands, const CommandCost &result, VehicleID veh_id)
This is the Callback method after the cloning attempt of a vehicle.
Map related accessors for depots.
DestinationID GetDepotDestinationIndex(Tile t)
Get the destination index of a 'depot'.
Definition depot_map.h:69
void ShowDropDownMenu(Window *w, std::span< const StringID > strings, int selected, WidgetID button, uint32_t disabled_mask, uint32_t hidden_mask, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a dropdown menu window near a widget of the parent window.
Definition dropdown.cpp:633
std::unique_ptr< DropDownListItem > MakeDropDownListDividerItem()
Creates new DropDownListDividerItem.
Definition dropdown.cpp:36
std::unique_ptr< DropDownListItem > MakeDropDownListIconItem(SpriteID sprite, PaletteID palette, StringID str, int value, bool masked, bool shaded)
Creates new DropDownListIconItem.
Definition dropdown.cpp:70
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
Dimension GetDropDownListDimension(const DropDownList &list)
Determine width and height required to fully display a DropDownList.
Definition dropdown.cpp:551
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Functions related to the drop down widget.
Types related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
@ Filterable
Set if the dropdown is filterable.
bool IsEngineRefittable(EngineID engine)
Check if an engine is refittable.
Definition engine.cpp:1327
Functions related to engines.
@ AutoRefit
Automatic refitting is allowed.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
@ Maglev
Maglev acceleration model.
Definition engine_type.h:49
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ Centre
Align to the centre.
@ Start
Align to the start, LTR/RTL aware.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
void UpdateCursorSize()
Update cursor dimension.
Definition gfx.cpp:1617
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
Dimension GetStringListBoundingBox(std::span< const StringID > list, FontSize fontsize)
Get maximum dimension of a list of strings.
Definition gfx.cpp:933
uint GetStringListWidth(std::span< const StringID > list, FontSize fontsize)
Get maximum width of a list of strings.
Definition gfx.cpp:918
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsShiftPressed()
Test if the shift key is pressed.
Definition gfx_func.h:88
Dimension GetScaledSpriteSize(SpriteID sprid)
Scale sprite size for GUI.
Definition widget.cpp:70
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
void DrawSpriteIgnorePadding(SpriteID img, PaletteID pal, const Rect &r, Alignment align)
Draw a sprite within a Rect, ignoring the sprite's padding.
Definition widget.cpp:350
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ White
White.
Definition gfx_type.h:300
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Orange
Orange.
Definition gfx_type.h:297
@ Grey
Grey.
Definition gfx_type.h:299
@ Forced
Ignore colour changes from strings.
Definition gfx_type.h:343
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:315
@ White
White colour.
Definition gfx_type.h:330
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Orange
Orange colour.
Definition gfx_type.h:324
@ Blue
Blue colour.
Definition gfx_type.h:318
@ Black
Black colour.
Definition gfx_type.h:334
@ Red
Red colour.
Definition gfx_type.h:321
constexpr NWidgetPart SetMatrixDataTip(uint32_t cols, uint32_t rows, StringID tip={})
Widget part function for setting the data and tooltip of WWT_MATRIX widgets.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetArrowWidgetTypeTip(ArrowWidgetType widget_type, StringID tip={})
Widget part function for setting the arrow widget type and tooltip.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
Command definitions related to engine groups.
void CcAddVehicleNewGroup(Commands, const CommandCost &result, GroupID new_group, GroupID, VehicleID, bool, const VehicleListIdentifier &)
Open rename window after adding a vehicle to a new group via drag and drop.
static const CursorID SPR_CURSOR_MOUSE
Definition sprites.h:1568
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void ShowCompanyGroup(CompanyID company, VehicleType vehicle_type, GroupID group)
Show the group window for the given company and vehicle type.
void ShowCompanyGroupForVehicle(const Vehicle *v)
Show the group window for the given vehicle.
Functions/definitions that have something to do with groups.
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
static constexpr GroupID ALL_GROUP
All vehicles are in this group.
Definition group_type.h:17
static constexpr GroupID NEW_GROUP
Sentinel for a to-be-created group.
Definition group_type.h:16
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
Hotkey related functions.
static bool CargoFilter(const Industry *const *industry, const std::pair< CargoType, CargoType > &cargoes)
Cargo filter functions.
Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:81
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:88
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
constexpr uint ToPercent16(uint i)
Converts a "fract" value 0..65535 to "percent" value 0..100.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition misc_gui.cpp:690
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
static constexpr CargoType CF_FREIGHT
Show only vehicles which carry any freight (non-passenger) cargo.
Definition cargo_type.h:100
static constexpr CargoType CF_NONE
Show only items which do not carry cargo (e.g. train engines).
Definition cargo_type.h:98
static constexpr CargoType CF_ANY
Show all items independent of carried cargo (i.e. no filtering).
Definition cargo_type.h:97
GrfSpecFeature GetGrfSpecFeature(VehicleType type)
Get the GrfSpecFeature associated with a VehicleType.
Definition newgrf.cpp:1889
EnumBitSet< VehicleCallbackMask, uint16_t > VehicleCallbackMasks
Bitset of VehicleCallbackMask elements.
@ CargoSuffix
Show suffix after cargo name.
@ CBID_VEHICLE_CARGO_SUFFIX
Determine the cargo "suffixes" for each refit possibility of a cargo.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Functions/types related to NewGRF debugging.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
StringID GetGRFStringID(GrfID grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
@ Vehicle
Vehicle news item. (new engine available).
Definition news_type.h:84
uint16_t GetServiceIntervalClamped(int interval, bool ispercent)
Clamp the service interval to the correct min/max.
Command definitions related to orders.
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related).
Definition order_type.h:18
@ Halt
Service the vehicle and then halt it.
Definition order_type.h:120
@ Unbunch
Service the vehicle and then unbunch it.
Definition order_type.h:122
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel).
Definition order_type.h:39
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
@ Normal
Normal colour shade.
Road vehicle states.
Command definitions related to road vehicles.
void DrawRoadVehImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip)
Draws an image of a road vehicle chain.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
@ Off
Scroll wheel has no effect.
void DrawShipImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type)
Draws an image of a ship.
Definition ship_gui.cpp:30
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
Scrolls the main window to given coordinates.
static const SpriteID SPR_SEND_ROADVEH_TODEPOT
Definition sprites.h:1087
static const SpriteID SPR_REFIT_VEHICLE
Definition sprites.h:1094
static const SpriteID SPR_SHOW_ORDERS
Definition sprites.h:1092
static const SpriteID SPR_FORCE_VEHICLE_TURN
Definition sprites.h:1095
static const SpriteID SPR_WARNING_SIGN
Warning sign (shown if there are any newgrf errors).
Definition sprites.h:76
static const SpriteID SPR_SEND_TRAIN_TODEPOT
Definition sprites.h:1086
static const PaletteID PALETTE_ALL_BLACK
Exchange any colour by black, needed for painting fictive tiles outside map.
Definition sprites.h:1800
static const SpriteID SPR_CLONE_AIRCRAFT
Definition sprites.h:115
static const SpriteID SPR_FLAG_VEH_STOPPED
Vehicle sprite-flags (red/green).
Definition sprites.h:1098
static const SpriteID SPR_CIRCLE_FOLDED
(+) icon.
Definition sprites.h:97
static const SpriteID SPR_FLAG_VEH_RUNNING
Vehicle sprite-flags (red/green).
Definition sprites.h:1099
static const SpriteID SPR_CLONE_ROADVEH
Definition sprites.h:113
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const SpriteID SPR_ROTOR_STOPPED
Definition sprites.h:1107
static const SpriteID SPR_IGNORE_SIGNALS
Definition sprites.h:1091
static const SpriteID SPR_CLONE_TRAIN
Definition sprites.h:112
static const SpriteID SPR_CIRCLE_UNFOLDED
(-) icon.
Definition sprites.h:98
static const SpriteID SPR_SEND_AIRCRAFT_TODEPOT
Definition sprites.h:1088
static const SpriteID SPR_EMPTY
Empty (transparent blue) sprite.
Definition sprites.h:46
static const SpriteID SPR_SHOW_VEHICLE_DETAILS
Definition sprites.h:1093
static const SpriteID SPR_SEND_SHIP_TODEPOT
Definition sprites.h:1089
static const SpriteID SPR_CLONE_SHIP
Definition sprites.h:114
Base classes/functions for stations.
Definition of base types and functions in a cross-platform compatible way.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:235
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
static void PrepareArgsForNextRun(std::span< StringParameter > args)
Prepare the string parameters for the next formatting run, resetting the type information.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
int64_t PackVelocity(uint speed, VehicleType type)
Pack velocity and vehicle type for use with SCC_VELOCITY string parameter.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
@ TD_RTL
Text is written right-to-left by default.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:75
std::string name
Name of vehicle.
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TimerGameTick::Ticks lateness_counter
How many ticks late (or early if negative) this vehicle is.
void SetCargoFilter(CargoType cargo_type)
Set cargo filter for the vehicle group list.
VehicleListIdentifier vli
Identifier of the vehicle list we want to currently show.
static const VehicleTypeIndexArray< const StringID > vehicle_depot_name
List of depot name strings for each VehicleType.
void DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
Draw all the vehicle list items.
VehicleID vehicle_sel
Selected vehicle.
Listing * sorting
Pointer to the vehicle type related sorting.
GroupBy grouping
How we want to group the list.
Dimension GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_create)
Compute the size for the Action dropdown.
uint order_arrow_width
Width of the arrow in the small order list.
uint8_t unitnumber_digits
The number of digits of the highest unit number.
DropDownList BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_create)
Display the Action dropdown window.
VehicleList vehicles
List of vehicles. This is the buffer for vehgroups to point into; if this is structurally modified,...
GUIVehicleGroupList vehgroups
List of (groups of) vehicles. This stores iterators of vehicles, and should be rebuilt if vehicles is...
void SetCargoFilterArray()
Populate the filter list and set the cargo filter criteria.
DropDownList BuildCargoDropDownList(bool full) const
Build drop down list for cargo filter selection.
void OnInit() override
Notification that the nested widget tree gets initialized.
CargoType cargo_filter_criteria
Selected cargo filter index.
void FilterVehicleList()
Filter the engine list against the currently selected cargo filter.
VehicleType type
Type of vehicle.
Class for storing amounts of cargo.
Definition cargo_type.h:120
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
SpriteID GetCargoIcon() const
Get sprite for showing cargo of this type.
StringID name
Name of this type of cargo.
Definition cargotype.h:93
Comparator to sort CargoType by according to desired order.
Definition cargotype.h:294
T y
Y coordinate.
T x
X coordinate.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
EngineMiscFlags misc_flags
Miscellaneous flags.
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
VehicleList::const_iterator vehicles_end
Pointer to past-the-end element of this vehicle group.
VehicleList::const_iterator vehicles_begin
Pointer to beginning element of this vehicle group.
Cached, frequently calculated values.
uint32_t cached_weight
Total weight of the consist (valid only for the first engine).
uint32_t cached_power
Total power of the consist (valid only for the first engine).
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
uint32_t cached_max_te
Maximum tractive effort of consist (valid only for the first engine).
List of hotkeys for a window.
Definition hotkeys.h:44
All data for a single hotkey.
Definition hotkeys.h:20
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:383
VehicleOrderID GetNext(VehicleOrderID cur) const
Get the order after the given one or the first one, if the given one is the last one.
Definition order_base.h:472
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
TileIndex GetLocation(const Vehicle *v, bool airport=false) const
Returns a tile somewhat representing the order destination (not suitable for pathfinding).
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
OrderType GetType() const
Get the type of order of this order.
Definition order_base.h:72
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition order_base.h:175
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Vehicle * Get(auto index)
static Vehicle * GetIfValid(auto index)
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
int Width() const
Get width of Rect.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Rect WithX(int new_left, int new_right) const
Create a new Rect, replacing the left and right coordinates.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
Rect Expand(int s) const
Copy and expand Rect by s pixels.
Option to refit a vehicle chain.
StringID string
GRF-local String to display for the cargo.
CargoType cargo
Cargo to refit to.
uint8_t subtype
Subcargo to use.
bool operator==(const RefitOption &other) const
Equality operator for RefitOption.
Refit cargo window.
void OnInit() override
Notification that the nested widget tree gets initialized.
uint information_width
Width required for correctly displaying all cargoes in the information panel.
void SetSelection(uint click_row)
Select a row.
void BuildRefitList()
Collects all (cargo, subcargo) refit options of a vehicle chain.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
int sprite_left
Left position of the vehicle sprite.
void RefreshScrollbar()
Refresh scrollbar after selection changed.
RefitOptions refit_list
List of refit subtypes available for each sorted cargo.
void OnMouseDrag(Point pt, WidgetID widget) override
An 'object' is being dragged at the provided position, highlight the target if possible.
void OnResize() override
Called after the window got resized.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
const RefitOption * selected_refit
Selected refit option.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
uint vehicle_margin
Margin to use while selecting vehicles when the vehicle image is centered.
uint8_t num_vehicles
Number of selected vehicles.
bool auto_refit
Select cargo for auto-refitting.
int sprite_right
Right position of the vehicle sprite.
VehicleOrderID order
If not INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
VehicleID selected_vehicle
First vehicle in the current selection.
void OnPaint() override
The window must be repainted.
void OnDragDrop(Point pt, WidgetID widget) override
A dragged 'object' has been released.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
Scrollbar * hscroll
Only used for long vehicles.
int vehicle_width
Width of the vehicle being drawn.
Scrollbar * vscroll
The main scrollbar.
int click_x
Position of the first click while dragging.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
std::string GetCapacityString(const RefitOption &option) const
Gets the StringID to use for displaying capacity.
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a road vehicle image in the GUI.
static bool IsExpected(const BaseStation *st)
T * Next() const
Get next vehicle in the chain.
static Train * From(Vehicle *v)
'Train' is either a loco or a wagon.
Definition train.h:97
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
int GetCursorImageOffset() const
Get the offset for train image when it is used as cursor.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Default settings for vehicles.
uint16_t servint_aircraft
service interval for aircraft
uint16_t servint_roadveh
service interval for road vehicles
uint16_t servint_ships
service interval for ships
uint16_t servint_trains
service interval for trains
bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
Event to display a custom tooltip.
uint GetRoadVehDetailsHeight(const Vehicle *v)
Gets the desired height for the road vehicle details panel.
static void DrawVehicleDetails(const Vehicle *v, const Rect &r, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
Draw the details for the given vehicle at the position of the Details windows.
void OnPaint() override
Repaint vehicle details window.
static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
Checks whether service interval is enabled for the vehicle.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnResize() override
Called after the window got resized.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
VehicleDetailsWindow(WindowDesc &desc, WindowNumber window_number)
Initialize a newly created vehicle details window.
TrainDetailsWindowTabs tab
For train vehicles: which tab is displayed.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
The information about a vehicle list.
Definition vehiclelist.h:32
VehicleListType type
The type of vehicle list.
Definition vehiclelist.h:33
WindowNumber ToWindowNumber() const
Pack a VehicleListIdentifier in 32 bits so it can be used as unique WindowNumber.
VehicleType vtype
The vehicle type associated with this list.
Definition vehiclelist.h:34
Window for the (old) vehicle listing.
void OnMouseLoop() override
Called for every mouse loop run, which is at least once per (game) tick.
void OnResize() override
Called after the window got resized.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnPaint() override
The window must be repainted.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
CaptionPlanes
Enumeration of planes of the title row at the top.
@ BP_SHARED_ORDERS
Show the normal caption.
@ BP_NORMAL
Show shared orders caption and buttons.
void OnGameTick() override
Called once per (game) tick.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
~VehicleListWindow() override
Save the last sorting state.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
ButtonPlanes
Enumeration of planes of the button row at the bottom.
@ BP_HIDE_BUTTONS
Show the empty panel.
@ BP_SHOW_BUTTONS
Show the buttons.
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:125
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
Window manager class for viewing a vehicle.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
void OnResize() override
Called after the window got resized.
void ShowNewGRFInspectWindow() const override
Show the NewGRF inspection window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void SelectPlane(PlaneSelections plane)
Display a plane in the window.
PlaneSelections
Display planes available in the vehicle view window.
@ SEL_RT_BASEPLANE
First plane of the WID_VV_SELECT_REFIT_TURN stacked widget.
@ SEL_RT_TURN_AROUND
Display 'turn around' button in WID_VV_SELECT_REFIT_TURN stacked widget.
@ SEL_DC_BASEPLANE
First plane of the WID_VV_SELECT_DEPOT_CLONE stacked widget.
@ SEL_RT_REFIT
Display 'refit' button in WID_VV_SELECT_REFIT_TURN stacked widget.
@ SEL_DC_GOTO_DEPOT
Display 'goto depot' button in WID_VV_SELECT_DEPOT_CLONE stacked widget.
@ SEL_DC_CLONE
Display 'clone vehicle' button in WID_VV_SELECT_DEPOT_CLONE stacked widget.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnMouseOver(Point pt, WidgetID widget) override
The mouse is currently moving over the window or has just moved outside of the window.
void UpdatePlanes()
Selects appropriate plane for current state of the shown vehicle.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnPaint() override
The window must be repainted.
std::string GetVehicleStatusString(const Vehicle *v, ExtendedTextColour &text_colour) const
Get the status of the vehicle.
EventState OnHotkey(int hotkey) override
A hotkey has been pressed.
void UpdateButtons()
Update buttons state to match shown vehicle.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnMouseWheel(int wheel, WidgetID widget) override
The mouse wheel has been turned.
bool IsNewGRFInspectable() const override
Is the data related to this window NewGRF inspectable?
Vehicle data structure.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
EngineID engine_type
The type of engine used for this vehicle.
virtual int GetDisplaySpeed() const
Gets the speed in km-ish/h that can be sent into string parameters for string processing.
int32_t z_pos
z coordinate.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:750
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Vehicle * GetNextArticulatedPart() const
Get the next part of an articulated engine.
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
uint8_t subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
bool HasArticulatedPart() const
Check if an engine has an articulated part.
uint8_t breakdown_ctr
Counter for managing breakdown events.
GroupID group_id
Index of group Pool array.
virtual int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into string parameters for string processing.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
VehStates vehstatus
Status.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
CargoType cargo_type
type of cargo this vehicle is carrying
VehicleOrderID GetNumManualOrders() const
Get the number of manually added orders this vehicle has.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Order current_order
The current order (+ status, like: loading).
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition vehicle.cpp:760
OrderList * orders
Pointer to the order list for this vehicle.
uint32_t GetDisplayMinPowerToWeight() const
Calculates the minimum power-to-weight ratio using the maximum weight of the ground vehicle.
Definition vehicle.cpp:3316
Vehicle * GetMovingFront() const
Get the moving front of the vehicle chain.
Money value
Value of the vehicle.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
VehicleCache vcache
Cache of often used vehicle values.
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition vehicle.cpp:3212
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Money GetDisplayProfitLastYear() const
Gets the profit vehicle had last year.
uint16_t cur_speed
current speed
uint8_t cargo_subtype
Used for livery refits (NewGRF variations).
TimerGameCalendar::Date age
Age in calendar days.
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2581
Money GetDisplayRunningCost() const
Gets the running cost of a vehicle that can be sent into string parameters for string processing.
uint8_t breakdowns_since_last_service
Counter for the amount of breakdowns.
TimerGameCalendar::Date max_age
Maximum age.
uint16_t reliability
Reliability.
Vehicle * FirstShared() const
Get the first vehicle of this vehicle chain.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
virtual void PlayLeaveStationSound(bool force=false) const
Play the sound associated with leaving the station.
virtual bool IsInDepot() const
Check whether the vehicle is in the depot.
TileIndex tile
Current tile index.
Owner owner
Which company owns the vehicle?
UnitID unitnumber
unit number, for display purposes only
virtual void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
GrfID GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition vehicle.cpp:770
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
void CloseChildWindows(WindowClass wc=WindowClass::Invalid) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1122
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
static int SortButtonWidth()
Get width of up/down arrow of sort button state.
Definition widget.cpp:839
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
Window * parent
Parent window.
Definition window_gui.h:327
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:514
void DrawSortButton(WidgetID widget, bool descending) const
Draw a sort button's up or down arrow symbol.
Definition widget.cpp:824
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
void SetWidgetsLoweredState(bool lowered_stat, Args... widgets)
Sets the lowered/raised status of a list of widgets.
Definition window_gui.h:525
Owner owner
The owner of the content shown in this window. Company colour is acquired from this variable.
Definition window_gui.h:315
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:440
int left
x position of left edge of the window
Definition window_gui.h:308
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
WindowFlags flags
Window flags.
Definition window_gui.h:299
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
virtual EventState OnHotkey(int hotkey)
A hotkey has been pressed.
Definition window.cpp:579
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int height
Height of the window (number of pixels down in y direction).
Definition window_gui.h:311
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
@ Rising
Make the text effect slowly go upwards.
Definition texteff.hpp:22
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
Functions related to tile highlights.
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
@ HT_DRAG
dragging items in the depot windows
@ HT_VEHICLE
vehicle is accepted as target as well (bitmask)
Functions related to time tabling.
void ShowTimetableWindow(const Vehicle *v)
Show the timetable for a given vehicle.
Base for the train class.
@ Stuck
Train can't get a path reservation.
Definition train.h:32
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:42
Command definitions related to trains.
void DrawTrainImage(const Train *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip, VehicleID drag_dest)
Draws an image of a whole train.
PaletteID GetVehiclePalette(const Vehicle *v)
Get the colour map for a vehicle.
Definition vehicle.cpp:2179
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8_t num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
Definition vehicle.cpp:3275
@ Crashed
Vehicle is crashed.
@ Stopped
Vehicle is stopped by the player.
Command definitions for vehicles.
void CcStartStopVehicle(Commands, const CommandCost &result, VehicleID veh_id, bool)
This is the Callback method after attempting to start/stop a vehicle.
Functions related to vehicles.
static const TimerGameEconomy::Date VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
static const Money VEHICLE_PROFIT_THRESHOLD
Threshold for a vehicle to be considered making good profit.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
void DrawAircraftDetails(const Aircraft *v, const Rect &r)
Draw the details for the given vehicle at the given position.
static bool CargoFilter(const GUIVehicleGroup *vehgroup, const CargoType cargo_type)
Check whether a vehicle can carry a specific cargo.
int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
Get the width of a vehicle (part) in pixels.
void DrawShipDetails(const Vehicle *v, const Rect &r)
Draw the details for the given vehicle at the given position.
Definition ship_gui.cpp:63
static const Vehicle * _last_vehicle[2]
Cached values for VehicleNameSorter to spare many GetString() calls.
int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
Get the width of a vehicle (including all parts of the consist) in pixels.
StringID GetCargoSubtypeText(const Vehicle *v)
Get the cargo subtype text from NewGRF for the vehicle details window.
static void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
Assign a vehicle window a new vehicle.
static VehicleTypeIndexArray< WindowDesc > _vehicle_list_desc
Window definitions for the vehicle list windows.
static bool IsVehicleRefittable(const Vehicle *v)
Checks whether the vehicle may be refitted at the moment.
static constexpr std::initializer_list< NWidgetPart > _nested_train_vehicle_details_widgets
Train details widgets.
static constexpr VehicleTypeIndexArray< const ZoomLevel > _vehicle_view_zoom_levels
Zoom levels for vehicle views indexed by vehicle type.
void CcBuildPrimaryVehicle(Commands, const CommandCost &result, VehicleID new_veh_id, uint, uint16_t, CargoArray)
This is the Callback method after the construction attempt of a primary vehicle.
static const int VV_INITIAL_VIEWPORT_HEIGHT
static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN
uint GetUnitNumberDigits(VehicleList &vehicles)
Get the number of digits the biggest unit number of a set of vehicles has.
static constexpr VehicleTypeIndexArray< const StringID > _vehicle_msg_translation_table[]
Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type.
void ShowVehicleViewWindow(const Vehicle *v)
Shows the vehicle view window of the given vehicle.
static WindowDesc _nontrain_vehicle_details_desc(WindowPosition::Automatic, "view_vehicle_details", 405, 113, WindowClass::VehicleDetails, WindowClass::VehicleView, {}, _nested_nontrain_vehicle_details_widgets)
Vehicle details window descriptor for other vehicles than a train.
static WindowDesc _train_view_desc(WindowPosition::Automatic, "view_vehicle_train", 250, 134, WindowClass::VehicleView, WindowClass::None, {}, _nested_vehicle_view_widgets, &VehicleViewWindow::hotkeys)
Vehicle view window descriptor for trains.
uint CountDigitsForAllocatingSpace(uint number)
Get the number of digits of space required for the given number.
static const uint MAX_REFIT_CYCLE
Maximum number of refit cycles we try, to prevent infinite loops.
VehicleCommandTranslation
Command indices for the _vehicle_command_translation_table.
uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
Display list of cargo types of the engine, for the purchase information window.
void DrawVehicleImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip)
Draws an image of a vehicle chain.
void DrawTrainDetails(const Train *v, const Rect &r, int vscroll_pos, uint16_t vscroll_cap, TrainDetailsWindowTabs det_tab)
Draw the details for the given vehicle at the given position.
static void DrawVehicleProfitButton(TimerGameEconomy::Date age, Money display_profit_last_year, uint num_vehicles, int x, int y)
Draw the vehicle profit button in the vehicle list window.
static int GetUnitNumberWidth(int digits)
Get width required for the formatted unit number display.
static constexpr std::initializer_list< NWidgetPart > _nested_vehicle_view_widgets
Vehicle view widgets.
static bool CargoFilterSingle(const Vehicle *v, const CargoType cargo_type)
Check whether a single vehicle should pass the filter.
uint8_t GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoType dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab)
Determines the number of lines in the train details window.
static const int VV_INITIAL_VIEWPORT_WIDTH
bool VehicleClicked(const Vehicle *v)
Dispatch a "vehicle selected" event if any window waits for it.
uint GetVehicleListHeight(VehicleType type, uint divisor)
Get the height of a vehicle in the vehicle list GUIs.
void StartStopVehicle(const Vehicle *v, bool texteffect)
Executes Commands::StartStopVehicle for given vehicle.
void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
Set the mouse cursor to look like a vehicle.
void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
Show the refit window for a vehicle.
static WindowDesc _vehicle_refit_desc(WindowPosition::Automatic, "view_vehicle_refit", 240, 174, WindowClass::VehicleRefit, WindowClass::VehicleView, WindowDefaultFlag::Construction, _nested_vehicle_refit_widgets)
Window definition for the vehicle refit window.
void DrawCargoIconOverlays(std::span< const CargoIconOverlay > overlays, int y)
Draw a list of cargo icon overlays.
void AddCargoIconOverlay(std::vector< CargoIconOverlay > &overlays, int x, int width, const Vehicle *v)
Add a cargo icon to the list of overlays.
static WindowDesc _vehicle_view_desc(WindowPosition::Automatic, "view_vehicle", 250, 116, WindowClass::VehicleView, WindowClass::None, {}, _nested_vehicle_view_widgets, &VehicleViewWindow::hotkeys)
Vehicle view window descriptor for all vehicles but trains.
static constexpr std::initializer_list< NWidgetPart > _nested_nontrain_vehicle_details_widgets
Vehicle details widgets (other than train).
static bool VehicleIndividualToGroupSorterWrapper(GUIVehicleGroup const &a, GUIVehicleGroup const &b)
Wrapper to convert a VehicleIndividualSortFunction to a VehicleGroupSortFunction.
void DrawCargoIconOverlay(int x, int y, CargoType cargo_type)
Draw a cargo icon overlaying an existing sprite, with a black contrast outline.
static WindowDesc _train_vehicle_details_desc(WindowPosition::Automatic, "view_vehicle_details_train", 405, 178, WindowClass::VehicleDetails, WindowClass::VehicleView, {}, _nested_train_vehicle_details_widgets)
Vehicle details window descriptor.
bool ShowCargoIconOverlay()
Test if cargo icon overlays should be drawn.
static void DrawVehicleRefitWindow(const RefitOptions &refits, const RefitOption *sel, uint pos, uint rows, uint delta, const Rect &r)
Draw the list of available refit options for a consist and highlight the selected refit option (if an...
static void ShowVehicleDetailsWindow(const Vehicle *v)
Shows the vehicle details window of the given vehicle.
void DrawRoadVehDetails(const Vehicle *v, const Rect &r)
Draw the details for the given vehicle at the given position.
std::map< CargoType, std::vector< RefitOption >, CargoTypeComparator > RefitOptions
Available refit options (subtype and string) associated with each cargo type.
void CcStartStopVehicle(Commands, const CommandCost &result, VehicleID veh_id, bool)
This is the Callback method after attempting to start/stop a vehicle.
Functions related to the vehicle's GUIs.
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Definition vehicle_gui.h:36
@ VIWD_AUTOREPLACE
Autoreplace replaced the vehicle.
Definition vehicle_gui.h:37
uint GetVehicleHeight(VehicleType type)
Get the height of a single vehicle in the GUIs.
Definition vehicle_gui.h:73
TrainDetailsWindowTabs
The tabs in the train details window.
Definition vehicle_gui.h:25
@ TDW_TAB_TOTALS
Tab with sum of total cargo transported.
Definition vehicle_gui.h:28
@ TDW_TAB_INFO
Tab with name and value of the vehicles.
Definition vehicle_gui.h:27
@ TDW_TAB_CARGO
Tab with cargo carried by the vehicles.
Definition vehicle_gui.h:26
Functions/classes shared between the different vehicle list GUIs.
EnumBitSet< DepotCommandFlag, uint8_t > DepotCommandFlags
Bitset of DepotCommandFlag elements.
EngineImageType
Visualisation contexts of vehicles and engines.
@ InList
Vehicle drawn in vehicle list, group list, ...
@ InDetails
Vehicle drawn in vehicle details, refit window, ...
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
@ MassSend
Tells that it's a mass send to depot command (type in VLW flag).
@ Service
The vehicle will leave the depot right after arrival (service only).
@ Original
Original acceleration model.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
static const uint MAX_LENGTH_VEHICLE_NAME_CHARS
The maximum length of a vehicle name in characters including '\0'.
@ WID_VR_MATRIX
Options to refit to.
@ WID_VR_SCROLLBAR
Scrollbar for the refit options.
@ WID_VR_SHOW_HSCROLLBAR
Selection widget for the horizontal scrollbar.
@ WID_VR_VEHICLE_PANEL_DISPLAY
Display with a representation of the vehicle to refit.
@ WID_VR_HSCROLLBAR
Horizontal scrollbar or the vehicle display.
@ WID_VR_REFIT
Perform the refit.
@ WID_VR_SELECT_HEADER
Header with question about the cargo to carry.
@ WID_VR_INFO
Information about the currently selected refit option.
@ WID_VR_CAPTION
Caption of window.
@ WID_VL_SORT_BY_PULLDOWN
Sort by dropdown list.
@ WID_VL_START_ALL
Start all button.
@ WID_VL_FILTER_BY_CARGO_SEL
Cargo filter dropdown list panel selector.
@ WID_VL_MANAGE_VEHICLES_DROPDOWN
Manage vehicles dropdown list.
@ WID_VL_HIDE_BUTTONS
Selection to hide the buttons.
@ WID_VL_GROUP_BY_PULLDOWN
Group by dropdown list.
@ WID_VL_AVAILABLE_VEHICLES
Available vehicles.
@ WID_VL_STOP_ALL
Stop all button.
@ WID_VL_CAPTION_SELECTION
Selection for caption.
@ WID_VL_FILTER_BY_CARGO
Cargo filter dropdown list.
@ WID_VL_SORT_ORDER
Sort order.
@ WID_VL_GROUP_ORDER
Group order.
@ WID_VL_SCROLLBAR
Scrollbar for the list.
@ WID_VL_CAPTION
Caption of window (for non shared orders windows).
@ WID_VL_LIST
List of the vehicles.
@ WID_VL_CAPTION_SHARED_ORDERS
Caption of window (for shared orders windows).
@ WID_VL_ORDER_VIEW
Button to open order window (for shared orders windows).
@ WID_VV_GOTO_DEPOT
Order this vehicle to go to the depot.
@ WID_VV_LOCATION
Center the main view on this vehicle.
@ WID_VV_TURN_AROUND
Turn this vehicle around.
@ WID_VV_SELECT_DEPOT_CLONE
Selection widget between 'goto depot', and 'clone vehicle' buttons.
@ WID_VV_FORCE_PROCEED
Force this vehicle to pass a signal at danger.
@ WID_VV_RENAME
Rename vehicle.
@ WID_VV_ORDER_LOCATION
Center the main view on the order's target location.
@ WID_VV_SHOW_ORDERS
Show the orders of this vehicle.
@ WID_VV_CLONE
Clone this vehicle.
@ WID_VV_CAPTION
Caption of window.
@ WID_VV_REFIT
Open the refit window.
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
@ WID_VV_SELECT_REFIT_TURN
Selection widget between 'refit' and 'turn around' buttons.
@ WID_VV_SHOW_DETAILS
Show details of this vehicle.
@ WID_VV_VIEWPORT
Viewport widget.
@ WID_VV_HONK_HORN
Honk the vehicles horn (not drawn on UI, only used for hotkey).
@ WID_VV_FORCE_PROCEED_SEL
Container for 'force proceed' button, which can be hidden.
@ WID_VD_DECREASE_SERVICING_INTERVAL
Decrease the servicing interval.
@ WID_VD_CAPTION
Caption of window.
@ WID_VD_SERVICE_INTERVAL_DROPDOWN
Dropdown to select default/days/percent service interval.
@ WID_VD_INCREASE_SERVICING_INTERVAL
Increase the servicing interval.
@ WID_VD_MATRIX
List of details for trains.
@ WID_VD_SERVICING_INTERVAL
Information about the servicing interval.
@ WID_VD_DETAILS_TRAIN_VEHICLES
Show all parts of the train with their description.
@ WID_VD_SCROLLBAR
Scrollbar for train details.
@ WID_VD_TOP_DETAILS
Panel with generic details.
@ WID_VD_MIDDLE_DETAILS
Details for non-trains.
@ WID_VD_DETAILS_TOTALS
Show the total cargo, total capacity, and length of the train.
@ WID_VD_DETAILS_CARGO_CARRIED
Show carried cargo and capacity per part of the train.
bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli)
Generate a list of vehicles based on window type.
std::vector< const Vehicle * > VehicleList
A list of vehicles.
Definition vehiclelist.h:68
VehicleListType
Vehicle List type flags.
Definition vehiclelist.h:22
@ Company
Index is the company.
Definition vehiclelist.h:23
@ Station
Index is the station.
Definition vehiclelist.h:25
@ End
End marker.
Definition vehiclelist.h:28
@ Depot
Index is the destination (station for hangar of aircraft, depot for others).
Definition vehiclelist.h:26
@ VehicleSharedOrders
Index is the first vehicle of the shared orders.
Definition vehiclelist.h:24
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_OUT
Zoom out (get helicopter view).
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:308
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_INSET
Pressed (inset) panel, most commonly used as combo box text area.
Definition widget_type.h:40
@ WWT_IMGBTN
(Toggle) Button with image
Definition widget_type.h:41
@ WWT_PUSHBTN
Normal push-button (no toggle button) with custom drawing.
@ WWT_PUSHIMGBTN
Normal push-button (no toggle button) with image caption.
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ NWID_HSCROLLBAR
Horizontal scrollbar.
Definition widget_type.h:75
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ NWID_VIEWPORT
Nested widget containing a viewport.
Definition widget_type.h:73
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ WWT_DEBUGBOX
NewGRF debug box (at top-right of a window, between WWT_CAPTION and WWT_SHADEBOX).
Definition widget_type.h:54
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ SZSP_NONE
Display plane with zero size in both directions (none filling and resizing).
@ EqualSize
Containers should keep all their (resizing) children equally large.
@ Decrease
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:20
@ Increase
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:21
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1228
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
TooltipCloseCondition
Definition window_gui.h:262
@ BorderOnly
Draw border only, no background.
Definition window_gui.h:25
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ DisableVpScroll
Window does not do autoscroll,.
Definition window_gui.h:230
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
EventState
State of handling an event.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
ZoomLevel ScaleZoomGUI(ZoomLevel value)
Scale zoom level relative to GUI zoom.
Definition zoom_func.h:87
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77
@ Ship
Default zoom level for the ship view.
Definition zoom_type.h:39
@ RoadVehicle
Default zoom level for the road vehicle view.
Definition zoom_type.h:41
@ Aircraft
Default zoom level for the aircraft view.
Definition zoom_type.h:38
@ Train
Default zoom level for the train view.
Definition zoom_type.h:40