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 <http://www.gnu.org/licenses/>.
6 */
7
8 /** @file vehicle_gui.cpp The base GUI for all vehicles. */
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_base.h"
17 #include "viewport_func.h"
18 #include "newgrf_text.h"
19 #include "newgrf_debug.h"
20 #include "roadveh.h"
21 #include "train.h"
22 #include "aircraft.h"
23 #include "depot_map.h"
24 #include "group_gui.h"
25 #include "strings_func.h"
26 #include "vehicle_func.h"
27 #include "autoreplace_gui.h"
28 #include "string_func.h"
29 #include "widgets/dropdown_func.h"
30 #include "timetable.h"
31 #include "articulated_vehicles.h"
32 #include "spritecache.h"
33 #include "core/geometry_func.hpp"
34 #include "company_base.h"
35 #include "engine_func.h"
36 #include "station_base.h"
37 #include "tilehighlight_func.h"
38 #include "zoom_func.h"
39
40 #include "safeguards.h"
41
42
43 BaseVehicleListWindow::GroupBy _grouping[VLT_END][VEH_COMPANY_END];
44 Sorting _sorting[BaseVehicleListWindow::GB_END];
45
46 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNumberSorter;
47 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNameSorter;
48 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleAgeSorter;
49 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitThisYearSorter;
50 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitLastYearSorter;
51 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleCargoSorter;
52 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleReliabilitySorter;
53 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleMaxSpeedSorter;
54 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleModelSorter;
55 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleValueSorter;
56 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleLengthSorter;
57 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimeToLiveSorter;
58 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimetableDelaySorter;
59 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupLengthSorter;
60 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitThisYearSorter;
61 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitLastYearSorter;
62 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitThisYearSorter;
63 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitLastYearSorter;
64
65 /** Wrapper to convert a VehicleIndividualSortFunction to a VehicleGroupSortFunction */
66 template <BaseVehicleListWindow::VehicleIndividualSortFunction func>
VehicleIndividualToGroupSorterWrapper(GUIVehicleGroup const & a,GUIVehicleGroup const & b)67 static bool VehicleIndividualToGroupSorterWrapper(GUIVehicleGroup const &a, GUIVehicleGroup const &b)
68 {
69 return func(*(a.vehicles_begin), *(b.vehicles_begin));
70 }
71
72 BaseVehicleListWindow::VehicleGroupSortFunction * const BaseVehicleListWindow::vehicle_group_none_sorter_funcs[] = {
73 &VehicleIndividualToGroupSorterWrapper<VehicleNumberSorter>,
74 &VehicleIndividualToGroupSorterWrapper<VehicleNameSorter>,
75 &VehicleIndividualToGroupSorterWrapper<VehicleAgeSorter>,
76 &VehicleIndividualToGroupSorterWrapper<VehicleProfitThisYearSorter>,
77 &VehicleIndividualToGroupSorterWrapper<VehicleProfitLastYearSorter>,
78 &VehicleIndividualToGroupSorterWrapper<VehicleCargoSorter>,
79 &VehicleIndividualToGroupSorterWrapper<VehicleReliabilitySorter>,
80 &VehicleIndividualToGroupSorterWrapper<VehicleMaxSpeedSorter>,
81 &VehicleIndividualToGroupSorterWrapper<VehicleModelSorter>,
82 &VehicleIndividualToGroupSorterWrapper<VehicleValueSorter>,
83 &VehicleIndividualToGroupSorterWrapper<VehicleLengthSorter>,
84 &VehicleIndividualToGroupSorterWrapper<VehicleTimeToLiveSorter>,
85 &VehicleIndividualToGroupSorterWrapper<VehicleTimetableDelaySorter>,
86 };
87
88 const StringID BaseVehicleListWindow::vehicle_group_none_sorter_names[] = {
89 STR_SORT_BY_NUMBER,
90 STR_SORT_BY_NAME,
91 STR_SORT_BY_AGE,
92 STR_SORT_BY_PROFIT_THIS_YEAR,
93 STR_SORT_BY_PROFIT_LAST_YEAR,
94 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
95 STR_SORT_BY_RELIABILITY,
96 STR_SORT_BY_MAX_SPEED,
97 STR_SORT_BY_MODEL,
98 STR_SORT_BY_VALUE,
99 STR_SORT_BY_LENGTH,
100 STR_SORT_BY_LIFE_TIME,
101 STR_SORT_BY_TIMETABLE_DELAY,
102 INVALID_STRING_ID
103 };
104
105 BaseVehicleListWindow::VehicleGroupSortFunction * const BaseVehicleListWindow::vehicle_group_shared_orders_sorter_funcs[] = {
106 &VehicleGroupLengthSorter,
107 &VehicleGroupTotalProfitThisYearSorter,
108 &VehicleGroupTotalProfitLastYearSorter,
109 &VehicleGroupAverageProfitThisYearSorter,
110 &VehicleGroupAverageProfitLastYearSorter,
111 };
112
113 const StringID BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names[] = {
114 STR_SORT_BY_NUM_VEHICLES,
115 STR_SORT_BY_TOTAL_PROFIT_THIS_YEAR,
116 STR_SORT_BY_TOTAL_PROFIT_LAST_YEAR,
117 STR_SORT_BY_AVERAGE_PROFIT_THIS_YEAR,
118 STR_SORT_BY_AVERAGE_PROFIT_LAST_YEAR,
119 INVALID_STRING_ID
120 };
121
122 const StringID BaseVehicleListWindow::vehicle_group_by_names[] = {
123 STR_GROUP_BY_NONE,
124 STR_GROUP_BY_SHARED_ORDERS,
125 INVALID_STRING_ID
126 };
127
128 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
129 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
130 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
131 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
132 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
133 };
134
BaseVehicleListWindow(WindowDesc * desc,WindowNumber wno)135 BaseVehicleListWindow::BaseVehicleListWindow(WindowDesc *desc, WindowNumber wno) : Window(desc), vli(VehicleListIdentifier::UnPack(wno))
136 {
137 this->grouping = _grouping[vli.type][vli.vtype];
138 this->UpdateSortingFromGrouping();
139 }
140
141 /**
142 * Get the number of digits of space required for the given number.
143 * @param number The number.
144 * @return The number of digits to allocate space for.
145 */
CountDigitsForAllocatingSpace(uint number)146 uint CountDigitsForAllocatingSpace(uint number)
147 {
148 if (number >= 10000) return 5;
149 if (number >= 1000) return 4;
150 if (number >= 100) return 3;
151
152 /*
153 * When the smallest unit number is less than 10, it is
154 * quite likely that it will expand to become more than
155 * 10 quite soon.
156 */
157 return 2;
158 }
159
160 /**
161 * Get the number of digits the biggest unit number of a set of vehicles has.
162 * @param vehicles The list of vehicles.
163 * @return The number of digits to allocate space for.
164 */
GetUnitNumberDigits(VehicleList & vehicles)165 uint GetUnitNumberDigits(VehicleList &vehicles)
166 {
167 uint unitnumber = 0;
168 for (const Vehicle *v : vehicles) {
169 unitnumber = std::max<uint>(unitnumber, v->unitnumber);
170 }
171
172 return CountDigitsForAllocatingSpace(unitnumber);
173 }
174
BuildVehicleList()175 void BaseVehicleListWindow::BuildVehicleList()
176 {
177 if (!this->vehgroups.NeedRebuild()) return;
178
179 Debug(misc, 3, "Building vehicle list type {} for company {} given index {}", this->vli.type, this->vli.company, this->vli.index);
180
181 this->vehgroups.clear();
182
183 GenerateVehicleSortList(&this->vehicles, this->vli);
184
185 if (this->grouping == GB_NONE) {
186 uint max_unitnumber = 0;
187 for (auto it = this->vehicles.begin(); it != this->vehicles.end(); ++it) {
188 this->vehgroups.emplace_back(it, it + 1);
189
190 max_unitnumber = std::max<uint>(max_unitnumber, (*it)->unitnumber);
191 }
192 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_unitnumber);
193 } else {
194 /* Sort by the primary vehicle; we just want all vehicles that share the same orders to form a contiguous range. */
195 std::stable_sort(this->vehicles.begin(), this->vehicles.end(), [](const Vehicle * const &u, const Vehicle * const &v) {
196 return u->FirstShared() < v->FirstShared();
197 });
198
199 uint max_num_vehicles = 0;
200
201 VehicleList::const_iterator begin = this->vehicles.begin();
202 while (begin != this->vehicles.end()) {
203 VehicleList::const_iterator end = std::find_if_not(begin, this->vehicles.cend(), [first_shared = (*begin)->FirstShared()](const Vehicle * const &v) {
204 return v->FirstShared() == first_shared;
205 });
206
207 this->vehgroups.emplace_back(begin, end);
208
209 max_num_vehicles = std::max<uint>(max_num_vehicles, static_cast<uint>(end - begin));
210
211 begin = end;
212 }
213
214 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_num_vehicles);
215 }
216
217 this->vehgroups.RebuildDone();
218 this->vscroll->SetCount(static_cast<int>(this->vehgroups.size()));
219 }
220
221 /**
222 * Compute the size for the Action dropdown.
223 * @param show_autoreplace If true include the autoreplace item.
224 * @param show_group If true include group-related stuff.
225 * @return Required size.
226 */
GetActionDropdownSize(bool show_autoreplace,bool show_group)227 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
228 {
229 Dimension d = {0, 0};
230
231 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
232 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
233 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
234
235 if (show_group) {
236 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
237 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
238 }
239
240 return d;
241 }
242
OnInit()243 void BaseVehicleListWindow::OnInit()
244 {
245 this->order_arrow_width = GetStringBoundingBox(STR_TINY_RIGHT_ARROW).width;
246 }
247
248 /**
249 * Display the Action dropdown window.
250 * @param show_autoreplace If true include the autoreplace item.
251 * @param show_group If true include group-related stuff.
252 * @return Itemlist for dropdown
253 */
BuildActionDropdownList(bool show_autoreplace,bool show_group)254 DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
255 {
256 DropDownList list;
257
258 if (show_autoreplace) list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false));
259 list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false));
260 list.emplace_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false));
261
262 if (show_group) {
263 list.emplace_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false));
264 list.emplace_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false));
265 }
266
267 return list;
268 }
269
270 /* cached values for VehicleNameSorter to spare many GetString() calls */
271 static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
272
SortVehicleList()273 void BaseVehicleListWindow::SortVehicleList()
274 {
275 if (this->vehgroups.Sort()) return;
276
277 /* invalidate cached values for name sorter - vehicle names could change */
278 _last_vehicle[0] = _last_vehicle[1] = nullptr;
279 }
280
DepotSortList(VehicleList * list)281 void DepotSortList(VehicleList *list)
282 {
283 if (list->size() < 2) return;
284 std::sort(list->begin(), list->end(), &VehicleNumberSorter);
285 }
286
287 /** draw the vehicle profit button in the vehicle list window. */
DrawVehicleProfitButton(Date age,Money display_profit_last_year,uint num_vehicles,int x,int y)288 static void DrawVehicleProfitButton(Date age, Money display_profit_last_year, uint num_vehicles, int x, int y)
289 {
290 SpriteID spr;
291
292 /* draw profit-based coloured icons */
293 if (age <= VEHICLE_PROFIT_MIN_AGE) {
294 spr = SPR_PROFIT_NA;
295 } else if (display_profit_last_year < 0) {
296 spr = SPR_PROFIT_NEGATIVE;
297 } else if (display_profit_last_year < VEHICLE_PROFIT_THRESHOLD * num_vehicles) {
298 spr = SPR_PROFIT_SOME;
299 } else {
300 spr = SPR_PROFIT_LOT;
301 }
302 DrawSprite(spr, PAL_NONE, x, y);
303 }
304
305 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
306 static const uint MAX_REFIT_CYCLE = 256;
307
308 /**
309 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
310 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
311 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
312 * @param v_from the vehicle to match the subtype from
313 * @param v_for the vehicle to get the subtype for
314 * @param dest_cargo_type Destination cargo type.
315 * @return the best sub type
316 */
GetBestFittingSubType(Vehicle * v_from,Vehicle * v_for,CargoID dest_cargo_type)317 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
318 {
319 v_from = v_from->GetFirstEnginePart();
320 v_for = v_for->GetFirstEnginePart();
321
322 /* Create a list of subtypes used by the various parts of v_for */
323 static std::vector<StringID> subtypes;
324 subtypes.clear();
325 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
326 const Engine *e_from = v_from->GetEngine();
327 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
328 include(subtypes, GetCargoSubtypeText(v_from));
329 }
330
331 byte ret_refit_cyc = 0;
332 bool success = false;
333 if (subtypes.size() > 0) {
334 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
335 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
336 const Engine *e = v->GetEngine();
337 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
338 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
339
340 CargoID old_cargo_type = v->cargo_type;
341 byte old_cargo_subtype = v->cargo_subtype;
342
343 /* Set the 'destination' cargo */
344 v->cargo_type = dest_cargo_type;
345
346 /* Cycle through the refits */
347 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
348 v->cargo_subtype = refit_cyc;
349
350 /* Make sure we don't pick up anything cached. */
351 v->First()->InvalidateNewGRFCache();
352 v->InvalidateNewGRFCache();
353
354 StringID subtype = GetCargoSubtypeText(v);
355 if (subtype == STR_EMPTY) break;
356
357 if (std::find(subtypes.begin(), subtypes.end(), subtype) == subtypes.end()) continue;
358
359 /* We found something matching. */
360 ret_refit_cyc = refit_cyc;
361 success = true;
362 break;
363 }
364
365 /* Reset the vehicle's cargo type */
366 v->cargo_type = old_cargo_type;
367 v->cargo_subtype = old_cargo_subtype;
368
369 /* Make sure we don't taint the vehicle. */
370 v->First()->InvalidateNewGRFCache();
371 v->InvalidateNewGRFCache();
372
373 if (success) break;
374 }
375 }
376
377 return ret_refit_cyc;
378 }
379
380 /** Option to refit a vehicle chain */
381 struct RefitOption {
382 CargoID cargo; ///< Cargo to refit to
383 byte subtype; ///< Subcargo to use
384 StringID string; ///< GRF-local String to display for the cargo
385
386 /**
387 * Inequality operator for #RefitOption.
388 * @param other Compare to this #RefitOption.
389 * @return True if both #RefitOption are different.
390 */
operator !=RefitOption391 inline bool operator != (const RefitOption &other) const
392 {
393 return other.cargo != this->cargo || other.string != this->string;
394 }
395
396 /**
397 * Equality operator for #RefitOption.
398 * @param other Compare to this #RefitOption.
399 * @return True if both #RefitOption are equal.
400 */
operator ==RefitOption401 inline bool operator == (const RefitOption &other) const
402 {
403 return other.cargo == this->cargo && other.string == this->string;
404 }
405 };
406
407 typedef std::vector<RefitOption> SubtypeList; ///< List of refit subtypes associated to a cargo.
408
409 /**
410 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
411 * @param list List of subtype options for each (sorted) cargo.
412 * @param sel Selected refit cargo-type in the window
413 * @param pos Position of the selected item in caller widow
414 * @param rows Number of rows(capacity) in caller window
415 * @param delta Step height in caller window
416 * @param r Rectangle of the matrix widget.
417 */
DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO],const int sel[2],uint pos,uint rows,uint delta,const Rect & r)418 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
419 {
420 uint y = r.top + WD_MATRIX_TOP;
421 uint current = 0;
422
423 bool rtl = _current_text_dir == TD_RTL;
424 uint iconwidth = std::max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
425 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
426 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
427
428 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
429 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
430 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
431
432 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
433 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
434
435 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
436 for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
437 for (uint j = 0; current < pos + rows && j < list[i].size(); j++) {
438 const RefitOption &refit = list[i][j];
439
440 /* Hide subtypes if sel[0] does not match */
441 if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
442
443 /* Refit options with a position smaller than pos don't have to be drawn. */
444 if (current < pos) {
445 current++;
446 continue;
447 }
448
449 if (list[i].size() > 1) {
450 if (refit.subtype != 0xFF) {
451 /* Draw tree lines */
452 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
453 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].size() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
454 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
455 } else {
456 /* Draw expand/collapse icon */
457 DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
458 }
459 }
460
461 TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
462 /* Get the cargo name. */
463 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
464 SetDParam(1, refit.string);
465 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
466
467 y += delta;
468 current++;
469 }
470 }
471 }
472
473 /** Refit cargo window. */
474 struct RefitWindow : public Window {
475 int sel[2]; ///< Index in refit options, sel[0] == -1 if nothing is selected.
476 RefitOption *cargo; ///< Refit option selected by #sel.
477 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
478 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
479 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
480 Scrollbar *vscroll; ///< The main scrollbar.
481 Scrollbar *hscroll; ///< Only used for long vehicles.
482 int vehicle_width; ///< Width of the vehicle being drawn.
483 int sprite_left; ///< Left position of the vehicle sprite.
484 int sprite_right; ///< Right position of the vehicle sprite.
485 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
486 int click_x; ///< Position of the first click while dragging.
487 VehicleID selected_vehicle; ///< First vehicle in the current selection.
488 uint8 num_vehicles; ///< Number of selected vehicles.
489 bool auto_refit; ///< Select cargo for auto-refitting.
490
491 /**
492 * Collects all (cargo, subcargo) refit options of a vehicle chain.
493 */
BuildRefitListRefitWindow494 void BuildRefitList()
495 {
496 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].clear();
497 Vehicle *v = Vehicle::Get(this->window_number);
498
499 /* Check only the selected vehicles. */
500 VehicleSet vehicles_to_refit;
501 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
502
503 do {
504 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end()) continue;
505 const Engine *e = v->GetEngine();
506 CargoTypes cmask = e->info.refit_mask;
507 byte callback_mask = e->info.callback_mask;
508
509 /* Skip this engine if it does not carry anything */
510 if (!e->CanCarryCargo()) continue;
511 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
512 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
513
514 /* Loop through all cargoes in the refit mask */
515 int current_index = 0;
516 for (const auto &cs : _sorted_cargo_specs) {
517 CargoID cid = cs->Index();
518 /* Skip cargo type if it's not listed */
519 if (!HasBit(cmask, cid)) {
520 current_index++;
521 continue;
522 }
523
524 bool first_vehicle = this->list[current_index].size() == 0;
525 if (first_vehicle) {
526 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
527 this->list[current_index].push_back({cid, 0xFF, STR_EMPTY});
528 }
529
530 /* Check the vehicle's callback mask for cargo suffixes.
531 * This is not supported for ordered refits, since subtypes only have a meaning
532 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
533 * autoreplace, autorenew, clone, order restoration, ... */
534 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
535 /* Make a note of the original cargo type. It has to be
536 * changed to test the cargo & subtype... */
537 CargoID temp_cargo = v->cargo_type;
538 byte temp_subtype = v->cargo_subtype;
539
540 v->cargo_type = cid;
541
542 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
543 v->cargo_subtype = refit_cyc;
544
545 /* Make sure we don't pick up anything cached. */
546 v->First()->InvalidateNewGRFCache();
547 v->InvalidateNewGRFCache();
548
549 StringID subtype = GetCargoSubtypeText(v);
550
551 if (first_vehicle) {
552 /* Append new subtype (don't add duplicates though) */
553 if (subtype == STR_EMPTY) break;
554
555 RefitOption option;
556 option.cargo = cid;
557 option.subtype = refit_cyc;
558 option.string = subtype;
559 include(this->list[current_index], option);
560 } else {
561 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
562 if (subtype == STR_EMPTY) {
563 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
564 SubtypeList &l = this->list[current_index];
565 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
566 for (uint i = 1; i < l.size(); i++) {
567 if (l[i].subtype >= refit_cyc) {
568 l.resize(i);
569 break;
570 }
571 }
572 break;
573 } else {
574 /* Check whether the subtype matches with the subtype of earlier vehicles. */
575 uint pos = 1;
576 SubtypeList &l = this->list[current_index];
577 while (pos < l.size() && l[pos].subtype != refit_cyc) pos++;
578 if (pos < l.size() && l[pos].string != subtype) {
579 /* String mismatch, remove item keeping the order */
580 l.erase(l.begin() + pos);
581 }
582 }
583 }
584 }
585
586 /* Reset the vehicle's cargo type */
587 v->cargo_type = temp_cargo;
588 v->cargo_subtype = temp_subtype;
589
590 /* And make sure we haven't tainted the cache */
591 v->First()->InvalidateNewGRFCache();
592 v->InvalidateNewGRFCache();
593 }
594 current_index++;
595 }
596 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
597 }
598
599 /**
600 * Refresh scrollbar after selection changed
601 */
RefreshScrollbarRefitWindow602 void RefreshScrollbar()
603 {
604 uint scroll_row = 0;
605 uint row = 0;
606
607 for (uint i = 0; i < NUM_CARGO; i++) {
608 for (uint j = 0; j < this->list[i].size(); j++) {
609 const RefitOption &refit = this->list[i][j];
610
611 /* Hide subtypes if sel[0] does not match */
612 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
613
614 if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
615
616 row++;
617 }
618 }
619
620 this->vscroll->SetCount(row);
621 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
622 }
623
624 /**
625 * Select a row.
626 * @param click_row Clicked row
627 */
SetSelectionRefitWindow628 void SetSelection(uint click_row)
629 {
630 uint row = 0;
631
632 for (uint i = 0; i < NUM_CARGO; i++) {
633 for (uint j = 0; j < this->list[i].size(); j++) {
634 const RefitOption &refit = this->list[i][j];
635
636 /* Hide subtypes if sel[0] does not match */
637 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
638
639 if (row == click_row) {
640 this->sel[0] = i;
641 this->sel[1] = j;
642 return;
643 }
644
645 row++;
646 }
647 }
648
649 this->sel[0] = -1;
650 this->sel[1] = 0;
651 }
652
653 /**
654 * Gets the #RefitOption placed in the selected index.
655 * @return Pointer to the #RefitOption currently in use.
656 */
GetRefitOptionRefitWindow657 RefitOption *GetRefitOption()
658 {
659 if (this->sel[0] < 0) return nullptr;
660
661 SubtypeList &l = this->list[this->sel[0]];
662 if ((uint)this->sel[1] >= l.size()) return nullptr;
663
664 return &l[this->sel[1]];
665 }
666
RefitWindowRefitWindow667 RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
668 {
669 this->sel[0] = -1;
670 this->sel[1] = 0;
671 this->auto_refit = auto_refit;
672 this->order = order;
673 this->CreateNestedTree();
674
675 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
676 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
677 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
678 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
679 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
680 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
681 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
682 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
683 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
684
685 this->FinishInitNested(v->index);
686 this->owner = v->owner;
687
688 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
689 }
690
OnInitRefitWindow691 void OnInit() override
692 {
693 if (this->cargo != nullptr) {
694 /* Store the RefitOption currently in use. */
695 RefitOption current_refit_option = *(this->cargo);
696
697 /* Rebuild the refit list */
698 this->BuildRefitList();
699 this->sel[0] = -1;
700 this->sel[1] = 0;
701 this->cargo = nullptr;
702 for (uint i = 0; this->cargo == nullptr && i < NUM_CARGO; i++) {
703 for (uint j = 0; j < list[i].size(); j++) {
704 if (list[i][j] == current_refit_option) {
705 this->sel[0] = i;
706 this->sel[1] = j;
707 this->cargo = &list[i][j];
708 break;
709 }
710 }
711 }
712
713 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
714 this->RefreshScrollbar();
715 } else {
716 /* Rebuild the refit list */
717 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
718 }
719 }
720
OnPaintRefitWindow721 void OnPaint() override
722 {
723 /* Determine amount of items for scroller. */
724 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
725
726 /* Calculate sprite position. */
727 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
728 int sprite_width = std::max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
729 this->sprite_left = vehicle_panel_display->pos_x;
730 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
731 if (_current_text_dir == TD_RTL) {
732 this->sprite_right -= sprite_width;
733 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
734 } else {
735 this->sprite_left += sprite_width;
736 this->vehicle_margin = sprite_left;
737 }
738
739 this->DrawWidgets();
740 }
741
UpdateWidgetSizeRefitWindow742 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
743 {
744 switch (widget) {
745 case WID_VR_MATRIX:
746 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
747 size->height = resize->height * 8;
748 break;
749
750 case WID_VR_VEHICLE_PANEL_DISPLAY:
751 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
752 break;
753
754 case WID_VR_INFO:
755 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
756 break;
757 }
758 }
759
SetStringParametersRefitWindow760 void SetStringParameters(int widget) const override
761 {
762 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
763 }
764
765 /**
766 * Gets the #StringID to use for displaying capacity.
767 * @param option Cargo and cargo subtype to check for capacity.
768 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
769 * @post String parameters have been set.
770 */
GetCapacityStringRefitWindow771 StringID GetCapacityString(RefitOption *option) const
772 {
773 assert(_current_company == _local_company);
774 Vehicle *v = Vehicle::Get(this->window_number);
775 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | option->subtype << 8 | this->num_vehicles << 16 |
776 (int)this->auto_refit << 24, DC_QUERY_COST, GetCmdRefitVeh(v->type));
777
778 if (cost.Failed()) return INVALID_STRING_ID;
779
780 SetDParam(0, option->cargo);
781 SetDParam(1, _returned_refit_capacity);
782
783 Money money = cost.GetCost();
784 if (_returned_mail_refit_capacity > 0) {
785 SetDParam(2, CT_MAIL);
786 SetDParam(3, _returned_mail_refit_capacity);
787 if (this->order != INVALID_VEH_ORDER_ID) {
788 /* No predictable cost */
789 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
790 } else if (money <= 0) {
791 SetDParam(4, -money);
792 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
793 } else {
794 SetDParam(4, money);
795 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
796 }
797 } else {
798 if (this->order != INVALID_VEH_ORDER_ID) {
799 /* No predictable cost */
800 SetDParam(2, STR_EMPTY);
801 return STR_PURCHASE_INFO_CAPACITY;
802 } else if (money <= 0) {
803 SetDParam(2, -money);
804 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
805 } else {
806 SetDParam(2, money);
807 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
808 }
809 }
810 }
811
DrawWidgetRefitWindow812 void DrawWidget(const Rect &r, int widget) const override
813 {
814 switch (widget) {
815 case WID_VR_VEHICLE_PANEL_DISPLAY: {
816 Vehicle *v = Vehicle::Get(this->window_number);
817 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
818 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
819
820 /* Highlight selected vehicles. */
821 if (this->order != INVALID_VEH_ORDER_ID) break;
822 int x = 0;
823 switch (v->type) {
824 case VEH_TRAIN: {
825 VehicleSet vehicles_to_refit;
826 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
827
828 int left = INT32_MIN;
829 int width = 0;
830
831 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
832 /* Start checking. */
833 const bool contained = std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), u->index) != vehicles_to_refit.end();
834 if (contained && left == INT32_MIN) {
835 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
836 width = 0;
837 }
838
839 /* Draw a selection. */
840 if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
841 if (u->Next() == nullptr && contained) {
842 int current_width = u->GetDisplayImageWidth();
843 width += current_width;
844 x += current_width;
845 }
846
847 int right = Clamp(left + width, 0, r.right);
848 left = std::max(0, left);
849
850 if (_current_text_dir == TD_RTL) {
851 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
852 left = right - width;
853 }
854
855 if (left != right) {
856 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
857 }
858
859 left = INT32_MIN;
860 }
861
862 int current_width = u->GetDisplayImageWidth();
863 width += current_width;
864 x += current_width;
865 }
866 break;
867 }
868
869 default: break;
870 }
871 break;
872 }
873
874 case WID_VR_MATRIX:
875 DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
876 break;
877
878 case WID_VR_INFO:
879 if (this->cargo != nullptr) {
880 StringID string = this->GetCapacityString(this->cargo);
881 if (string != INVALID_STRING_ID) {
882 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
883 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
884 }
885 }
886 break;
887 }
888 }
889
890 /**
891 * Some data on this window has become invalid.
892 * @param data Information about the changed data.
893 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
894 */
OnInvalidateDataRefitWindow895 void OnInvalidateData(int data = 0, bool gui_scope = true) override
896 {
897 switch (data) {
898 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
899 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
900 /* Clear the selection. */
901 Vehicle *v = Vehicle::Get(this->window_number);
902 this->selected_vehicle = v->index;
903 this->num_vehicles = UINT8_MAX;
904 FALLTHROUGH;
905 }
906
907 case 2: { // The vehicle selection has changed; rebuild the entire list.
908 if (!gui_scope) break;
909 this->BuildRefitList();
910
911 /* The vehicle width has changed too. */
912 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
913 uint max_width = 0;
914
915 /* Check the width of all cargo information strings. */
916 for (uint i = 0; i < NUM_CARGO; i++) {
917 for (uint j = 0; j < this->list[i].size(); j++) {
918 StringID string = this->GetCapacityString(&list[i][j]);
919 if (string != INVALID_STRING_ID) {
920 Dimension dim = GetStringBoundingBox(string);
921 max_width = std::max(dim.width, max_width);
922 }
923 }
924 }
925
926 if (this->information_width < max_width) {
927 this->information_width = max_width;
928 this->ReInit();
929 }
930 FALLTHROUGH;
931 }
932
933 case 1: // A new cargo has been selected.
934 if (!gui_scope) break;
935 this->cargo = GetRefitOption();
936 this->RefreshScrollbar();
937 break;
938 }
939 }
940
GetClickPositionRefitWindow941 int GetClickPosition(int click_x)
942 {
943 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
944 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
945 click_x -= this->vehicle_margin;
946 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
947
948 return click_x;
949 }
950
SetSelectedVehiclesRefitWindow951 void SetSelectedVehicles(int drag_x)
952 {
953 drag_x = GetClickPosition(drag_x);
954
955 int left_x = std::min(this->click_x, drag_x);
956 int right_x = std::max(this->click_x, drag_x);
957 this->num_vehicles = 0;
958
959 Vehicle *v = Vehicle::Get(this->window_number);
960 /* Find the vehicle part that was clicked. */
961 switch (v->type) {
962 case VEH_TRAIN: {
963 /* Don't select anything if we are not clicking in the vehicle. */
964 if (left_x >= 0) {
965 const Train *u = Train::From(v);
966 bool start_counting = false;
967 for (; u != nullptr; u = u->Next()) {
968 int current_width = u->GetDisplayImageWidth();
969 left_x -= current_width;
970 right_x -= current_width;
971
972 if (left_x < 0 && !start_counting) {
973 this->selected_vehicle = u->index;
974 start_counting = true;
975
976 /* Count the first vehicle, even if articulated part */
977 this->num_vehicles++;
978 } else if (start_counting && !u->IsArticulatedPart()) {
979 /* Do not count articulated parts */
980 this->num_vehicles++;
981 }
982
983 if (right_x < 0) break;
984 }
985 }
986
987 /* If the selection is not correct, clear it. */
988 if (this->num_vehicles != 0) {
989 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
990 break;
991 }
992 FALLTHROUGH;
993 }
994
995 default:
996 /* Clear the selection. */
997 this->selected_vehicle = v->index;
998 this->num_vehicles = UINT8_MAX;
999 break;
1000 }
1001 }
1002
OnClickRefitWindow1003 void OnClick(Point pt, int widget, int click_count) override
1004 {
1005 switch (widget) {
1006 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1007 if (this->order != INVALID_VEH_ORDER_ID) break;
1008 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1009 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
1010 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1011 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1012 if (!_ctrl_pressed) {
1013 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1014 } else {
1015 /* The vehicle selection has changed. */
1016 this->InvalidateData(2);
1017 }
1018 break;
1019 }
1020
1021 case WID_VR_MATRIX: { // listbox
1022 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
1023 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
1024 this->InvalidateData(1);
1025
1026 if (click_count == 1) break;
1027 FALLTHROUGH;
1028 }
1029
1030 case WID_VR_REFIT: // refit button
1031 if (this->cargo != nullptr) {
1032 const Vehicle *v = Vehicle::Get(this->window_number);
1033
1034 if (this->order == INVALID_VEH_ORDER_ID) {
1035 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1036 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) this->Close();
1037 } else {
1038 if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) this->Close();
1039 }
1040 }
1041 break;
1042 }
1043 }
1044
OnMouseDragRefitWindow1045 void OnMouseDrag(Point pt, int widget) override
1046 {
1047 switch (widget) {
1048 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1049 if (this->order != INVALID_VEH_ORDER_ID) break;
1050 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1051 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1052 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1053 break;
1054 }
1055 }
1056 }
1057
OnDragDropRefitWindow1058 void OnDragDrop(Point pt, int widget) override
1059 {
1060 switch (widget) {
1061 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1062 if (this->order != INVALID_VEH_ORDER_ID) break;
1063 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1064 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1065 this->InvalidateData(2);
1066 break;
1067 }
1068 }
1069 }
1070
OnResizeRefitWindow1071 void OnResize() override
1072 {
1073 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1074 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1075 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1076 }
1077 };
1078
1079 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
1080 NWidget(NWID_HORIZONTAL),
1081 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1082 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1083 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1084 EndContainer(),
1085 /* Vehicle display + scrollbar. */
1086 NWidget(NWID_VERTICAL),
1087 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1088 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1089 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1090 EndContainer(),
1091 EndContainer(),
1092 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1093 /* Matrix + scrollbar. */
1094 NWidget(NWID_HORIZONTAL),
1095 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VR_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VR_SCROLLBAR),
1096 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1097 EndContainer(),
1098 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1099 NWidget(NWID_HORIZONTAL),
1100 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1101 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1102 EndContainer(),
1103 };
1104
1105 static WindowDesc _vehicle_refit_desc(
1106 WDP_AUTO, "view_vehicle_refit", 240, 174,
1107 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1108 WDF_CONSTRUCTION,
1109 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1110 );
1111
1112 /**
1113 * Show the refit window for a vehicle
1114 * @param *v The vehicle to show the refit window for
1115 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1116 * @param parent the parent window of the refit window
1117 * @param auto_refit Choose cargo for auto-refitting
1118 */
ShowVehicleRefitWindow(const Vehicle * v,VehicleOrderID order,Window * parent,bool auto_refit)1119 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1120 {
1121 CloseWindowById(WC_VEHICLE_REFIT, v->index);
1122 RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
1123 w->parent = parent;
1124 }
1125
1126 /** Display list of cargo types of the engine, for the purchase information window */
ShowRefitOptionsList(int left,int right,int y,EngineID engine)1127 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1128 {
1129 /* List of cargo types of this engine */
1130 CargoTypes cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1131 /* List of cargo types available in this climate */
1132 CargoTypes lmask = _cargo_mask;
1133
1134 /* Draw nothing if the engine is not refittable */
1135 if (HasAtMostOneBit(cmask)) return y;
1136
1137 if (cmask == lmask) {
1138 /* Engine can be refitted to all types in this climate */
1139 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1140 } else {
1141 /* Check if we are able to refit to more cargo types and unable to. If
1142 * so, invert the cargo types to list those that we can't refit to. */
1143 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1144 cmask ^= lmask;
1145 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1146 } else {
1147 SetDParam(0, STR_JUST_CARGO_LIST);
1148 }
1149 SetDParam(1, cmask);
1150 }
1151
1152 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1153 }
1154
1155 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
GetCargoSubtypeText(const Vehicle * v)1156 StringID GetCargoSubtypeText(const Vehicle *v)
1157 {
1158 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1159 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1160 if (cb != CALLBACK_FAILED) {
1161 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1162 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1163 }
1164 if (cb != CALLBACK_FAILED) {
1165 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1166 }
1167 }
1168 return STR_EMPTY;
1169 }
1170
1171 /** Sort vehicle groups by the number of vehicles in the group */
VehicleGroupLengthSorter(const GUIVehicleGroup & a,const GUIVehicleGroup & b)1172 static bool VehicleGroupLengthSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1173 {
1174 return a.NumVehicles() < b.NumVehicles();
1175 }
1176
1177 /** Sort vehicle groups by the total profit this year */
VehicleGroupTotalProfitThisYearSorter(const GUIVehicleGroup & a,const GUIVehicleGroup & b)1178 static bool VehicleGroupTotalProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1179 {
1180 return a.GetDisplayProfitThisYear() < b.GetDisplayProfitThisYear();
1181 }
1182
1183 /** Sort vehicle groups by the total profit last year */
VehicleGroupTotalProfitLastYearSorter(const GUIVehicleGroup & a,const GUIVehicleGroup & b)1184 static bool VehicleGroupTotalProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1185 {
1186 return a.GetDisplayProfitLastYear() < b.GetDisplayProfitLastYear();
1187 }
1188
1189 /** Sort vehicle groups by the average profit this year */
VehicleGroupAverageProfitThisYearSorter(const GUIVehicleGroup & a,const GUIVehicleGroup & b)1190 static bool VehicleGroupAverageProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1191 {
1192 return a.GetDisplayProfitThisYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitThisYear() * static_cast<uint>(a.NumVehicles());
1193 }
1194
1195 /** Sort vehicle groups by the average profit last year */
VehicleGroupAverageProfitLastYearSorter(const GUIVehicleGroup & a,const GUIVehicleGroup & b)1196 static bool VehicleGroupAverageProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1197 {
1198 return a.GetDisplayProfitLastYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitLastYear() * static_cast<uint>(a.NumVehicles());
1199 }
1200
1201 /** Sort vehicles by their number */
VehicleNumberSorter(const Vehicle * const & a,const Vehicle * const & b)1202 static bool VehicleNumberSorter(const Vehicle * const &a, const Vehicle * const &b)
1203 {
1204 return a->unitnumber < b->unitnumber;
1205 }
1206
1207 /** Sort vehicles by their name */
VehicleNameSorter(const Vehicle * const & a,const Vehicle * const & b)1208 static bool VehicleNameSorter(const Vehicle * const &a, const Vehicle * const &b)
1209 {
1210 static char last_name[2][64];
1211
1212 if (a != _last_vehicle[0]) {
1213 _last_vehicle[0] = a;
1214 SetDParam(0, a->index);
1215 GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
1216 }
1217
1218 if (b != _last_vehicle[1]) {
1219 _last_vehicle[1] = b;
1220 SetDParam(0, b->index);
1221 GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
1222 }
1223
1224 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1225 return (r != 0) ? r < 0: VehicleNumberSorter(a, b);
1226 }
1227
1228 /** Sort vehicles by their age */
VehicleAgeSorter(const Vehicle * const & a,const Vehicle * const & b)1229 static bool VehicleAgeSorter(const Vehicle * const &a, const Vehicle * const &b)
1230 {
1231 int r = a->age - b->age;
1232 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1233 }
1234
1235 /** Sort vehicles by this year profit */
VehicleProfitThisYearSorter(const Vehicle * const & a,const Vehicle * const & b)1236 static bool VehicleProfitThisYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1237 {
1238 int r = ClampToI32(a->GetDisplayProfitThisYear() - b->GetDisplayProfitThisYear());
1239 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1240 }
1241
1242 /** Sort vehicles by last year profit */
VehicleProfitLastYearSorter(const Vehicle * const & a,const Vehicle * const & b)1243 static bool VehicleProfitLastYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1244 {
1245 int r = ClampToI32(a->GetDisplayProfitLastYear() - b->GetDisplayProfitLastYear());
1246 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1247 }
1248
1249 /** Sort vehicles by their cargo */
VehicleCargoSorter(const Vehicle * const & a,const Vehicle * const & b)1250 static bool VehicleCargoSorter(const Vehicle * const &a, const Vehicle * const &b)
1251 {
1252 const Vehicle *v;
1253 CargoArray diff;
1254
1255 /* Append the cargo of the connected waggons */
1256 for (v = a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1257 for (v = b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1258
1259 int r = 0;
1260 for (CargoID i = 0; i < NUM_CARGO; i++) {
1261 r = diff[i];
1262 if (r != 0) break;
1263 }
1264
1265 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1266 }
1267
1268 /** Sort vehicles by their reliability */
VehicleReliabilitySorter(const Vehicle * const & a,const Vehicle * const & b)1269 static bool VehicleReliabilitySorter(const Vehicle * const &a, const Vehicle * const &b)
1270 {
1271 int r = a->reliability - b->reliability;
1272 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1273 }
1274
1275 /** Sort vehicles by their max speed */
VehicleMaxSpeedSorter(const Vehicle * const & a,const Vehicle * const & b)1276 static bool VehicleMaxSpeedSorter(const Vehicle * const &a, const Vehicle * const &b)
1277 {
1278 int r = a->vcache.cached_max_speed - b->vcache.cached_max_speed;
1279 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1280 }
1281
1282 /** Sort vehicles by model */
VehicleModelSorter(const Vehicle * const & a,const Vehicle * const & b)1283 static bool VehicleModelSorter(const Vehicle * const &a, const Vehicle * const &b)
1284 {
1285 int r = a->engine_type - b->engine_type;
1286 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1287 }
1288
1289 /** Sort vehicles by their value */
VehicleValueSorter(const Vehicle * const & a,const Vehicle * const & b)1290 static bool VehicleValueSorter(const Vehicle * const &a, const Vehicle * const &b)
1291 {
1292 const Vehicle *u;
1293 Money diff = 0;
1294
1295 for (u = a; u != nullptr; u = u->Next()) diff += u->value;
1296 for (u = b; u != nullptr; u = u->Next()) diff -= u->value;
1297
1298 int r = ClampToI32(diff);
1299 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1300 }
1301
1302 /** Sort vehicles by their length */
VehicleLengthSorter(const Vehicle * const & a,const Vehicle * const & b)1303 static bool VehicleLengthSorter(const Vehicle * const &a, const Vehicle * const &b)
1304 {
1305 int r = a->GetGroundVehicleCache()->cached_total_length - b->GetGroundVehicleCache()->cached_total_length;
1306 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1307 }
1308
1309 /** Sort vehicles by the time they can still live */
VehicleTimeToLiveSorter(const Vehicle * const & a,const Vehicle * const & b)1310 static bool VehicleTimeToLiveSorter(const Vehicle * const &a, const Vehicle * const &b)
1311 {
1312 int r = ClampToI32((a->max_age - a->age) - (b->max_age - b->age));
1313 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1314 }
1315
1316 /** Sort vehicles by the timetable delay */
VehicleTimetableDelaySorter(const Vehicle * const & a,const Vehicle * const & b)1317 static bool VehicleTimetableDelaySorter(const Vehicle * const &a, const Vehicle * const &b)
1318 {
1319 int r = a->lateness_counter - b->lateness_counter;
1320 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1321 }
1322
InitializeGUI()1323 void InitializeGUI()
1324 {
1325 MemSetT(&_grouping, 0);
1326 MemSetT(&_sorting, 0);
1327 }
1328
1329 /**
1330 * Assign a vehicle window a new vehicle
1331 * @param window_class WindowClass to search for
1332 * @param from_index the old vehicle ID
1333 * @param to_index the new vehicle ID
1334 */
ChangeVehicleWindow(WindowClass window_class,VehicleID from_index,VehicleID to_index)1335 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1336 {
1337 Window *w = FindWindowById(window_class, from_index);
1338 if (w != nullptr) {
1339 /* Update window_number */
1340 w->window_number = to_index;
1341 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1342
1343 /* Update vehicle drag data */
1344 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1345 _thd.window_number = to_index;
1346 }
1347
1348 /* Notify the window. */
1349 w->InvalidateData(VIWD_AUTOREPLACE, false);
1350 }
1351 }
1352
1353 /**
1354 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1355 * @param from_index the old vehicle ID
1356 * @param to_index the new vehicle ID
1357 */
ChangeVehicleViewWindow(VehicleID from_index,VehicleID to_index)1358 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1359 {
1360 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1361 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1362 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1363 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1364 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1365 }
1366
1367 static const NWidgetPart _nested_vehicle_list[] = {
1368 NWidget(NWID_HORIZONTAL),
1369 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1370 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_CAPTION_SELECTION),
1371 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1372 NWidget(NWID_HORIZONTAL),
1373 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION_SHARED_ORDERS),
1374 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_ORDER_VIEW), SetMinimalSize(61, 14), SetDataTip(STR_GOTO_ORDER_VIEW, STR_GOTO_ORDER_VIEW_TOOLTIP),
1375 EndContainer(),
1376 EndContainer(),
1377 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1378 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1379 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1380 EndContainer(),
1381
1382 NWidget(NWID_HORIZONTAL),
1383 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VL_GROUP_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_STATION_VIEW_GROUP, STR_TOOLTIP_GROUP_ORDER),
1384 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_GROUP_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
1385 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1386 EndContainer(),
1387
1388 NWidget(NWID_HORIZONTAL),
1389 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1390 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1391 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1392 EndContainer(),
1393
1394 NWidget(NWID_HORIZONTAL),
1395 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VL_SCROLLBAR),
1396 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1397 EndContainer(),
1398
1399 NWidget(NWID_HORIZONTAL),
1400 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1401 NWidget(NWID_HORIZONTAL),
1402 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1403 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1404 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1405 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1406 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1407 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1408 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1409 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1410 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1411 EndContainer(),
1412 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1413 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1414 EndContainer(),
1415 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1416 EndContainer(),
1417 };
1418
DrawSmallOrderList(const Vehicle * v,int left,int right,int y,uint order_arrow_width,VehicleOrderID start)1419 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, uint order_arrow_width, VehicleOrderID start)
1420 {
1421 const Order *order = v->GetOrder(start);
1422 if (order == nullptr) return;
1423
1424 bool rtl = _current_text_dir == TD_RTL;
1425 int l_offset = rtl ? 0 : order_arrow_width;
1426 int r_offset = rtl ? order_arrow_width : 0;
1427 int i = 0;
1428 VehicleOrderID oid = start;
1429
1430 do {
1431 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1432
1433 if (order->IsType(OT_GOTO_STATION)) {
1434 SetDParam(0, order->GetDestination());
1435 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1436
1437 y += FONT_HEIGHT_SMALL;
1438 if (++i == 4) break;
1439 }
1440
1441 oid++;
1442 order = order->next;
1443 if (order == nullptr) {
1444 order = v->orders.list->GetFirstOrder();
1445 oid = 0;
1446 }
1447 } while (oid != start);
1448 }
1449
1450 /** Draw small order list in the vehicle GUI, but without the little black arrow. This is used for shared order groups. */
DrawSmallOrderList(const Order * order,int left,int right,int y,uint order_arrow_width)1451 static void DrawSmallOrderList(const Order *order, int left, int right, int y, uint order_arrow_width)
1452 {
1453 bool rtl = _current_text_dir == TD_RTL;
1454 int l_offset = rtl ? 0 : order_arrow_width;
1455 int r_offset = rtl ? order_arrow_width : 0;
1456 int i = 0;
1457 while (order != nullptr) {
1458 if (order->IsType(OT_GOTO_STATION)) {
1459 SetDParam(0, order->GetDestination());
1460 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1461
1462 y += FONT_HEIGHT_SMALL;
1463 if (++i == 4) break;
1464 }
1465 order = order->next;
1466 }
1467 }
1468
1469 /**
1470 * Draws an image of a vehicle chain
1471 * @param v Front vehicle
1472 * @param left The minimum horizontal position
1473 * @param right The maximum horizontal position
1474 * @param y Vertical position to draw at
1475 * @param selection Selected vehicle to draw a frame around
1476 * @param skip Number of pixels to skip at the front (for scrolling)
1477 */
DrawVehicleImage(const Vehicle * v,int left,int right,int y,VehicleID selection,EngineImageType image_type,int skip)1478 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1479 {
1480 switch (v->type) {
1481 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1482 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1483 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1484 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1485 default: NOT_REACHED();
1486 }
1487 }
1488
1489 /**
1490 * Get the height of a vehicle in the vehicle list GUIs.
1491 * @param type the vehicle type to look at
1492 * @param divisor the resulting height must be dividable by this
1493 * @return the height
1494 */
GetVehicleListHeight(VehicleType type,uint divisor)1495 uint GetVehicleListHeight(VehicleType type, uint divisor)
1496 {
1497 /* Name + vehicle + profit */
1498 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1499 /* Drawing of the 4 small orders + profit*/
1500 if (type >= VEH_SHIP) base = std::max(base, 5U * FONT_HEIGHT_SMALL);
1501
1502 if (divisor == 1) return base;
1503
1504 /* Make sure the height is dividable by divisor */
1505 uint rem = base % divisor;
1506 return base + (rem == 0 ? 0 : divisor - rem);
1507 }
1508
1509 /**
1510 * Draw all the vehicle list items.
1511 * @param selected_vehicle The vehicle that is to be highlighted.
1512 * @param line_height Height of a single item line.
1513 * @param r Rectangle with edge positions of the matrix widget.
1514 */
DrawVehicleListItems(VehicleID selected_vehicle,int line_height,const Rect & r) const1515 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1516 {
1517 int left = r.left + WD_MATRIX_LEFT;
1518 int right = r.right - WD_MATRIX_RIGHT;
1519 int width = right - left;
1520 bool rtl = _current_text_dir == TD_RTL;
1521
1522 int text_offset = std::max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits) + WD_FRAMERECT_RIGHT;
1523 int text_left = left + (rtl ? 0 : text_offset);
1524 int text_right = right - (rtl ? text_offset : 0);
1525
1526 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1527 int orderlist_left = left + (rtl ? 0 : std::max(ScaleGUITrad(100) + text_offset, width / 2));
1528 int orderlist_right = right - (rtl ? std::max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1529
1530 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1531 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1532
1533 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1534
1535 int y = r.top;
1536 uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehgroups.size()));
1537 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1538
1539 const GUIVehicleGroup &vehgroup = this->vehgroups[i];
1540
1541 SetDParam(0, vehgroup.GetDisplayProfitThisYear());
1542 SetDParam(1, vehgroup.GetDisplayProfitLastYear());
1543 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1544
1545 DrawVehicleProfitButton(vehgroup.GetOldestVehicleAge(), vehgroup.GetDisplayProfitLastYear(), vehgroup.NumVehicles(), vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1546
1547 switch (this->grouping) {
1548 case GB_NONE: {
1549 const Vehicle *v = vehgroup.GetSingleVehicle();
1550
1551 if (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) {
1552 DrawSprite(SPR_WARNING_SIGN, PAL_NONE, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3 + GetSpriteSize(SPR_PROFIT_LOT).height);
1553 }
1554
1555 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1556
1557 if (!v->name.empty()) {
1558 /* The vehicle got a name so we will print it */
1559 SetDParam(0, v->index);
1560 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1561 } else if (v->group_id != DEFAULT_GROUP) {
1562 /* The vehicle has no name, but is member of a group, so print group name */
1563 SetDParam(0, v->group_id);
1564 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1565 }
1566
1567 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, this->order_arrow_width, v->cur_real_order_index);
1568
1569 StringID str;
1570 if (v->IsChainInDepot()) {
1571 str = STR_BLUE_COMMA;
1572 } else {
1573 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1574 }
1575
1576 SetDParam(0, v->unitnumber);
1577 DrawString(left, right, y + 2, str);
1578 break;
1579 }
1580
1581 case GB_SHARED_ORDERS:
1582 assert(vehgroup.NumVehicles() > 0);
1583
1584 for (int i = 0; i < static_cast<int>(vehgroup.NumVehicles()); ++i) {
1585 if (image_left + 8 * i >= image_right) break; // Break if there is no more space to draw any more vehicles anyway.
1586 DrawVehicleImage(vehgroup.vehicles_begin[i], image_left + 8 * i, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1587 }
1588
1589 if (show_orderlist) DrawSmallOrderList((vehgroup.vehicles_begin[0])->GetFirstOrder(), orderlist_left, orderlist_right, y, this->order_arrow_width);
1590
1591 SetDParam(0, vehgroup.NumVehicles());
1592 DrawString(left, right, y + 2, STR_BLACK_COMMA);
1593 break;
1594
1595 default:
1596 NOT_REACHED();
1597 }
1598
1599 y += line_height;
1600 }
1601 }
1602
UpdateSortingFromGrouping()1603 void BaseVehicleListWindow::UpdateSortingFromGrouping()
1604 {
1605 /* Set up sorting. Make the window-specific _sorting variable
1606 * point to the correct global _sorting struct so we are freed
1607 * from having conditionals during window operation */
1608 switch (this->vli.vtype) {
1609 case VEH_TRAIN: this->sorting = &_sorting[this->grouping].train; break;
1610 case VEH_ROAD: this->sorting = &_sorting[this->grouping].roadveh; break;
1611 case VEH_SHIP: this->sorting = &_sorting[this->grouping].ship; break;
1612 case VEH_AIRCRAFT: this->sorting = &_sorting[this->grouping].aircraft; break;
1613 default: NOT_REACHED();
1614 }
1615 this->vehgroups.SetSortFuncs(this->GetVehicleSorterFuncs());
1616 this->vehgroups.SetListing(*this->sorting);
1617 this->vehgroups.ForceRebuild();
1618 this->vehgroups.NeedResort();
1619 }
1620
UpdateVehicleGroupBy(GroupBy group_by)1621 void BaseVehicleListWindow::UpdateVehicleGroupBy(GroupBy group_by)
1622 {
1623 if (this->grouping != group_by) {
1624 /* Save the old sorting option, so that if we change the grouping option back later on,
1625 * UpdateSortingFromGrouping() will automatically restore the saved sorting option. */
1626 *this->sorting = this->vehgroups.GetListing();
1627
1628 this->grouping = group_by;
1629 _grouping[this->vli.type][this->vli.vtype] = group_by;
1630 this->UpdateSortingFromGrouping();
1631 }
1632 }
1633
1634 /**
1635 * Window for the (old) vehicle listing.
1636 *
1637 * bitmask for w->window_number
1638 * 0-7 CompanyID (owner)
1639 * 8-10 window type (use flags in vehicle_gui.h)
1640 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1641 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1642 */
1643 struct VehicleListWindow : public BaseVehicleListWindow {
1644 private:
1645 /** Enumeration of planes of the button row at the bottom. */
1646 enum ButtonPlanes {
1647 BP_SHOW_BUTTONS, ///< Show the buttons.
1648 BP_HIDE_BUTTONS, ///< Show the empty panel.
1649 };
1650
1651 /** Enumeration of planes of the title row at the top. */
1652 enum CaptionPlanes {
1653 BP_NORMAL, ///< Show shared orders caption and buttons.
1654 BP_SHARED_ORDERS, ///< Show the normal caption.
1655 };
1656
1657 public:
VehicleListWindowVehicleListWindow1658 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1659 {
1660 this->CreateNestedTree();
1661
1662 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1663
1664 this->BuildVehicleList();
1665 this->SortVehicleList();
1666
1667 /* Set up the window widgets */
1668 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1669
1670 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_CAPTION_SELECTION);
1671 if (this->vli.type == VL_SHARED_ORDERS) {
1672 this->GetWidget<NWidgetCore>(WID_VL_CAPTION_SHARED_ORDERS)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1673 /* If we are in the shared orders window, then disable the group-by dropdown menu.
1674 * Remove this when the group-by dropdown menu has another option apart from grouping by shared orders. */
1675 this->SetWidgetDisabledState(WID_VL_GROUP_ORDER, true);
1676 this->SetWidgetDisabledState(WID_VL_GROUP_BY_PULLDOWN, true);
1677 nwi->SetDisplayedPlane(BP_SHARED_ORDERS);
1678 } else {
1679 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1680 nwi->SetDisplayedPlane(BP_NORMAL);
1681 }
1682
1683 this->FinishInitNested(window_number);
1684 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1685 }
1686
~VehicleListWindowVehicleListWindow1687 ~VehicleListWindow()
1688 {
1689 *this->sorting = this->vehgroups.GetListing();
1690 }
1691
UpdateWidgetSizeVehicleListWindow1692 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1693 {
1694 switch (widget) {
1695 case WID_VL_LIST:
1696 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1697
1698 switch (this->vli.vtype) {
1699 case VEH_TRAIN:
1700 case VEH_ROAD:
1701 size->height = 6 * resize->height;
1702 break;
1703 case VEH_SHIP:
1704 case VEH_AIRCRAFT:
1705 size->height = 4 * resize->height;
1706 break;
1707 default: NOT_REACHED();
1708 }
1709 break;
1710
1711 case WID_VL_SORT_ORDER: {
1712 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1713 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1714 d.height += padding.height;
1715 *size = maxdim(*size, d);
1716 break;
1717 }
1718
1719 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1720 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1721 d.height += padding.height;
1722 d.width += padding.width;
1723 *size = maxdim(*size, d);
1724 break;
1725 }
1726 }
1727 }
1728
SetStringParametersVehicleListWindow1729 void SetStringParameters(int widget) const override
1730 {
1731 switch (widget) {
1732 case WID_VL_AVAILABLE_VEHICLES:
1733 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1734 break;
1735
1736 case WID_VL_CAPTION:
1737 case WID_VL_CAPTION_SHARED_ORDERS: {
1738 switch (this->vli.type) {
1739 case VL_SHARED_ORDERS: // Shared Orders
1740 if (this->vehicles.size() == 0) {
1741 /* We can't open this window without vehicles using this order
1742 * and we should close the window when deleting the order. */
1743 NOT_REACHED();
1744 }
1745 SetDParam(0, this->vehicles.size());
1746 break;
1747
1748 case VL_STANDARD: // Company Name
1749 SetDParam(0, STR_COMPANY_NAME);
1750 SetDParam(1, this->vli.index);
1751 SetDParam(3, this->vehicles.size());
1752 break;
1753
1754 case VL_STATION_LIST: // Station/Waypoint Name
1755 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
1756 SetDParam(1, this->vli.index);
1757 SetDParam(3, this->vehicles.size());
1758 break;
1759
1760 case VL_DEPOT_LIST:
1761 SetDParam(0, STR_DEPOT_CAPTION);
1762 SetDParam(1, this->vli.vtype);
1763 SetDParam(2, this->vli.index);
1764 SetDParam(3, this->vehicles.size());
1765 break;
1766 default: NOT_REACHED();
1767 }
1768 break;
1769 }
1770 }
1771 }
1772
DrawWidgetVehicleListWindow1773 void DrawWidget(const Rect &r, int widget) const override
1774 {
1775 switch (widget) {
1776 case WID_VL_SORT_ORDER:
1777 /* draw arrow pointing up/down for ascending/descending sorting */
1778 this->DrawSortButtonState(widget, this->vehgroups.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1779 break;
1780
1781 case WID_VL_LIST:
1782 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1783 break;
1784 }
1785 }
1786
OnPaintVehicleListWindow1787 void OnPaint() override
1788 {
1789 this->BuildVehicleList();
1790 this->SortVehicleList();
1791
1792 if (this->vehicles.size() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1793 HideDropDownMenu(this);
1794 }
1795
1796 /* Hide the widgets that we will not use in this window
1797 * Some windows contains actions only fit for the owner */
1798 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1799 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1800 if (plane_to_show != nwi->shown_plane) {
1801 nwi->SetDisplayedPlane(plane_to_show);
1802 nwi->SetDirty(this);
1803 }
1804 if (this->owner == _local_company) {
1805 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1806 this->SetWidgetsDisabledState(this->vehicles.size() == 0,
1807 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1808 WID_VL_STOP_ALL,
1809 WID_VL_START_ALL,
1810 WIDGET_LIST_END);
1811 }
1812
1813 /* Set text of group by dropdown widget. */
1814 this->GetWidget<NWidgetCore>(WID_VL_GROUP_BY_PULLDOWN)->widget_data = this->vehicle_group_by_names[this->grouping];
1815
1816 /* Set text of sort by dropdown widget. */
1817 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->GetVehicleSorterNames()[this->vehgroups.SortType()];
1818
1819 this->DrawWidgets();
1820 }
1821
OnClickVehicleListWindow1822 void OnClick(Point pt, int widget, int click_count) override
1823 {
1824 switch (widget) {
1825 case WID_VL_ORDER_VIEW: // Open the shared orders window
1826 assert(this->vli.type == VL_SHARED_ORDERS);
1827 assert(!this->vehicles.empty());
1828 ShowOrdersWindow(this->vehicles[0]);
1829 break;
1830
1831 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1832 this->vehgroups.ToggleSortOrder();
1833 this->SetDirty();
1834 break;
1835
1836 case WID_VL_GROUP_BY_PULLDOWN: // Select sorting criteria dropdown menu
1837 ShowDropDownMenu(this, this->vehicle_group_by_names, this->grouping, WID_VL_GROUP_BY_PULLDOWN, 0, 0);
1838 return;
1839
1840 case WID_VL_SORT_BY_PULLDOWN: // Select sorting criteria dropdown menu
1841 ShowDropDownMenu(this, this->GetVehicleSorterNames(), this->vehgroups.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1842 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1843 return;
1844
1845 case WID_VL_LIST: { // Matrix to show vehicles
1846 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1847 if (id_v >= this->vehgroups.size()) return; // click out of list bound
1848
1849 const GUIVehicleGroup &vehgroup = this->vehgroups[id_v];
1850 switch (this->grouping) {
1851 case GB_NONE: {
1852 const Vehicle *v = vehgroup.GetSingleVehicle();
1853 if (!VehicleClicked(v)) {
1854 if (_ctrl_pressed) {
1855 ShowCompanyGroupForVehicle(v);
1856 } else {
1857 ShowVehicleViewWindow(v);
1858 }
1859 }
1860 break;
1861 }
1862
1863 case GB_SHARED_ORDERS: {
1864 assert(vehgroup.NumVehicles() > 0);
1865 const Vehicle *v = vehgroup.vehicles_begin[0];
1866 /* We do not support VehicleClicked() here since the contextual action may only make sense for individual vehicles */
1867
1868 if (_ctrl_pressed) {
1869 ShowOrdersWindow(v);
1870 } else {
1871 if (vehgroup.NumVehicles() == 1) {
1872 ShowVehicleViewWindow(v);
1873 } else {
1874 ShowVehicleListWindow(v);
1875 }
1876 }
1877 break;
1878 }
1879
1880 default: NOT_REACHED();
1881 }
1882
1883 break;
1884 }
1885
1886 case WID_VL_AVAILABLE_VEHICLES:
1887 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1888 break;
1889
1890 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1891 ShowDropDownList(this, this->BuildActionDropdownList(VehicleListIdentifier::UnPack(this->window_number).type == VL_STANDARD, false), 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1892 break;
1893 }
1894
1895 case WID_VL_STOP_ALL:
1896 case WID_VL_START_ALL:
1897 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1898 break;
1899 }
1900 }
1901
OnDropdownSelectVehicleListWindow1902 void OnDropdownSelect(int widget, int index) override
1903 {
1904 switch (widget) {
1905 case WID_VL_GROUP_BY_PULLDOWN:
1906 this->UpdateVehicleGroupBy(static_cast<GroupBy>(index));
1907 break;
1908
1909 case WID_VL_SORT_BY_PULLDOWN:
1910 this->vehgroups.SetSortType(index);
1911 break;
1912
1913 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1914 assert(this->vehicles.size() != 0);
1915
1916 switch (index) {
1917 case ADI_REPLACE: // Replace window
1918 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1919 break;
1920 case ADI_SERVICE: // Send for servicing
1921 case ADI_DEPOT: // Send to Depots
1922 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
1923 break;
1924
1925 default: NOT_REACHED();
1926 }
1927 break;
1928
1929 default: NOT_REACHED();
1930 }
1931 this->SetDirty();
1932 }
1933
OnGameTickVehicleListWindow1934 void OnGameTick() override
1935 {
1936 if (this->vehgroups.NeedResort()) {
1937 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1938
1939 Debug(misc, 3, "Periodic resort {} list company {} at station {}", this->vli.vtype, this->owner, station);
1940 this->SetDirty();
1941 }
1942 }
1943
OnResizeVehicleListWindow1944 void OnResize() override
1945 {
1946 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1947 }
1948
1949 /**
1950 * Some data on this window has become invalid.
1951 * @param data Information about the changed data.
1952 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1953 */
OnInvalidateDataVehicleListWindow1954 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1955 {
1956 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1957 /* Needs to be done in command-scope, so everything stays valid */
1958 this->vli.index = GB(data, 0, 20);
1959 this->window_number = this->vli.Pack();
1960 this->vehgroups.ForceRebuild();
1961 return;
1962 }
1963
1964 if (data == 0) {
1965 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1966 this->vehgroups.ForceRebuild();
1967 } else {
1968 this->vehgroups.ForceResort();
1969 }
1970 }
1971 };
1972
1973 static WindowDesc _vehicle_list_other_desc(
1974 WDP_AUTO, "list_vehicles", 260, 246,
1975 WC_INVALID, WC_NONE,
1976 0,
1977 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1978 );
1979
1980 static WindowDesc _vehicle_list_train_desc(
1981 WDP_AUTO, "list_vehicles_train", 325, 246,
1982 WC_TRAINS_LIST, WC_NONE,
1983 0,
1984 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1985 );
1986
ShowVehicleListWindowLocal(CompanyID company,VehicleListType vlt,VehicleType vehicle_type,uint32 unique_number)1987 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1988 {
1989 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1990
1991 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1992 if (vehicle_type == VEH_TRAIN) {
1993 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
1994 } else {
1995 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
1996 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
1997 }
1998 }
1999
ShowVehicleListWindow(CompanyID company,VehicleType vehicle_type)2000 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
2001 {
2002 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
2003 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
2004 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
2005 */
2006
2007 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
2008 ShowCompanyGroup(company, vehicle_type);
2009 } else {
2010 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
2011 }
2012 }
2013
ShowVehicleListWindow(const Vehicle * v)2014 void ShowVehicleListWindow(const Vehicle *v)
2015 {
2016 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
2017 }
2018
ShowVehicleListWindow(CompanyID company,VehicleType vehicle_type,StationID station)2019 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
2020 {
2021 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
2022 }
2023
ShowVehicleListWindow(CompanyID company,VehicleType vehicle_type,TileIndex depot_tile)2024 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
2025 {
2026 uint16 depot_airport_index;
2027
2028 if (vehicle_type == VEH_AIRCRAFT) {
2029 depot_airport_index = GetStationIndex(depot_tile);
2030 } else {
2031 depot_airport_index = GetDepotIndex(depot_tile);
2032 }
2033 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
2034 }
2035
2036
2037 /* Unified vehicle GUI - Vehicle Details Window */
2038
2039 static_assert(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
2040 static_assert(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
2041 static_assert(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
2042 static_assert(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
2043
2044 /** Vehicle details widgets (other than train). */
2045 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
2046 NWidget(NWID_HORIZONTAL),
2047 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2048 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2049 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2050 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2051 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2052 EndContainer(),
2053 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
2054 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
2055 NWidget(NWID_HORIZONTAL),
2056 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2057 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2058 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2059 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2060 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2061 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2062 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2063 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2064 EndContainer(),
2065 };
2066
2067 /** Train details widgets. */
2068 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
2069 NWidget(NWID_HORIZONTAL),
2070 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2071 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2072 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2073 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2074 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2075 EndContainer(),
2076 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
2077 NWidget(NWID_HORIZONTAL),
2078 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
2079 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
2080 EndContainer(),
2081 NWidget(NWID_HORIZONTAL),
2082 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2083 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2084 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2085 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2086 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2087 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2088 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2089 EndContainer(),
2090 NWidget(NWID_HORIZONTAL),
2091 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
2092 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2093 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
2094 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2095 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
2096 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2097 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
2098 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2099 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2100 EndContainer(),
2101 };
2102
2103
2104 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
2105 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
2106 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
2107 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
2108 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
2109
2110 static StringID _service_interval_dropdown[] = {
2111 STR_VEHICLE_DETAILS_DEFAULT,
2112 STR_VEHICLE_DETAILS_DAYS,
2113 STR_VEHICLE_DETAILS_PERCENT,
2114 INVALID_STRING_ID,
2115 };
2116
2117 /** Class for managing the vehicle details window. */
2118 struct VehicleDetailsWindow : Window {
2119 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
2120 Scrollbar *vscroll;
2121
2122 /** Initialize a newly created vehicle details window */
VehicleDetailsWindowVehicleDetailsWindow2123 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2124 {
2125 const Vehicle *v = Vehicle::Get(window_number);
2126
2127 this->CreateNestedTree();
2128 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
2129 this->FinishInitNested(window_number);
2130
2131 this->owner = v->owner;
2132 this->tab = TDW_TAB_CARGO;
2133 }
2134
2135 /**
2136 * Some data on this window has become invalid.
2137 * @param data Information about the changed data.
2138 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2139 */
OnInvalidateDataVehicleDetailsWindow2140 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2141 {
2142 if (data == VIWD_AUTOREPLACE) {
2143 /* Autoreplace replaced the vehicle.
2144 * Nothing to do for this window. */
2145 return;
2146 }
2147 if (!gui_scope) return;
2148 const Vehicle *v = Vehicle::Get(this->window_number);
2149 if (v->type == VEH_ROAD) {
2150 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
2151 uint aimed_height = this->GetRoadVehDetailsHeight(v);
2152 /* If the number of articulated parts changes, the size of the window must change too. */
2153 if (aimed_height != nwid_info->current_y) {
2154 this->ReInit();
2155 }
2156 }
2157 }
2158
2159 /**
2160 * Gets the desired height for the road vehicle details panel.
2161 * @param v Road vehicle being shown.
2162 * @return Desired height in pixels.
2163 */
GetRoadVehDetailsHeightVehicleDetailsWindow2164 uint GetRoadVehDetailsHeight(const Vehicle *v)
2165 {
2166 uint desired_height;
2167 if (v->HasArticulatedPart()) {
2168 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2169 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
2170 /* Add space for the cargo amount for each part. */
2171 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2172 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
2173 }
2174 } else {
2175 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2176 }
2177 return desired_height;
2178 }
2179
UpdateWidgetSizeVehicleDetailsWindow2180 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2181 {
2182 switch (widget) {
2183 case WID_VD_TOP_DETAILS: {
2184 Dimension dim = { 0, 0 };
2185 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2186
2187 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
2188 static const StringID info_strings[] = {
2189 STR_VEHICLE_INFO_MAX_SPEED,
2190 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
2191 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
2192 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
2193 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
2194 };
2195 for (uint i = 0; i < lengthof(info_strings); i++) {
2196 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
2197 }
2198 SetDParam(0, STR_VEHICLE_INFO_AGE);
2199 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2200 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2201 break;
2202 }
2203
2204 case WID_VD_MIDDLE_DETAILS: {
2205 const Vehicle *v = Vehicle::Get(this->window_number);
2206 switch (v->type) {
2207 case VEH_ROAD:
2208 size->height = this->GetRoadVehDetailsHeight(v);
2209 break;
2210
2211 case VEH_SHIP:
2212 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2213 break;
2214
2215 case VEH_AIRCRAFT:
2216 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
2217 break;
2218
2219 default:
2220 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2221 }
2222 break;
2223 }
2224
2225 case WID_VD_MATRIX:
2226 resize->height = std::max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
2227 size->height = 4 * resize->height;
2228 break;
2229
2230 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2231 StringID *strs = _service_interval_dropdown;
2232 while (*strs != INVALID_STRING_ID) {
2233 *size = maxdim(*size, GetStringBoundingBox(*strs++));
2234 }
2235 size->width += padding.width;
2236 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2237 break;
2238 }
2239
2240 case WID_VD_SERVICING_INTERVAL:
2241 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2242 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
2243 size->width = std::max(
2244 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT).width,
2245 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS).width
2246 ) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2247 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2248 break;
2249 }
2250 }
2251
2252 /** Checks whether service interval is enabled for the vehicle. */
IsVehicleServiceIntervalEnabledVehicleDetailsWindow2253 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2254 {
2255 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2256 switch (vehicle_type) {
2257 default: NOT_REACHED();
2258 case VEH_TRAIN: return vds->servint_trains != 0;
2259 case VEH_ROAD: return vds->servint_roadveh != 0;
2260 case VEH_SHIP: return vds->servint_ships != 0;
2261 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2262 }
2263 }
2264
2265 /**
2266 * Draw the details for the given vehicle at the position of the Details windows
2267 *
2268 * @param v current vehicle
2269 * @param left The left most coordinate to draw
2270 * @param right The right most coordinate to draw
2271 * @param y The y coordinate
2272 * @param vscroll_pos Position of scrollbar (train only)
2273 * @param vscroll_cap Number of lines currently displayed (train only)
2274 * @param det_tab Selected details tab (train only)
2275 */
DrawVehicleDetailsVehicleDetailsWindow2276 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2277 {
2278 switch (v->type) {
2279 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2280 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2281 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2282 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2283 default: NOT_REACHED();
2284 }
2285 }
2286
SetStringParametersVehicleDetailsWindow2287 void SetStringParameters(int widget) const override
2288 {
2289 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2290 }
2291
DrawWidgetVehicleDetailsWindow2292 void DrawWidget(const Rect &r, int widget) const override
2293 {
2294 const Vehicle *v = Vehicle::Get(this->window_number);
2295
2296 switch (widget) {
2297 case WID_VD_TOP_DETAILS: {
2298 int y = r.top + WD_FRAMERECT_TOP;
2299
2300 /* Draw running cost */
2301 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2302 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2303 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2304 SetDParam(3, v->GetDisplayRunningCost());
2305 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2306 y += FONT_HEIGHT_NORMAL;
2307
2308 /* Draw max speed */
2309 StringID string;
2310 if (v->type == VEH_TRAIN ||
2311 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2312 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2313 SetDParam(2, v->GetDisplayMaxSpeed());
2314 SetDParam(1, gcache->cached_power);
2315 SetDParam(0, gcache->cached_weight);
2316 SetDParam(3, gcache->cached_max_te / 1000);
2317 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2318 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2319 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2320 } else {
2321 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2322 }
2323 } else {
2324 SetDParam(0, v->GetDisplayMaxSpeed());
2325 if (v->type == VEH_AIRCRAFT) {
2326 SetDParam(1, v->GetEngine()->GetAircraftTypeText());
2327 if (Aircraft::From(v)->GetRange() > 0) {
2328 SetDParam(2, Aircraft::From(v)->GetRange());
2329 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE;
2330 } else {
2331 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE;
2332 }
2333 } else {
2334 string = STR_VEHICLE_INFO_MAX_SPEED;
2335 }
2336 }
2337 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2338 y += FONT_HEIGHT_NORMAL;
2339
2340 /* Draw profit */
2341 SetDParam(0, v->GetDisplayProfitThisYear());
2342 SetDParam(1, v->GetDisplayProfitLastYear());
2343 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2344 y += FONT_HEIGHT_NORMAL;
2345
2346 /* Draw breakdown & reliability */
2347 SetDParam(0, ToPercent16(v->reliability));
2348 SetDParam(1, v->breakdowns_since_last_service);
2349 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2350 break;
2351 }
2352
2353 case WID_VD_MATRIX:
2354 /* For trains only. */
2355 DrawVehicleDetails(v, r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, r.top + WD_MATRIX_TOP, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->tab);
2356 break;
2357
2358 case WID_VD_MIDDLE_DETAILS: {
2359 /* For other vehicles, at the place of the matrix. */
2360 bool rtl = _current_text_dir == TD_RTL;
2361 uint sprite_width = GetSingleVehicleWidth(v, EIT_IN_DETAILS) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2362
2363 uint text_left = r.left + (rtl ? 0 : sprite_width);
2364 uint text_right = r.right - (rtl ? sprite_width : 0);
2365
2366 /* Articulated road vehicles use a complete line. */
2367 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2368 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2369 } else {
2370 uint sprite_left = rtl ? text_right : r.left;
2371 uint sprite_right = rtl ? r.right : text_left;
2372
2373 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2374 }
2375 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2376 break;
2377 }
2378
2379 case WID_VD_SERVICING_INTERVAL:
2380 /* Draw service interval text */
2381 SetDParam(0, v->GetServiceInterval());
2382 SetDParam(1, v->date_of_last_service);
2383 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2384 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2385 break;
2386 }
2387 }
2388
2389 /** Repaint vehicle details window. */
OnPaintVehicleDetailsWindow2390 void OnPaint() override
2391 {
2392 const Vehicle *v = Vehicle::Get(this->window_number);
2393
2394 if (v->type == VEH_TRAIN) {
2395 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2396 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2397 }
2398
2399 /* Disable service-scroller when interval is set to disabled */
2400 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2401 WID_VD_INCREASE_SERVICING_INTERVAL,
2402 WID_VD_DECREASE_SERVICING_INTERVAL,
2403 WIDGET_LIST_END);
2404
2405 StringID str = v->ServiceIntervalIsCustom() ?
2406 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2407 STR_VEHICLE_DETAILS_DEFAULT;
2408 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2409
2410 this->DrawWidgets();
2411 }
2412
OnClickVehicleDetailsWindow2413 void OnClick(Point pt, int widget, int click_count) override
2414 {
2415 switch (widget) {
2416 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2417 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2418 int mod = _ctrl_pressed ? 5 : 10;
2419 const Vehicle *v = Vehicle::Get(this->window_number);
2420
2421 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2422 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2423 if (mod == v->GetServiceInterval()) return;
2424
2425 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2426 break;
2427 }
2428
2429 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2430 const Vehicle *v = Vehicle::Get(this->window_number);
2431 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2432 break;
2433 }
2434
2435 case WID_VD_DETAILS_CARGO_CARRIED:
2436 case WID_VD_DETAILS_TRAIN_VEHICLES:
2437 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2438 case WID_VD_DETAILS_TOTAL_CARGO:
2439 this->SetWidgetsDisabledState(false,
2440 WID_VD_DETAILS_CARGO_CARRIED,
2441 WID_VD_DETAILS_TRAIN_VEHICLES,
2442 WID_VD_DETAILS_CAPACITY_OF_EACH,
2443 WID_VD_DETAILS_TOTAL_CARGO,
2444 widget,
2445 WIDGET_LIST_END);
2446
2447 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2448 this->SetDirty();
2449 break;
2450 }
2451 }
2452
OnDropdownSelectVehicleDetailsWindow2453 void OnDropdownSelect(int widget, int index) override
2454 {
2455 switch (widget) {
2456 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2457 const Vehicle *v = Vehicle::Get(this->window_number);
2458 bool iscustom = index != 0;
2459 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2460 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2461 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2462 break;
2463 }
2464 }
2465 }
2466
OnResizeVehicleDetailsWindow2467 void OnResize() override
2468 {
2469 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2470 if (nwi != nullptr) {
2471 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2472 }
2473 }
2474 };
2475
2476 /** Vehicle details window descriptor. */
2477 static WindowDesc _train_vehicle_details_desc(
2478 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2479 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2480 0,
2481 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2482 );
2483
2484 /** Vehicle details window descriptor for other vehicles than a train. */
2485 static WindowDesc _nontrain_vehicle_details_desc(
2486 WDP_AUTO, "view_vehicle_details", 405, 113,
2487 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2488 0,
2489 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2490 );
2491
2492 /** Shows the vehicle details window of the given vehicle. */
ShowVehicleDetailsWindow(const Vehicle * v)2493 static void ShowVehicleDetailsWindow(const Vehicle *v)
2494 {
2495 CloseWindowById(WC_VEHICLE_ORDERS, v->index, false);
2496 CloseWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2497 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2498 }
2499
2500
2501 /* Unified vehicle GUI - Vehicle View Window */
2502
2503 /** Vehicle view widgets. */
2504 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2505 NWidget(NWID_HORIZONTAL),
2506 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2507 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_RENAME), SetMinimalSize(12, 14), SetDataTip(SPR_RENAME, STR_NULL /* filled in later */),
2508 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2509 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_NULL /* filled in later */),
2510 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2511 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2512 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2513 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2514 EndContainer(),
2515 NWidget(NWID_HORIZONTAL),
2516 NWidget(WWT_PANEL, COLOUR_GREY),
2517 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2518 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1),
2519 EndContainer(),
2520 EndContainer(),
2521 NWidget(NWID_VERTICAL),
2522 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2523 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2524 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2525 EndContainer(),
2526 /* For trains only, 'ignore signal' button. */
2527 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18),
2528 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2529 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2530 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2531 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18),
2532 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2533 EndContainer(),
2534 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2535 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2536 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2537 EndContainer(),
2538 EndContainer(),
2539 NWidget(NWID_HORIZONTAL),
2540 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2541 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_ORDER_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_VEHICLE_VIEW_ORDER_LOCATION_TOOLTIP),
2542 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2543 EndContainer(),
2544 };
2545
2546 /** Vehicle view window descriptor for all vehicles but trains. */
2547 static WindowDesc _vehicle_view_desc(
2548 WDP_AUTO, "view_vehicle", 250, 116,
2549 WC_VEHICLE_VIEW, WC_NONE,
2550 0,
2551 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2552 );
2553
2554 /**
2555 * Vehicle view window descriptor for trains. Only minimum_height and
2556 * default_height are different for train view.
2557 */
2558 static WindowDesc _train_view_desc(
2559 WDP_AUTO, "view_vehicle_train", 250, 134,
2560 WC_VEHICLE_VIEW, WC_NONE,
2561 0,
2562 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2563 );
2564
2565
2566 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2567 using them for array indexing in a number of places here. */
2568 static_assert(VEH_TRAIN == 0);
2569 static_assert(VEH_ROAD == 1);
2570 static_assert(VEH_SHIP == 2);
2571 static_assert(VEH_AIRCRAFT == 3);
2572
2573 /** Zoom levels for vehicle views indexed by vehicle type. */
2574 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2575 ZOOM_LVL_TRAIN,
2576 ZOOM_LVL_ROADVEH,
2577 ZOOM_LVL_SHIP,
2578 ZOOM_LVL_AIRCRAFT,
2579 };
2580
2581 /* Constants for geometry of vehicle view viewport */
2582 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2583 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2584 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2585
2586 /** Command indices for the _vehicle_command_translation_table. */
2587 enum VehicleCommandTranslation {
2588 VCT_CMD_START_STOP = 0,
2589 VCT_CMD_CLONE_VEH,
2590 VCT_CMD_TURN_AROUND,
2591 };
2592
2593 /** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
2594 static const uint32 _vehicle_command_translation_table[][4] = {
2595 { // VCT_CMD_START_STOP
2596 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
2597 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
2598 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
2599 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
2600 },
2601 { // VCT_CMD_CLONE_VEH
2602 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
2603 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
2604 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
2605 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
2606 },
2607 { // VCT_CMD_TURN_AROUND
2608 CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
2609 CMD_TURN_ROADVEH | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
2610 0xffffffff, // invalid for ships
2611 0xffffffff // invalid for aircraft
2612 },
2613 };
2614
2615 /**
2616 * This is the Callback method after attempting to start/stop a vehicle
2617 * @param result the result of the start/stop command
2618 * @param tile unused
2619 * @param p1 vehicle ID
2620 * @param p2 unused
2621 */
CcStartStopVehicle(const CommandCost & result,TileIndex tile,uint32 p1,uint32 p2,uint32 cmd)2622 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
2623 {
2624 if (result.Failed()) return;
2625
2626 const Vehicle *v = Vehicle::GetIfValid(p1);
2627 if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2628
2629 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2630 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2631 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2632 }
2633
2634 /**
2635 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2636 * @param v Vehicle to start/stop
2637 * @param texteffect Should a texteffect be shown?
2638 */
StartStopVehicle(const Vehicle * v,bool texteffect)2639 void StartStopVehicle(const Vehicle *v, bool texteffect)
2640 {
2641 assert(v->IsPrimaryVehicle());
2642 DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr);
2643 }
2644
2645 /** Checks whether the vehicle may be refitted at the moment.*/
IsVehicleRefitable(const Vehicle * v)2646 static bool IsVehicleRefitable(const Vehicle *v)
2647 {
2648 if (!v->IsStoppedInDepot()) return false;
2649
2650 do {
2651 if (IsEngineRefittable(v->engine_type)) return true;
2652 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
2653
2654 return false;
2655 }
2656
2657 /** Window manager class for viewing a vehicle. */
2658 struct VehicleViewWindow : Window {
2659 private:
2660 /** Display planes available in the vehicle view window. */
2661 enum PlaneSelections {
2662 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2663 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2664
2665 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2666 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2667
2668 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2669 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2670 };
2671 bool mouse_over_start_stop = false;
2672
2673 /**
2674 * Display a plane in the window.
2675 * @param plane Plane to show.
2676 */
SelectPlaneVehicleViewWindow2677 void SelectPlane(PlaneSelections plane)
2678 {
2679 switch (plane) {
2680 case SEL_DC_GOTO_DEPOT:
2681 case SEL_DC_CLONE:
2682 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2683 break;
2684
2685 case SEL_RT_REFIT:
2686 case SEL_RT_TURN_AROUND:
2687 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2688 break;
2689
2690 default:
2691 NOT_REACHED();
2692 }
2693 }
2694
2695 public:
VehicleViewWindowVehicleViewWindow2696 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2697 {
2698 this->flags |= WF_DISABLE_VP_SCROLL;
2699 this->CreateNestedTree();
2700
2701 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2702 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2703 SPR_SEND_TRAIN_TODEPOT,
2704 SPR_SEND_ROADVEH_TODEPOT,
2705 SPR_SEND_SHIP_TODEPOT,
2706 SPR_SEND_AIRCRAFT_TODEPOT,
2707 };
2708 const Vehicle *v = Vehicle::Get(window_number);
2709 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2710
2711 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2712 static const SpriteID vehicle_view_clone_sprites[] = {
2713 SPR_CLONE_TRAIN,
2714 SPR_CLONE_ROADVEH,
2715 SPR_CLONE_SHIP,
2716 SPR_CLONE_AIRCRAFT,
2717 };
2718 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2719
2720 switch (v->type) {
2721 case VEH_TRAIN:
2722 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2723 break;
2724
2725 case VEH_ROAD:
2726 break;
2727
2728 case VEH_SHIP:
2729 case VEH_AIRCRAFT:
2730 this->SelectPlane(SEL_RT_REFIT);
2731 break;
2732
2733 default: NOT_REACHED();
2734 }
2735 this->FinishInitNested(window_number);
2736 this->owner = v->owner;
2737 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2738
2739 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATUS_START_STOP_TOOLTIP + v->type;
2740 this->GetWidget<NWidgetCore>(WID_VV_RENAME)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
2741 this->GetWidget<NWidgetCore>(WID_VV_LOCATION)->tool_tip = STR_VEHICLE_VIEW_TRAIN_CENTER_TOOLTIP + v->type;
2742 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2743 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2744 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2745 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2746 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2747
2748 this->UpdateButtonStatus();
2749 }
2750
CloseVehicleViewWindow2751 void Close() override
2752 {
2753 CloseWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2754 CloseWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2755 CloseWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2756 CloseWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2757 this->Window::Close();
2758 }
2759
UpdateWidgetSizeVehicleViewWindow2760 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2761 {
2762 const Vehicle *v = Vehicle::Get(this->window_number);
2763 switch (widget) {
2764 case WID_VV_START_STOP:
2765 size->height = std::max({size->height, GetSpriteSize(SPR_WARNING_SIGN).height, GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height}) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM;
2766 break;
2767
2768 case WID_VV_FORCE_PROCEED:
2769 if (v->type != VEH_TRAIN) {
2770 size->height = 0;
2771 size->width = 0;
2772 }
2773 break;
2774
2775 case WID_VV_VIEWPORT:
2776 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2777 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2778 break;
2779 }
2780 }
2781
OnPaintVehicleViewWindow2782 void OnPaint() override
2783 {
2784 const Vehicle *v = Vehicle::Get(this->window_number);
2785 bool is_localcompany = v->owner == _local_company;
2786 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2787
2788 this->SetWidgetDisabledState(WID_VV_RENAME, !is_localcompany);
2789 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2790 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2791 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2792
2793 if (v->type == VEH_TRAIN) {
2794 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2795 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2796 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2797 }
2798
2799 this->SetWidgetDisabledState(WID_VV_ORDER_LOCATION, v->current_order.GetLocation(v) == INVALID_TILE);
2800
2801 this->DrawWidgets();
2802 }
2803
SetStringParametersVehicleViewWindow2804 void SetStringParameters(int widget) const override
2805 {
2806 if (widget != WID_VV_CAPTION) return;
2807
2808 const Vehicle *v = Vehicle::Get(this->window_number);
2809 SetDParam(0, v->index);
2810 }
2811
DrawWidgetVehicleViewWindow2812 void DrawWidget(const Rect &r, int widget) const override
2813 {
2814 if (widget != WID_VV_START_STOP) return;
2815
2816 const Vehicle *v = Vehicle::Get(this->window_number);
2817 StringID str;
2818 TextColour text_colour = TC_FROMSTRING;
2819 if (v->vehstatus & VS_CRASHED) {
2820 str = STR_VEHICLE_STATUS_CRASHED;
2821 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2822 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2823 } else if (v->vehstatus & VS_STOPPED && (!mouse_over_start_stop || v->IsStoppedInDepot())) {
2824 if (v->type == VEH_TRAIN) {
2825 if (v->cur_speed == 0) {
2826 if (Train::From(v)->gcache.cached_power == 0) {
2827 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2828 } else {
2829 str = STR_VEHICLE_STATUS_STOPPED;
2830 }
2831 } else {
2832 SetDParam(0, v->GetDisplaySpeed());
2833 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2834 }
2835 } else { // no train
2836 str = STR_VEHICLE_STATUS_STOPPED;
2837 }
2838 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2839 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2840 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2841 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2842 } else { // vehicle is in a "normal" state, show current order
2843 if (mouse_over_start_stop) {
2844 if (v->vehstatus & VS_STOPPED) {
2845 text_colour = TC_RED | TC_FORCED;
2846 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2847 text_colour = TC_ORANGE | TC_FORCED;
2848 }
2849 }
2850 switch (v->current_order.GetType()) {
2851 case OT_GOTO_STATION: {
2852 SetDParam(0, v->current_order.GetDestination());
2853 SetDParam(1, v->GetDisplaySpeed());
2854 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_STATION_VEL : STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2855 break;
2856 }
2857
2858 case OT_GOTO_DEPOT: {
2859 SetDParam(0, v->type);
2860 SetDParam(1, v->current_order.GetDestination());
2861 SetDParam(2, v->GetDisplaySpeed());
2862 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2863 /* This case *only* happens when multiple nearest depot orders
2864 * follow each other (including an order list only one order: a
2865 * nearest depot order) and there are no reachable depots.
2866 * It is primarily to guard for the case that there is no
2867 * depot with index 0, which would be used as fallback for
2868 * evaluating the string in the status bar. */
2869 str = STR_EMPTY;
2870 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2871 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2872 } else {
2873 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2874 }
2875 break;
2876 }
2877
2878 case OT_LOADING:
2879 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2880 break;
2881
2882 case OT_GOTO_WAYPOINT: {
2883 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2884 SetDParam(0, v->current_order.GetDestination());
2885 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_WAYPOINT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2886 SetDParam(1, v->GetDisplaySpeed());
2887 break;
2888 }
2889
2890 case OT_LEAVESTATION:
2891 if (v->type != VEH_AIRCRAFT) {
2892 str = STR_VEHICLE_STATUS_LEAVING;
2893 break;
2894 }
2895 FALLTHROUGH;
2896 default:
2897 if (v->GetNumManualOrders() == 0) {
2898 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2899 SetDParam(0, v->GetDisplaySpeed());
2900 } else {
2901 str = STR_EMPTY;
2902 }
2903 break;
2904 }
2905 }
2906
2907 /* Draw the flag plus orders. */
2908 bool rtl = (_current_text_dir == TD_RTL);
2909 uint text_offset = std::max({GetSpriteSize(SPR_WARNING_SIGN).width, GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width}) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2910 int height = r.bottom - r.top;
2911 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2912 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2913 int text_top = r.top + WD_FRAMERECT_TOP + (height - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM - FONT_HEIGHT_NORMAL) / 2;
2914 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) ? SPR_WARNING_SIGN : SPR_FLAG_VEH_RUNNING;
2915 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2916 int image_top = r.top + WD_IMGBTN_TOP + (height - WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM - GetSpriteSize(image).height) / 2;
2917 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2918 DrawSprite(image, PAL_NONE, image_left + lowered, image_top + lowered);
2919 DrawString(text_left + lowered, text_right + lowered, text_top + lowered, str, text_colour, SA_HOR_CENTER);
2920 }
2921
OnClickVehicleViewWindow2922 void OnClick(Point pt, int widget, int click_count) override
2923 {
2924 const Vehicle *v = Vehicle::Get(this->window_number);
2925
2926 switch (widget) {
2927 case WID_VV_RENAME: { // rename
2928 SetDParam(0, v->index);
2929 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2930 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2931 break;
2932 }
2933
2934 case WID_VV_START_STOP: // start stop
2935 StartStopVehicle(v, false);
2936 break;
2937
2938 case WID_VV_ORDER_LOCATION: {
2939 /* Scroll to current order destination */
2940 TileIndex tile = v->current_order.GetLocation(v);
2941 if (tile == INVALID_TILE) break;
2942
2943 if (_ctrl_pressed) {
2944 ShowExtraViewportWindow(tile);
2945 } else {
2946 ScrollMainWindowToTile(tile);
2947 }
2948 break;
2949 }
2950
2951 case WID_VV_LOCATION: // center main view
2952 if (_ctrl_pressed) {
2953 ShowExtraViewportWindow(TileVirtXY(v->x_pos, v->y_pos));
2954 } else {
2955 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2956 if (click_count > 1 && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2957 /* main window 'follows' vehicle */
2958 mainwindow->viewport->follow_vehicle = v->index;
2959 } else {
2960 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2961 }
2962 }
2963 break;
2964
2965 case WID_VV_GOTO_DEPOT: // goto hangar
2966 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
2967 break;
2968 case WID_VV_REFIT: // refit
2969 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
2970 break;
2971 case WID_VV_SHOW_ORDERS: // show orders
2972 if (_ctrl_pressed) {
2973 ShowTimetableWindow(v);
2974 } else {
2975 ShowOrdersWindow(v);
2976 }
2977 break;
2978 case WID_VV_SHOW_DETAILS: // show details
2979 if (_ctrl_pressed) {
2980 ShowCompanyGroupForVehicle(v);
2981 } else {
2982 ShowVehicleDetailsWindow(v);
2983 }
2984 break;
2985 case WID_VV_CLONE: // clone vehicle
2986 /* Suppress the vehicle GUI when share-cloning.
2987 * There is no point to it except for starting the vehicle.
2988 * For starting the vehicle the player has to open the depot GUI, which is
2989 * most likely already open, but is also visible in the vehicle viewport. */
2990 DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
2991 _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
2992 _ctrl_pressed ? nullptr : CcCloneVehicle);
2993 break;
2994 case WID_VV_TURN_AROUND: // turn around
2995 assert(v->IsGroundVehicle());
2996 DoCommandP(v->tile, v->index, 0,
2997 _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
2998 break;
2999 case WID_VV_FORCE_PROCEED: // force proceed
3000 assert(v->type == VEH_TRAIN);
3001 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
3002 break;
3003 }
3004 }
3005
OnQueryTextFinishedVehicleViewWindow3006 void OnQueryTextFinished(char *str) override
3007 {
3008 if (str == nullptr) return;
3009
3010 DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), nullptr, str);
3011 }
3012
OnMouseOverVehicleViewWindow3013 void OnMouseOver(Point pt, int widget) override
3014 {
3015 bool start_stop = widget == WID_VV_START_STOP;
3016 if (start_stop != mouse_over_start_stop) {
3017 mouse_over_start_stop = start_stop;
3018 this->SetWidgetDirty(WID_VV_START_STOP);
3019 }
3020 }
3021
OnResizeVehicleViewWindow3022 void OnResize() override
3023 {
3024 if (this->viewport != nullptr) {
3025 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
3026 nvp->UpdateViewportCoordinates(this);
3027 }
3028 }
3029
UpdateButtonStatusVehicleViewWindow3030 void UpdateButtonStatus()
3031 {
3032 const Vehicle *v = Vehicle::Get(this->window_number);
3033 bool veh_stopped = v->IsStoppedInDepot();
3034
3035 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
3036 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
3037 */
3038 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
3039 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
3040 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
3041 this->SelectPlane(plane);
3042 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
3043 }
3044 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
3045 if (v->IsGroundVehicle()) {
3046 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
3047 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
3048 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
3049 this->SelectPlane(plane);
3050 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
3051 }
3052 }
3053 }
3054
3055 /**
3056 * Some data on this window has become invalid.
3057 * @param data Information about the changed data.
3058 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
3059 */
OnInvalidateDataVehicleViewWindow3060 void OnInvalidateData(int data = 0, bool gui_scope = true) override
3061 {
3062 if (data == VIWD_AUTOREPLACE) {
3063 /* Autoreplace replaced the vehicle.
3064 * Nothing to do for this window. */
3065 return;
3066 }
3067
3068 this->UpdateButtonStatus();
3069 }
3070
IsNewGRFInspectableVehicleViewWindow3071 bool IsNewGRFInspectable() const override
3072 {
3073 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3074 }
3075
ShowNewGRFInspectWindowVehicleViewWindow3076 void ShowNewGRFInspectWindow() const override
3077 {
3078 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3079 }
3080 };
3081
3082
3083 /** Shows the vehicle view window of the given vehicle. */
ShowVehicleViewWindow(const Vehicle * v)3084 void ShowVehicleViewWindow(const Vehicle *v)
3085 {
3086 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
3087 }
3088
3089 /**
3090 * Dispatch a "vehicle selected" event if any window waits for it.
3091 * @param v selected vehicle;
3092 * @return did any window accept vehicle selection?
3093 */
VehicleClicked(const Vehicle * v)3094 bool VehicleClicked(const Vehicle *v)
3095 {
3096 assert(v != nullptr);
3097 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3098
3099 v = v->First();
3100 if (!v->IsPrimaryVehicle()) return false;
3101
3102 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
3103 }
3104
StopGlobalFollowVehicle(const Vehicle * v)3105 void StopGlobalFollowVehicle(const Vehicle *v)
3106 {
3107 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
3108 if (w != nullptr && w->viewport->follow_vehicle == v->index) {
3109 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
3110 w->viewport->follow_vehicle = INVALID_VEHICLE;
3111 }
3112 }
3113
3114
3115 /**
3116 * This is the Callback method after the construction attempt of a primary vehicle
3117 * @param result indicates completion (or not) of the operation
3118 * @param tile unused
3119 * @param p1 unused
3120 * @param p2 unused
3121 * @param cmd unused
3122 */
CcBuildPrimaryVehicle(const CommandCost & result,TileIndex tile,uint32 p1,uint32 p2,uint32 cmd)3123 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
3124 {
3125 if (result.Failed()) return;
3126
3127 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
3128 ShowVehicleViewWindow(v);
3129 }
3130
3131 /**
3132 * Get the width of a vehicle (part) in pixels.
3133 * @param v Vehicle to get the width for.
3134 * @return Width of the vehicle.
3135 */
GetSingleVehicleWidth(const Vehicle * v,EngineImageType image_type)3136 int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
3137 {
3138 switch (v->type) {
3139 case VEH_TRAIN:
3140 return Train::From(v)->GetDisplayImageWidth();
3141
3142 case VEH_ROAD:
3143 return RoadVehicle::From(v)->GetDisplayImageWidth();
3144
3145 default:
3146 bool rtl = _current_text_dir == TD_RTL;
3147 VehicleSpriteSeq seq;
3148 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3149 Rect rec;
3150 seq.GetBounds(&rec);
3151 return UnScaleGUI(rec.right - rec.left + 1);
3152 }
3153 }
3154
3155 /**
3156 * Get the width of a vehicle (including all parts of the consist) in pixels.
3157 * @param v Vehicle to get the width for.
3158 * @return Width of the vehicle.
3159 */
GetVehicleWidth(const Vehicle * v,EngineImageType image_type)3160 int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
3161 {
3162 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
3163 int vehicle_width = 0;
3164 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
3165 vehicle_width += GetSingleVehicleWidth(u, image_type);
3166 }
3167 return vehicle_width;
3168 } else {
3169 return GetSingleVehicleWidth(v, image_type);
3170 }
3171 }
3172
3173 /**
3174 * Set the mouse cursor to look like a vehicle.
3175 * @param v Vehicle
3176 * @param image_type Type of vehicle image to use.
3177 */
SetMouseCursorVehicle(const Vehicle * v,EngineImageType image_type)3178 void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
3179 {
3180 bool rtl = _current_text_dir == TD_RTL;
3181
3182 _cursor.sprite_count = 0;
3183 int total_width = 0;
3184 int y_offset = 0;
3185 bool rotor_seq = false; // Whether to draw the rotor of the vehicle in this step.
3186
3187 while (v != nullptr) {
3188 if (total_width >= ScaleGUITrad(2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH)) break;
3189
3190 PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
3191 VehicleSpriteSeq seq;
3192
3193 if (rotor_seq) {
3194 GetCustomRotorSprite(Aircraft::From(v), true, image_type, &seq);
3195 if (!seq.IsValid()) seq.Set(SPR_ROTOR_STOPPED);
3196 y_offset = - ScaleGUITrad(5);
3197 } else {
3198 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3199 }
3200
3201 if (_cursor.sprite_count + seq.count > lengthof(_cursor.sprite_seq)) break;
3202
3203 for (uint i = 0; i < seq.count; ++i) {
3204 PaletteID pal2 = (v->vehstatus & VS_CRASHED) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
3205 _cursor.sprite_seq[_cursor.sprite_count].sprite = seq.seq[i].sprite;
3206 _cursor.sprite_seq[_cursor.sprite_count].pal = pal2;
3207 _cursor.sprite_pos[_cursor.sprite_count].x = rtl ? -total_width : total_width;
3208 _cursor.sprite_pos[_cursor.sprite_count].y = y_offset;
3209 _cursor.sprite_count++;
3210 }
3211
3212 if (v->type == VEH_AIRCRAFT && v->subtype == AIR_HELICOPTER && !rotor_seq) {
3213 /* Draw rotor part in the next step. */
3214 rotor_seq = true;
3215 } else {
3216 total_width += GetSingleVehicleWidth(v, image_type);
3217 v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
3218 }
3219 }
3220
3221 int offs = (ScaleGUITrad(VEHICLEINFO_FULL_VEHICLE_WIDTH) - total_width) / 2;
3222 if (rtl) offs = -offs;
3223 for (uint i = 0; i < _cursor.sprite_count; ++i) {
3224 _cursor.sprite_pos[i].x += offs;
3225 }
3226
3227 UpdateCursorSize();
3228 }
3229