Codechange: Use null pointer literal instead of the NULL macro
[openttd-github.git] / src / vehicle_gui.cpp
blobb2517f967923bb18beb7315aeea4f60d66660e27
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file vehicle_gui.cpp The base GUI for all vehicles. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "company_func.h"
15 #include "gui.h"
16 #include "textbuf_gui.h"
17 #include "command_func.h"
18 #include "vehicle_gui_base.h"
19 #include "viewport_func.h"
20 #include "newgrf_text.h"
21 #include "newgrf_debug.h"
22 #include "roadveh.h"
23 #include "train.h"
24 #include "aircraft.h"
25 #include "depot_map.h"
26 #include "group_gui.h"
27 #include "strings_func.h"
28 #include "vehicle_func.h"
29 #include "autoreplace_gui.h"
30 #include "string_func.h"
31 #include "widgets/dropdown_func.h"
32 #include "timetable.h"
33 #include "articulated_vehicles.h"
34 #include "spritecache.h"
35 #include "core/geometry_func.hpp"
36 #include "company_base.h"
37 #include "engine_func.h"
38 #include "station_base.h"
39 #include "tilehighlight_func.h"
40 #include "zoom_func.h"
42 #include "safeguards.h"
45 Sorting _sorting;
47 static GUIVehicleList::SortFunction VehicleNumberSorter;
48 static GUIVehicleList::SortFunction VehicleNameSorter;
49 static GUIVehicleList::SortFunction VehicleAgeSorter;
50 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
51 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
52 static GUIVehicleList::SortFunction VehicleCargoSorter;
53 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
54 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
55 static GUIVehicleList::SortFunction VehicleModelSorter;
56 static GUIVehicleList::SortFunction VehicleValueSorter;
57 static GUIVehicleList::SortFunction VehicleLengthSorter;
58 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
59 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
61 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
62 &VehicleNumberSorter,
63 &VehicleNameSorter,
64 &VehicleAgeSorter,
65 &VehicleProfitThisYearSorter,
66 &VehicleProfitLastYearSorter,
67 &VehicleCargoSorter,
68 &VehicleReliabilitySorter,
69 &VehicleMaxSpeedSorter,
70 &VehicleModelSorter,
71 &VehicleValueSorter,
72 &VehicleLengthSorter,
73 &VehicleTimeToLiveSorter,
74 &VehicleTimetableDelaySorter,
77 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
78 STR_SORT_BY_NUMBER,
79 STR_SORT_BY_NAME,
80 STR_SORT_BY_AGE,
81 STR_SORT_BY_PROFIT_THIS_YEAR,
82 STR_SORT_BY_PROFIT_LAST_YEAR,
83 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
84 STR_SORT_BY_RELIABILITY,
85 STR_SORT_BY_MAX_SPEED,
86 STR_SORT_BY_MODEL,
87 STR_SORT_BY_VALUE,
88 STR_SORT_BY_LENGTH,
89 STR_SORT_BY_LIFE_TIME,
90 STR_SORT_BY_TIMETABLE_DELAY,
91 INVALID_STRING_ID
94 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
95 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
96 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
97 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
98 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
102 * Get the number of digits the biggest unit number of a set of vehicles has.
103 * @param vehicles The list of vehicles.
104 * @return The number of digits to allocate space for.
106 uint GetUnitNumberDigits(VehicleList &vehicles)
108 uint unitnumber = 0;
109 for (const Vehicle *v : vehicles) {
110 unitnumber = max<uint>(unitnumber, v->unitnumber);
113 if (unitnumber >= 10000) return 5;
114 if (unitnumber >= 1000) return 4;
115 if (unitnumber >= 100) return 3;
118 * When the smallest unit number is less than 10, it is
119 * quite likely that it will expand to become more than
120 * 10 quite soon.
122 return 2;
125 void BaseVehicleListWindow::BuildVehicleList()
127 if (!this->vehicles.NeedRebuild()) return;
129 DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
131 GenerateVehicleSortList(&this->vehicles, this->vli);
133 this->unitnumber_digits = GetUnitNumberDigits(this->vehicles);
135 this->vehicles.RebuildDone();
136 this->vscroll->SetCount((uint)this->vehicles.size());
140 * Compute the size for the Action dropdown.
141 * @param show_autoreplace If true include the autoreplace item.
142 * @param show_group If true include group-related stuff.
143 * @return Required size.
145 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
147 Dimension d = {0, 0};
149 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
150 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
151 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
153 if (show_group) {
154 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
155 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
158 return d;
162 * Display the Action dropdown window.
163 * @param show_autoreplace If true include the autoreplace item.
164 * @param show_group If true include group-related stuff.
165 * @return Itemlist for dropdown
167 DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
169 DropDownList list;
171 if (show_autoreplace) list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false));
172 list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false));
173 list.emplace_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false));
175 if (show_group) {
176 list.emplace_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false));
177 list.emplace_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false));
180 return list;
183 /* cached values for VehicleNameSorter to spare many GetString() calls */
184 static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
186 void BaseVehicleListWindow::SortVehicleList()
188 if (this->vehicles.Sort()) return;
190 /* invalidate cached values for name sorter - vehicle names could change */
191 _last_vehicle[0] = _last_vehicle[1] = nullptr;
194 void DepotSortList(VehicleList *list)
196 if (list->size() < 2) return;
197 QSortT(list->data(), list->size(), &VehicleNumberSorter);
200 /** draw the vehicle profit button in the vehicle list window. */
201 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
203 SpriteID spr;
205 /* draw profit-based coloured icons */
206 if (v->age <= VEHICLE_PROFIT_MIN_AGE) {
207 spr = SPR_PROFIT_NA;
208 } else if (v->GetDisplayProfitLastYear() < 0) {
209 spr = SPR_PROFIT_NEGATIVE;
210 } else if (v->GetDisplayProfitLastYear() < VEHICLE_PROFIT_THRESHOLD) {
211 spr = SPR_PROFIT_SOME;
212 } else {
213 spr = SPR_PROFIT_LOT;
215 DrawSprite(spr, PAL_NONE, x, y);
218 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
219 static const uint MAX_REFIT_CYCLE = 256;
222 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
223 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
224 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
225 * @param v_from the vehicle to match the subtype from
226 * @param v_for the vehicle to get the subtype for
227 * @param dest_cargo_type Destination cargo type.
228 * @return the best sub type
230 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
232 v_from = v_from->GetFirstEnginePart();
233 v_for = v_for->GetFirstEnginePart();
235 /* Create a list of subtypes used by the various parts of v_for */
236 static std::vector<StringID> subtypes;
237 subtypes.clear();
238 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
239 const Engine *e_from = v_from->GetEngine();
240 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
241 include(subtypes, GetCargoSubtypeText(v_from));
244 byte ret_refit_cyc = 0;
245 bool success = false;
246 if (subtypes.size() > 0) {
247 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
248 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
249 const Engine *e = v->GetEngine();
250 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
251 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
253 CargoID old_cargo_type = v->cargo_type;
254 byte old_cargo_subtype = v->cargo_subtype;
256 /* Set the 'destination' cargo */
257 v->cargo_type = dest_cargo_type;
259 /* Cycle through the refits */
260 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
261 v->cargo_subtype = refit_cyc;
263 /* Make sure we don't pick up anything cached. */
264 v->First()->InvalidateNewGRFCache();
265 v->InvalidateNewGRFCache();
267 StringID subtype = GetCargoSubtypeText(v);
268 if (subtype == STR_EMPTY) break;
270 if (std::find(subtypes.begin(), subtypes.end(), subtype) == subtypes.end()) continue;
272 /* We found something matching. */
273 ret_refit_cyc = refit_cyc;
274 success = true;
275 break;
278 /* Reset the vehicle's cargo type */
279 v->cargo_type = old_cargo_type;
280 v->cargo_subtype = old_cargo_subtype;
282 /* Make sure we don't taint the vehicle. */
283 v->First()->InvalidateNewGRFCache();
284 v->InvalidateNewGRFCache();
286 if (success) break;
290 return ret_refit_cyc;
293 /** Option to refit a vehicle chain */
294 struct RefitOption {
295 CargoID cargo; ///< Cargo to refit to
296 byte subtype; ///< Subcargo to use
297 StringID string; ///< GRF-local String to display for the cargo
300 * Inequality operator for #RefitOption.
301 * @param other Compare to this #RefitOption.
302 * @return True if both #RefitOption are different.
304 inline bool operator != (const RefitOption &other) const
306 return other.cargo != this->cargo || other.string != this->string;
310 * Equality operator for #RefitOption.
311 * @param other Compare to this #RefitOption.
312 * @return True if both #RefitOption are equal.
314 inline bool operator == (const RefitOption &other) const
316 return other.cargo == this->cargo && other.string == this->string;
320 typedef std::vector<RefitOption> SubtypeList; ///< List of refit subtypes associated to a cargo.
323 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
324 * @param list List of subtype options for each (sorted) cargo.
325 * @param sel Selected refit cargo-type in the window
326 * @param pos Position of the selected item in caller widow
327 * @param rows Number of rows(capacity) in caller window
328 * @param delta Step height in caller window
329 * @param r Rectangle of the matrix widget.
331 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
333 uint y = r.top + WD_MATRIX_TOP;
334 uint current = 0;
336 bool rtl = _current_text_dir == TD_RTL;
337 uint iconwidth = max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
338 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
339 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
341 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
342 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
343 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
345 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
346 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
348 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
349 for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
350 for (uint j = 0; current < pos + rows && j < list[i].size(); j++) {
351 const RefitOption &refit = list[i][j];
353 /* Hide subtypes if sel[0] does not match */
354 if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
356 /* Refit options with a position smaller than pos don't have to be drawn. */
357 if (current < pos) {
358 current++;
359 continue;
362 if (list[i].size() > 1) {
363 if (refit.subtype != 0xFF) {
364 /* Draw tree lines */
365 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
366 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].size() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
367 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
368 } else {
369 /* Draw expand/collapse icon */
370 DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
374 TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
375 /* Get the cargo name. */
376 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
377 SetDParam(1, refit.string);
378 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
380 y += delta;
381 current++;
386 /** Refit cargo window. */
387 struct RefitWindow : public Window {
388 int sel[2]; ///< Index in refit options, sel[0] == -1 if nothing is selected.
389 RefitOption *cargo; ///< Refit option selected by #sel.
390 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
391 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
392 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
393 Scrollbar *vscroll; ///< The main scrollbar.
394 Scrollbar *hscroll; ///< Only used for long vehicles.
395 int vehicle_width; ///< Width of the vehicle being drawn.
396 int sprite_left; ///< Left position of the vehicle sprite.
397 int sprite_right; ///< Right position of the vehicle sprite.
398 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
399 int click_x; ///< Position of the first click while dragging.
400 VehicleID selected_vehicle; ///< First vehicle in the current selection.
401 uint8 num_vehicles; ///< Number of selected vehicles.
402 bool auto_refit; ///< Select cargo for auto-refitting.
405 * Collects all (cargo, subcargo) refit options of a vehicle chain.
407 void BuildRefitList()
409 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].clear();
410 Vehicle *v = Vehicle::Get(this->window_number);
412 /* Check only the selected vehicles. */
413 VehicleSet vehicles_to_refit;
414 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
416 do {
417 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end()) continue;
418 const Engine *e = v->GetEngine();
419 CargoTypes cmask = e->info.refit_mask;
420 byte callback_mask = e->info.callback_mask;
422 /* Skip this engine if it does not carry anything */
423 if (!e->CanCarryCargo()) continue;
424 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
425 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
427 /* Loop through all cargoes in the refit mask */
428 int current_index = 0;
429 const CargoSpec *cs;
430 FOR_ALL_SORTED_CARGOSPECS(cs) {
431 CargoID cid = cs->Index();
432 /* Skip cargo type if it's not listed */
433 if (!HasBit(cmask, cid)) {
434 current_index++;
435 continue;
438 bool first_vehicle = this->list[current_index].size() == 0;
439 if (first_vehicle) {
440 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
441 this->list[current_index].push_back({cid, 0xFF, STR_EMPTY});
444 /* Check the vehicle's callback mask for cargo suffixes.
445 * This is not supported for ordered refits, since subtypes only have a meaning
446 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
447 * autoreplace, autorenew, clone, order restoration, ... */
448 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
449 /* Make a note of the original cargo type. It has to be
450 * changed to test the cargo & subtype... */
451 CargoID temp_cargo = v->cargo_type;
452 byte temp_subtype = v->cargo_subtype;
454 v->cargo_type = cid;
456 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
457 v->cargo_subtype = refit_cyc;
459 /* Make sure we don't pick up anything cached. */
460 v->First()->InvalidateNewGRFCache();
461 v->InvalidateNewGRFCache();
463 StringID subtype = GetCargoSubtypeText(v);
465 if (first_vehicle) {
466 /* Append new subtype (don't add duplicates though) */
467 if (subtype == STR_EMPTY) break;
469 RefitOption option;
470 option.cargo = cid;
471 option.subtype = refit_cyc;
472 option.string = subtype;
473 include(this->list[current_index], option);
474 } else {
475 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
476 if (subtype == STR_EMPTY) {
477 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
478 SubtypeList &l = this->list[current_index];
479 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
480 for (uint i = 1; i < l.size(); i++) {
481 if (l[i].subtype >= refit_cyc) {
482 l.resize(i);
483 break;
486 break;
487 } else {
488 /* Check whether the subtype matches with the subtype of earlier vehicles. */
489 uint pos = 1;
490 SubtypeList &l = this->list[current_index];
491 while (pos < l.size() && l[pos].subtype != refit_cyc) pos++;
492 if (pos < l.size() && l[pos].string != subtype) {
493 /* String mismatch, remove item keeping the order */
494 l.erase(l.begin() + pos);
500 /* Reset the vehicle's cargo type */
501 v->cargo_type = temp_cargo;
502 v->cargo_subtype = temp_subtype;
504 /* And make sure we haven't tainted the cache */
505 v->First()->InvalidateNewGRFCache();
506 v->InvalidateNewGRFCache();
508 current_index++;
510 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
514 * Refresh scrollbar after selection changed
516 void RefreshScrollbar()
518 uint scroll_row = 0;
519 uint row = 0;
521 for (uint i = 0; i < NUM_CARGO; i++) {
522 for (uint j = 0; j < this->list[i].size(); j++) {
523 const RefitOption &refit = this->list[i][j];
525 /* Hide subtypes if sel[0] does not match */
526 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
528 if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
530 row++;
534 this->vscroll->SetCount(row);
535 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
539 * Select a row.
540 * @param click_row Clicked row
542 void SetSelection(uint click_row)
544 uint row = 0;
546 for (uint i = 0; i < NUM_CARGO; i++) {
547 for (uint j = 0; j < this->list[i].size(); j++) {
548 const RefitOption &refit = this->list[i][j];
550 /* Hide subtypes if sel[0] does not match */
551 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
553 if (row == click_row) {
554 this->sel[0] = i;
555 this->sel[1] = j;
556 return;
559 row++;
563 this->sel[0] = -1;
564 this->sel[1] = 0;
568 * Gets the #RefitOption placed in the selected index.
569 * @return Pointer to the #RefitOption currently in use.
571 RefitOption *GetRefitOption()
573 if (this->sel[0] < 0) return nullptr;
575 SubtypeList &l = this->list[this->sel[0]];
576 if ((uint)this->sel[1] >= l.size()) return nullptr;
578 return &l[this->sel[1]];
581 RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
583 this->sel[0] = -1;
584 this->sel[1] = 0;
585 this->auto_refit = auto_refit;
586 this->order = order;
587 this->CreateNestedTree();
589 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
590 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
591 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
592 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
593 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
594 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
595 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
596 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
597 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
599 this->FinishInitNested(v->index);
600 this->owner = v->owner;
602 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
605 void OnInit() override
607 if (this->cargo != nullptr) {
608 /* Store the RefitOption currently in use. */
609 RefitOption current_refit_option = *(this->cargo);
611 /* Rebuild the refit list */
612 this->BuildRefitList();
613 this->sel[0] = -1;
614 this->sel[1] = 0;
615 this->cargo = nullptr;
616 for (uint i = 0; this->cargo == nullptr && i < NUM_CARGO; i++) {
617 for (uint j = 0; j < list[i].size(); j++) {
618 if (list[i][j] == current_refit_option) {
619 this->sel[0] = i;
620 this->sel[1] = j;
621 this->cargo = &list[i][j];
622 break;
627 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
628 this->RefreshScrollbar();
629 } else {
630 /* Rebuild the refit list */
631 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
635 void OnPaint() override
637 /* Determine amount of items for scroller. */
638 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
640 /* Calculate sprite position. */
641 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
642 int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
643 this->sprite_left = vehicle_panel_display->pos_x;
644 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
645 if (_current_text_dir == TD_RTL) {
646 this->sprite_right -= sprite_width;
647 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
648 } else {
649 this->sprite_left += sprite_width;
650 this->vehicle_margin = sprite_left;
653 this->DrawWidgets();
656 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
658 switch (widget) {
659 case WID_VR_MATRIX:
660 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
661 size->height = resize->height * 8;
662 break;
664 case WID_VR_VEHICLE_PANEL_DISPLAY:
665 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
666 break;
668 case WID_VR_INFO:
669 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
670 break;
674 void SetStringParameters(int widget) const override
676 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
680 * Gets the #StringID to use for displaying capacity.
681 * @param option Cargo and cargo subtype to check for capacity.
682 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
683 * @post String parameters have been set.
685 StringID GetCapacityString(RefitOption *option) const
687 assert(_current_company == _local_company);
688 Vehicle *v = Vehicle::Get(this->window_number);
689 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | option->subtype << 8 | this->num_vehicles << 16 |
690 (int)this->auto_refit << 24, DC_QUERY_COST, GetCmdRefitVeh(v->type));
692 if (cost.Failed()) return INVALID_STRING_ID;
694 SetDParam(0, option->cargo);
695 SetDParam(1, _returned_refit_capacity);
697 Money money = cost.GetCost();
698 if (_returned_mail_refit_capacity > 0) {
699 SetDParam(2, CT_MAIL);
700 SetDParam(3, _returned_mail_refit_capacity);
701 if (this->order != INVALID_VEH_ORDER_ID) {
702 /* No predictable cost */
703 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
704 } else if (money <= 0) {
705 SetDParam(4, -money);
706 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
707 } else {
708 SetDParam(4, money);
709 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
711 } else {
712 if (this->order != INVALID_VEH_ORDER_ID) {
713 /* No predictable cost */
714 SetDParam(2, STR_EMPTY);
715 return STR_PURCHASE_INFO_CAPACITY;
716 } else if (money <= 0) {
717 SetDParam(2, -money);
718 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
719 } else {
720 SetDParam(2, money);
721 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
726 void DrawWidget(const Rect &r, int widget) const override
728 switch (widget) {
729 case WID_VR_VEHICLE_PANEL_DISPLAY: {
730 Vehicle *v = Vehicle::Get(this->window_number);
731 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
732 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
734 /* Highlight selected vehicles. */
735 if (this->order != INVALID_VEH_ORDER_ID) break;
736 int x = 0;
737 switch (v->type) {
738 case VEH_TRAIN: {
739 VehicleSet vehicles_to_refit;
740 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
742 int left = INT32_MIN;
743 int width = 0;
745 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
746 /* Start checking. */
747 const bool contained = std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), u->index) != vehicles_to_refit.end();
748 if (contained && left == INT32_MIN) {
749 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
750 width = 0;
753 /* Draw a selection. */
754 if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
755 if (u->Next() == nullptr && contained) {
756 int current_width = u->GetDisplayImageWidth();
757 width += current_width;
758 x += current_width;
761 int right = Clamp(left + width, 0, r.right);
762 left = max(0, left);
764 if (_current_text_dir == TD_RTL) {
765 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
766 left = right - width;
769 if (left != right) {
770 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
773 left = INT32_MIN;
776 int current_width = u->GetDisplayImageWidth();
777 width += current_width;
778 x += current_width;
780 break;
783 default: break;
785 break;
788 case WID_VR_MATRIX:
789 DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
790 break;
792 case WID_VR_INFO:
793 if (this->cargo != nullptr) {
794 StringID string = this->GetCapacityString(this->cargo);
795 if (string != INVALID_STRING_ID) {
796 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
797 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
800 break;
805 * Some data on this window has become invalid.
806 * @param data Information about the changed data.
807 * @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.
809 void OnInvalidateData(int data = 0, bool gui_scope = true) override
811 switch (data) {
812 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
813 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
814 /* Clear the selection. */
815 Vehicle *v = Vehicle::Get(this->window_number);
816 this->selected_vehicle = v->index;
817 this->num_vehicles = UINT8_MAX;
818 FALLTHROUGH;
821 case 2: { // The vehicle selection has changed; rebuild the entire list.
822 if (!gui_scope) break;
823 this->BuildRefitList();
825 /* The vehicle width has changed too. */
826 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
827 uint max_width = 0;
829 /* Check the width of all cargo information strings. */
830 for (uint i = 0; i < NUM_CARGO; i++) {
831 for (uint j = 0; j < this->list[i].size(); j++) {
832 StringID string = this->GetCapacityString(&list[i][j]);
833 if (string != INVALID_STRING_ID) {
834 Dimension dim = GetStringBoundingBox(string);
835 max_width = max(dim.width, max_width);
840 if (this->information_width < max_width) {
841 this->information_width = max_width;
842 this->ReInit();
844 FALLTHROUGH;
847 case 1: // A new cargo has been selected.
848 if (!gui_scope) break;
849 this->cargo = GetRefitOption();
850 this->RefreshScrollbar();
851 break;
855 int GetClickPosition(int click_x)
857 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
858 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
859 click_x -= this->vehicle_margin;
860 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
862 return click_x;
865 void SetSelectedVehicles(int drag_x)
867 drag_x = GetClickPosition(drag_x);
869 int left_x = min(this->click_x, drag_x);
870 int right_x = max(this->click_x, drag_x);
871 this->num_vehicles = 0;
873 Vehicle *v = Vehicle::Get(this->window_number);
874 /* Find the vehicle part that was clicked. */
875 switch (v->type) {
876 case VEH_TRAIN: {
877 /* Don't select anything if we are not clicking in the vehicle. */
878 if (left_x >= 0) {
879 const Train *u = Train::From(v);
880 bool start_counting = false;
881 for (; u != nullptr; u = u->Next()) {
882 int current_width = u->GetDisplayImageWidth();
883 left_x -= current_width;
884 right_x -= current_width;
886 if (left_x < 0 && !start_counting) {
887 this->selected_vehicle = u->index;
888 start_counting = true;
890 /* Count the first vehicle, even if articulated part */
891 this->num_vehicles++;
892 } else if (start_counting && !u->IsArticulatedPart()) {
893 /* Do not count articulated parts */
894 this->num_vehicles++;
897 if (right_x < 0) break;
901 /* If the selection is not correct, clear it. */
902 if (this->num_vehicles != 0) {
903 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
904 break;
906 FALLTHROUGH;
909 default:
910 /* Clear the selection. */
911 this->selected_vehicle = v->index;
912 this->num_vehicles = UINT8_MAX;
913 break;
917 void OnClick(Point pt, int widget, int click_count) override
919 switch (widget) {
920 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
921 if (this->order != INVALID_VEH_ORDER_ID) break;
922 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
923 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
924 this->SetSelectedVehicles(pt.x - nwi->pos_x);
925 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
926 if (!_ctrl_pressed) {
927 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
928 } else {
929 /* The vehicle selection has changed. */
930 this->InvalidateData(2);
932 break;
935 case WID_VR_MATRIX: { // listbox
936 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
937 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
938 this->InvalidateData(1);
940 if (click_count == 1) break;
941 FALLTHROUGH;
944 case WID_VR_REFIT: // refit button
945 if (this->cargo != nullptr) {
946 const Vehicle *v = Vehicle::Get(this->window_number);
948 if (this->order == INVALID_VEH_ORDER_ID) {
949 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
950 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
951 } else {
952 if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) delete this;
955 break;
959 void OnMouseDrag(Point pt, int widget) override
961 switch (widget) {
962 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
963 if (this->order != INVALID_VEH_ORDER_ID) break;
964 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
965 this->SetSelectedVehicles(pt.x - nwi->pos_x);
966 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
967 break;
972 void OnDragDrop(Point pt, int widget) override
974 switch (widget) {
975 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
976 if (this->order != INVALID_VEH_ORDER_ID) break;
977 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
978 this->SetSelectedVehicles(pt.x - nwi->pos_x);
979 this->InvalidateData(2);
980 break;
985 void OnResize() override
987 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
988 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
989 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
993 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
994 NWidget(NWID_HORIZONTAL),
995 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
996 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
997 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
998 EndContainer(),
999 /* Vehicle display + scrollbar. */
1000 NWidget(NWID_VERTICAL),
1001 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1002 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1003 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1004 EndContainer(),
1005 EndContainer(),
1006 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1007 /* Matrix + scrollbar. */
1008 NWidget(NWID_HORIZONTAL),
1009 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),
1010 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1011 EndContainer(),
1012 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1013 NWidget(NWID_HORIZONTAL),
1014 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1015 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1016 EndContainer(),
1019 static WindowDesc _vehicle_refit_desc(
1020 WDP_AUTO, "view_vehicle_refit", 240, 174,
1021 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1022 WDF_CONSTRUCTION,
1023 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1027 * Show the refit window for a vehicle
1028 * @param *v The vehicle to show the refit window for
1029 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1030 * @param parent the parent window of the refit window
1031 * @param auto_refit Choose cargo for auto-refitting
1033 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1035 DeleteWindowById(WC_VEHICLE_REFIT, v->index);
1036 RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
1037 w->parent = parent;
1040 /** Display list of cargo types of the engine, for the purchase information window */
1041 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1043 /* List of cargo types of this engine */
1044 CargoTypes cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1045 /* List of cargo types available in this climate */
1046 CargoTypes lmask = _cargo_mask;
1048 /* Draw nothing if the engine is not refittable */
1049 if (HasAtMostOneBit(cmask)) return y;
1051 if (cmask == lmask) {
1052 /* Engine can be refitted to all types in this climate */
1053 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1054 } else {
1055 /* Check if we are able to refit to more cargo types and unable to. If
1056 * so, invert the cargo types to list those that we can't refit to. */
1057 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1058 cmask ^= lmask;
1059 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1060 } else {
1061 SetDParam(0, STR_JUST_CARGO_LIST);
1063 SetDParam(1, cmask);
1066 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1069 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1070 StringID GetCargoSubtypeText(const Vehicle *v)
1072 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1073 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1074 if (cb != CALLBACK_FAILED) {
1075 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1076 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1078 if (cb != CALLBACK_FAILED) {
1079 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1082 return STR_EMPTY;
1085 /** Sort vehicles by their number */
1086 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
1088 return (*a)->unitnumber - (*b)->unitnumber;
1091 /** Sort vehicles by their name */
1092 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
1094 static char last_name[2][64];
1096 if (*a != _last_vehicle[0]) {
1097 _last_vehicle[0] = *a;
1098 SetDParam(0, (*a)->index);
1099 GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
1102 if (*b != _last_vehicle[1]) {
1103 _last_vehicle[1] = *b;
1104 SetDParam(0, (*b)->index);
1105 GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
1108 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1109 return (r != 0) ? r : VehicleNumberSorter(a, b);
1112 /** Sort vehicles by their age */
1113 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
1115 int r = (*a)->age - (*b)->age;
1116 return (r != 0) ? r : VehicleNumberSorter(a, b);
1119 /** Sort vehicles by this year profit */
1120 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1122 int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
1123 return (r != 0) ? r : VehicleNumberSorter(a, b);
1126 /** Sort vehicles by last year profit */
1127 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1129 int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
1130 return (r != 0) ? r : VehicleNumberSorter(a, b);
1133 /** Sort vehicles by their cargo */
1134 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
1136 const Vehicle *v;
1137 CargoArray diff;
1139 /* Append the cargo of the connected waggons */
1140 for (v = *a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1141 for (v = *b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1143 int r = 0;
1144 for (CargoID i = 0; i < NUM_CARGO; i++) {
1145 r = diff[i];
1146 if (r != 0) break;
1149 return (r != 0) ? r : VehicleNumberSorter(a, b);
1152 /** Sort vehicles by their reliability */
1153 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
1155 int r = (*a)->reliability - (*b)->reliability;
1156 return (r != 0) ? r : VehicleNumberSorter(a, b);
1159 /** Sort vehicles by their max speed */
1160 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
1162 int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
1163 return (r != 0) ? r : VehicleNumberSorter(a, b);
1166 /** Sort vehicles by model */
1167 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
1169 int r = (*a)->engine_type - (*b)->engine_type;
1170 return (r != 0) ? r : VehicleNumberSorter(a, b);
1173 /** Sort vehicles by their value */
1174 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
1176 const Vehicle *u;
1177 Money diff = 0;
1179 for (u = *a; u != nullptr; u = u->Next()) diff += u->value;
1180 for (u = *b; u != nullptr; u = u->Next()) diff -= u->value;
1182 int r = ClampToI32(diff);
1183 return (r != 0) ? r : VehicleNumberSorter(a, b);
1186 /** Sort vehicles by their length */
1187 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
1189 int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
1190 return (r != 0) ? r : VehicleNumberSorter(a, b);
1193 /** Sort vehicles by the time they can still live */
1194 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
1196 int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
1197 return (r != 0) ? r : VehicleNumberSorter(a, b);
1200 /** Sort vehicles by the timetable delay */
1201 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
1203 int r = (*a)->lateness_counter - (*b)->lateness_counter;
1204 return (r != 0) ? r : VehicleNumberSorter(a, b);
1207 void InitializeGUI()
1209 MemSetT(&_sorting, 0);
1213 * Assign a vehicle window a new vehicle
1214 * @param window_class WindowClass to search for
1215 * @param from_index the old vehicle ID
1216 * @param to_index the new vehicle ID
1218 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1220 Window *w = FindWindowById(window_class, from_index);
1221 if (w != nullptr) {
1222 /* Update window_number */
1223 w->window_number = to_index;
1224 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1226 /* Update vehicle drag data */
1227 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1228 _thd.window_number = to_index;
1231 /* Notify the window. */
1232 w->InvalidateData(VIWD_AUTOREPLACE, false);
1237 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1238 * @param from_index the old vehicle ID
1239 * @param to_index the new vehicle ID
1241 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1243 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1244 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1245 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1246 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1247 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1250 static const NWidgetPart _nested_vehicle_list[] = {
1251 NWidget(NWID_HORIZONTAL),
1252 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1253 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1254 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1255 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1256 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1257 EndContainer(),
1259 NWidget(NWID_HORIZONTAL),
1260 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1261 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1262 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
1263 EndContainer(),
1264 EndContainer(),
1266 NWidget(NWID_HORIZONTAL),
1267 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),
1268 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1269 EndContainer(),
1271 NWidget(NWID_HORIZONTAL),
1272 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1273 NWidget(NWID_HORIZONTAL),
1274 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1275 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1276 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1277 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1278 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1279 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1280 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1281 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1282 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1283 EndContainer(),
1284 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1285 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1286 EndContainer(),
1287 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1288 EndContainer(),
1291 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
1293 const Order *order = v->GetOrder(start);
1294 if (order == nullptr) return;
1296 bool rtl = _current_text_dir == TD_RTL;
1297 int l_offset = rtl ? 0 : ScaleGUITrad(6);
1298 int r_offset = rtl ? ScaleGUITrad(6) : 0;
1299 int i = 0;
1300 VehicleOrderID oid = start;
1302 do {
1303 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1305 if (order->IsType(OT_GOTO_STATION)) {
1306 SetDParam(0, order->GetDestination());
1307 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1309 y += FONT_HEIGHT_SMALL;
1310 if (++i == 4) break;
1313 oid++;
1314 order = order->next;
1315 if (order == nullptr) {
1316 order = v->orders.list->GetFirstOrder();
1317 oid = 0;
1319 } while (oid != start);
1323 * Draws an image of a vehicle chain
1324 * @param v Front vehicle
1325 * @param left The minimum horizontal position
1326 * @param right The maximum horizontal position
1327 * @param y Vertical position to draw at
1328 * @param selection Selected vehicle to draw a frame around
1329 * @param skip Number of pixels to skip at the front (for scrolling)
1331 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1333 switch (v->type) {
1334 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1335 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1336 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1337 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1338 default: NOT_REACHED();
1343 * Get the height of a vehicle in the vehicle list GUIs.
1344 * @param type the vehicle type to look at
1345 * @param divisor the resulting height must be dividable by this
1346 * @return the height
1348 uint GetVehicleListHeight(VehicleType type, uint divisor)
1350 /* Name + vehicle + profit */
1351 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1352 /* Drawing of the 4 small orders + profit*/
1353 if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
1355 if (divisor == 1) return base;
1357 /* Make sure the height is dividable by divisor */
1358 uint rem = base % divisor;
1359 return base + (rem == 0 ? 0 : divisor - rem);
1363 * Draw all the vehicle list items.
1364 * @param selected_vehicle The vehicle that is to be highlighted.
1365 * @param line_height Height of a single item line.
1366 * @param r Rectangle with edge positions of the matrix widget.
1368 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1370 int left = r.left + WD_MATRIX_LEFT;
1371 int right = r.right - WD_MATRIX_RIGHT;
1372 int width = right - left;
1373 bool rtl = _current_text_dir == TD_RTL;
1375 int text_offset = max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits) + WD_FRAMERECT_RIGHT;
1376 int text_left = left + (rtl ? 0 : text_offset);
1377 int text_right = right - (rtl ? text_offset : 0);
1379 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1380 int orderlist_left = left + (rtl ? 0 : max(ScaleGUITrad(100) + text_offset, width / 2));
1381 int orderlist_right = right - (rtl ? max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1383 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1384 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1386 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1388 int y = r.top;
1389 uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)this->vehicles.size());
1390 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1391 const Vehicle *v = this->vehicles[i];
1392 StringID str;
1394 SetDParam(0, v->GetDisplayProfitThisYear());
1395 SetDParam(1, v->GetDisplayProfitLastYear());
1397 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1398 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1400 if (v->name != nullptr) {
1401 /* The vehicle got a name so we will print it */
1402 SetDParam(0, v->index);
1403 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1404 } else if (v->group_id != DEFAULT_GROUP) {
1405 /* The vehicle has no name, but is member of a group, so print group name */
1406 SetDParam(0, v->group_id);
1407 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1410 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
1412 if (v->IsChainInDepot()) {
1413 str = STR_BLUE_COMMA;
1414 } else {
1415 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1418 SetDParam(0, v->unitnumber);
1419 DrawString(left, right, y + 2, str);
1421 DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1423 y += line_height;
1428 * Window for the (old) vehicle listing.
1430 * bitmask for w->window_number
1431 * 0-7 CompanyID (owner)
1432 * 8-10 window type (use flags in vehicle_gui.h)
1433 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1434 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1436 struct VehicleListWindow : public BaseVehicleListWindow {
1437 private:
1438 /** Enumeration of planes of the button row at the bottom. */
1439 enum ButtonPlanes {
1440 BP_SHOW_BUTTONS, ///< Show the buttons.
1441 BP_HIDE_BUTTONS, ///< Show the empty panel.
1444 public:
1445 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1447 /* Set up sorting. Make the window-specific _sorting variable
1448 * point to the correct global _sorting struct so we are freed
1449 * from having conditionals during window operation */
1450 switch (this->vli.vtype) {
1451 case VEH_TRAIN: this->sorting = &_sorting.train; break;
1452 case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
1453 case VEH_SHIP: this->sorting = &_sorting.ship; break;
1454 case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
1455 default: NOT_REACHED();
1458 this->CreateNestedTree();
1460 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1462 this->vehicles.SetListing(*this->sorting);
1463 this->vehicles.ForceRebuild();
1464 this->vehicles.NeedResort();
1465 this->BuildVehicleList();
1466 this->SortVehicleList();
1468 /* Set up the window widgets */
1469 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1471 if (this->vli.type == VL_SHARED_ORDERS) {
1472 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1473 } else {
1474 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1477 this->FinishInitNested(window_number);
1478 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1481 ~VehicleListWindow()
1483 *this->sorting = this->vehicles.GetListing();
1486 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1488 switch (widget) {
1489 case WID_VL_LIST:
1490 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1492 switch (this->vli.vtype) {
1493 case VEH_TRAIN:
1494 case VEH_ROAD:
1495 size->height = 6 * resize->height;
1496 break;
1497 case VEH_SHIP:
1498 case VEH_AIRCRAFT:
1499 size->height = 4 * resize->height;
1500 break;
1501 default: NOT_REACHED();
1503 break;
1505 case WID_VL_SORT_ORDER: {
1506 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1507 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1508 d.height += padding.height;
1509 *size = maxdim(*size, d);
1510 break;
1513 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1514 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1515 d.height += padding.height;
1516 d.width += padding.width;
1517 *size = maxdim(*size, d);
1518 break;
1523 void SetStringParameters(int widget) const override
1525 switch (widget) {
1526 case WID_VL_AVAILABLE_VEHICLES:
1527 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1528 break;
1530 case WID_VL_CAPTION: {
1531 switch (this->vli.type) {
1532 case VL_SHARED_ORDERS: // Shared Orders
1533 if (this->vehicles.size() == 0) {
1534 /* We can't open this window without vehicles using this order
1535 * and we should close the window when deleting the order. */
1536 NOT_REACHED();
1538 SetDParam(0, this->vscroll->GetCount());
1539 break;
1541 case VL_STANDARD: // Company Name
1542 SetDParam(0, STR_COMPANY_NAME);
1543 SetDParam(1, this->vli.index);
1544 SetDParam(3, this->vscroll->GetCount());
1545 break;
1547 case VL_STATION_LIST: // Station/Waypoint Name
1548 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
1549 SetDParam(1, this->vli.index);
1550 SetDParam(3, this->vscroll->GetCount());
1551 break;
1553 case VL_DEPOT_LIST:
1554 SetDParam(0, STR_DEPOT_CAPTION);
1555 SetDParam(1, this->vli.vtype);
1556 SetDParam(2, this->vli.index);
1557 SetDParam(3, this->vscroll->GetCount());
1558 break;
1559 default: NOT_REACHED();
1561 break;
1566 void DrawWidget(const Rect &r, int widget) const override
1568 switch (widget) {
1569 case WID_VL_SORT_ORDER:
1570 /* draw arrow pointing up/down for ascending/descending sorting */
1571 this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1572 break;
1574 case WID_VL_LIST:
1575 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1576 break;
1580 void OnPaint() override
1582 this->BuildVehicleList();
1583 this->SortVehicleList();
1585 if (this->vehicles.size() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1586 HideDropDownMenu(this);
1589 /* Hide the widgets that we will not use in this window
1590 * Some windows contains actions only fit for the owner */
1591 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1592 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1593 if (plane_to_show != nwi->shown_plane) {
1594 nwi->SetDisplayedPlane(plane_to_show);
1595 nwi->SetDirty(this);
1597 if (this->owner == _local_company) {
1598 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1599 this->SetWidgetsDisabledState(this->vehicles.size() == 0,
1600 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1601 WID_VL_STOP_ALL,
1602 WID_VL_START_ALL,
1603 WIDGET_LIST_END);
1606 /* Set text of sort by dropdown widget. */
1607 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
1609 this->DrawWidgets();
1612 void OnClick(Point pt, int widget, int click_count) override
1614 switch (widget) {
1615 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1616 this->vehicles.ToggleSortOrder();
1617 this->SetDirty();
1618 break;
1620 case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
1621 ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1622 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1623 return;
1625 case WID_VL_LIST: { // Matrix to show vehicles
1626 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1627 if (id_v >= this->vehicles.size()) return; // click out of list bound
1629 const Vehicle *v = this->vehicles[id_v];
1630 if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
1631 break;
1634 case WID_VL_AVAILABLE_VEHICLES:
1635 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1636 break;
1638 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1639 ShowDropDownList(this, this->BuildActionDropdownList(VehicleListIdentifier::UnPack(this->window_number).type == VL_STANDARD, false), 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1640 break;
1643 case WID_VL_STOP_ALL:
1644 case WID_VL_START_ALL:
1645 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1646 break;
1650 void OnDropdownSelect(int widget, int index) override
1652 switch (widget) {
1653 case WID_VL_SORT_BY_PULLDOWN:
1654 this->vehicles.SetSortType(index);
1655 break;
1656 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1657 assert(this->vehicles.size() != 0);
1659 switch (index) {
1660 case ADI_REPLACE: // Replace window
1661 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1662 break;
1663 case ADI_SERVICE: // Send for servicing
1664 case ADI_DEPOT: // Send to Depots
1665 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
1666 break;
1668 default: NOT_REACHED();
1670 break;
1671 default: NOT_REACHED();
1673 this->SetDirty();
1676 void OnGameTick() override
1678 if (this->vehicles.NeedResort()) {
1679 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1681 DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
1682 this->SetDirty();
1686 void OnResize() override
1688 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1692 * Some data on this window has become invalid.
1693 * @param data Information about the changed data.
1694 * @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.
1696 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1698 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1699 /* Needs to be done in command-scope, so everything stays valid */
1700 this->vli.index = GB(data, 0, 20);
1701 this->window_number = this->vli.Pack();
1702 this->vehicles.ForceRebuild();
1703 return;
1706 if (data == 0) {
1707 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1708 this->vehicles.ForceRebuild();
1709 } else {
1710 this->vehicles.ForceResort();
1715 static WindowDesc _vehicle_list_other_desc(
1716 WDP_AUTO, "list_vehicles", 260, 246,
1717 WC_INVALID, WC_NONE,
1719 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1722 static WindowDesc _vehicle_list_train_desc(
1723 WDP_AUTO, "list_vehicles_train", 325, 246,
1724 WC_TRAINS_LIST, WC_NONE,
1726 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1729 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1731 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1733 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1734 if (vehicle_type == VEH_TRAIN) {
1735 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
1736 } else {
1737 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
1738 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
1742 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
1744 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
1745 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
1746 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
1749 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
1750 ShowCompanyGroup(company, vehicle_type);
1751 } else {
1752 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
1756 void ShowVehicleListWindow(const Vehicle *v)
1758 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
1761 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
1763 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
1766 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
1768 uint16 depot_airport_index;
1770 if (vehicle_type == VEH_AIRCRAFT) {
1771 depot_airport_index = GetStationIndex(depot_tile);
1772 } else {
1773 depot_airport_index = GetDepotIndex(depot_tile);
1775 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
1779 /* Unified vehicle GUI - Vehicle Details Window */
1781 assert_compile(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
1782 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
1783 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
1784 assert_compile(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
1786 /** Vehicle details widgets (other than train). */
1787 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
1788 NWidget(NWID_HORIZONTAL),
1789 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1790 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1791 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
1792 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1793 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1794 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1795 EndContainer(),
1796 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
1797 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
1798 NWidget(NWID_HORIZONTAL),
1799 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1800 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1801 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1802 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
1803 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1804 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1805 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1806 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1807 EndContainer(),
1810 /** Train details widgets. */
1811 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
1812 NWidget(NWID_HORIZONTAL),
1813 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1814 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1815 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
1816 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1817 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1818 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1819 EndContainer(),
1820 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
1821 NWidget(NWID_HORIZONTAL),
1822 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),
1823 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
1824 EndContainer(),
1825 NWidget(NWID_HORIZONTAL),
1826 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1827 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1828 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1829 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
1830 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1831 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1832 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1833 EndContainer(),
1834 NWidget(NWID_HORIZONTAL),
1835 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
1836 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1837 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
1838 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1839 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
1840 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1841 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
1842 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1843 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1844 EndContainer(),
1848 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
1849 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
1850 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
1851 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
1852 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
1854 static StringID _service_interval_dropdown[] = {
1855 STR_VEHICLE_DETAILS_DEFAULT,
1856 STR_VEHICLE_DETAILS_DAYS,
1857 STR_VEHICLE_DETAILS_PERCENT,
1858 INVALID_STRING_ID,
1861 /** Class for managing the vehicle details window. */
1862 struct VehicleDetailsWindow : Window {
1863 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
1864 Scrollbar *vscroll;
1866 /** Initialize a newly created vehicle details window */
1867 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1869 const Vehicle *v = Vehicle::Get(window_number);
1871 this->CreateNestedTree();
1872 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
1873 this->FinishInitNested(window_number);
1875 this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
1877 this->owner = v->owner;
1878 this->tab = TDW_TAB_CARGO;
1882 * Some data on this window has become invalid.
1883 * @param data Information about the changed data.
1884 * @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.
1886 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1888 if (data == VIWD_AUTOREPLACE) {
1889 /* Autoreplace replaced the vehicle.
1890 * Nothing to do for this window. */
1891 return;
1893 if (!gui_scope) return;
1894 const Vehicle *v = Vehicle::Get(this->window_number);
1895 if (v->type == VEH_ROAD) {
1896 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
1897 uint aimed_height = this->GetRoadVehDetailsHeight(v);
1898 /* If the number of articulated parts changes, the size of the window must change too. */
1899 if (aimed_height != nwid_info->current_y) {
1900 this->ReInit();
1906 * Gets the desired height for the road vehicle details panel.
1907 * @param v Road vehicle being shown.
1908 * @return Desired height in pixels.
1910 uint GetRoadVehDetailsHeight(const Vehicle *v)
1912 uint desired_height;
1913 if (v->HasArticulatedPart()) {
1914 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
1915 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
1916 /* Add space for the cargo amount for each part. */
1917 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1918 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
1920 } else {
1921 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
1923 return desired_height;
1926 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1928 switch (widget) {
1929 case WID_VD_TOP_DETAILS: {
1930 Dimension dim = { 0, 0 };
1931 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1933 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
1934 static const StringID info_strings[] = {
1935 STR_VEHICLE_INFO_MAX_SPEED,
1936 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
1937 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
1938 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
1939 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
1941 for (uint i = 0; i < lengthof(info_strings); i++) {
1942 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
1944 SetDParam(0, STR_VEHICLE_INFO_AGE);
1945 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
1946 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1947 break;
1950 case WID_VD_MIDDLE_DETAILS: {
1951 const Vehicle *v = Vehicle::Get(this->window_number);
1952 switch (v->type) {
1953 case VEH_ROAD:
1954 size->height = this->GetRoadVehDetailsHeight(v);
1955 break;
1957 case VEH_SHIP:
1958 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
1959 break;
1961 case VEH_AIRCRAFT:
1962 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
1963 break;
1965 default:
1966 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
1968 break;
1971 case WID_VD_MATRIX:
1972 resize->height = max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
1973 size->height = 4 * resize->height;
1974 break;
1976 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
1977 StringID *strs = _service_interval_dropdown;
1978 while (*strs != INVALID_STRING_ID) {
1979 *size = maxdim(*size, GetStringBoundingBox(*strs++));
1981 size->width += padding.width;
1982 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
1983 break;
1986 case WID_VD_SERVICING_INTERVAL:
1987 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
1988 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
1989 size->width = max(GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT).width, GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS).width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1990 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1991 break;
1995 /** Checks whether service interval is enabled for the vehicle. */
1996 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
1998 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
1999 switch (vehicle_type) {
2000 default: NOT_REACHED();
2001 case VEH_TRAIN: return vds->servint_trains != 0;
2002 case VEH_ROAD: return vds->servint_roadveh != 0;
2003 case VEH_SHIP: return vds->servint_ships != 0;
2004 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2009 * Draw the details for the given vehicle at the position of the Details windows
2011 * @param v current vehicle
2012 * @param left The left most coordinate to draw
2013 * @param right The right most coordinate to draw
2014 * @param y The y coordinate
2015 * @param vscroll_pos Position of scrollbar (train only)
2016 * @param vscroll_cap Number of lines currently displayed (train only)
2017 * @param det_tab Selected details tab (train only)
2019 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2021 switch (v->type) {
2022 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2023 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2024 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2025 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2026 default: NOT_REACHED();
2030 void SetStringParameters(int widget) const override
2032 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2035 void DrawWidget(const Rect &r, int widget) const override
2037 const Vehicle *v = Vehicle::Get(this->window_number);
2039 switch (widget) {
2040 case WID_VD_TOP_DETAILS: {
2041 int y = r.top + WD_FRAMERECT_TOP;
2043 /* Draw running cost */
2044 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2045 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2046 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2047 SetDParam(3, v->GetDisplayRunningCost());
2048 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2049 y += FONT_HEIGHT_NORMAL;
2051 /* Draw max speed */
2052 StringID string;
2053 if (v->type == VEH_TRAIN ||
2054 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2055 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2056 SetDParam(2, v->GetDisplayMaxSpeed());
2057 SetDParam(1, gcache->cached_power);
2058 SetDParam(0, gcache->cached_weight);
2059 SetDParam(3, gcache->cached_max_te / 1000);
2060 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2061 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2062 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2063 } else {
2064 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2066 } else {
2067 SetDParam(0, v->GetDisplayMaxSpeed());
2068 if (v->type == VEH_AIRCRAFT) {
2069 SetDParam(1, v->GetEngine()->GetAircraftTypeText());
2070 if (Aircraft::From(v)->GetRange() > 0) {
2071 SetDParam(2, Aircraft::From(v)->GetRange());
2072 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE;
2073 } else {
2074 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE;
2076 } else {
2077 string = STR_VEHICLE_INFO_MAX_SPEED;
2080 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2081 y += FONT_HEIGHT_NORMAL;
2083 /* Draw profit */
2084 SetDParam(0, v->GetDisplayProfitThisYear());
2085 SetDParam(1, v->GetDisplayProfitLastYear());
2086 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2087 y += FONT_HEIGHT_NORMAL;
2089 /* Draw breakdown & reliability */
2090 SetDParam(0, ToPercent16(v->reliability));
2091 SetDParam(1, v->breakdowns_since_last_service);
2092 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2093 break;
2096 case WID_VD_MATRIX:
2097 /* For trains only. */
2098 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);
2099 break;
2101 case WID_VD_MIDDLE_DETAILS: {
2102 /* For other vehicles, at the place of the matrix. */
2103 bool rtl = _current_text_dir == TD_RTL;
2104 uint sprite_width = GetSingleVehicleWidth(v, EIT_IN_DETAILS) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2106 uint text_left = r.left + (rtl ? 0 : sprite_width);
2107 uint text_right = r.right - (rtl ? sprite_width : 0);
2109 /* Articulated road vehicles use a complete line. */
2110 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2111 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2112 } else {
2113 uint sprite_left = rtl ? text_right : r.left;
2114 uint sprite_right = rtl ? r.right : text_left;
2116 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2118 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2119 break;
2122 case WID_VD_SERVICING_INTERVAL:
2123 /* Draw service interval text */
2124 SetDParam(0, v->GetServiceInterval());
2125 SetDParam(1, v->date_of_last_service);
2126 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2127 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2128 break;
2132 /** Repaint vehicle details window. */
2133 void OnPaint() override
2135 const Vehicle *v = Vehicle::Get(this->window_number);
2137 this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
2139 if (v->type == VEH_TRAIN) {
2140 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2141 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2144 /* Disable service-scroller when interval is set to disabled */
2145 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2146 WID_VD_INCREASE_SERVICING_INTERVAL,
2147 WID_VD_DECREASE_SERVICING_INTERVAL,
2148 WIDGET_LIST_END);
2150 StringID str = v->ServiceIntervalIsCustom() ?
2151 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2152 STR_VEHICLE_DETAILS_DEFAULT;
2153 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2155 this->DrawWidgets();
2158 void OnClick(Point pt, int widget, int click_count) override
2160 switch (widget) {
2161 case WID_VD_RENAME_VEHICLE: { // rename
2162 const Vehicle *v = Vehicle::Get(this->window_number);
2163 SetDParam(0, v->index);
2164 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2165 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2166 break;
2169 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2170 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2171 int mod = _ctrl_pressed ? 5 : 10;
2172 const Vehicle *v = Vehicle::Get(this->window_number);
2174 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2175 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2176 if (mod == v->GetServiceInterval()) return;
2178 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2179 break;
2182 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2183 const Vehicle *v = Vehicle::Get(this->window_number);
2184 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2185 break;
2188 case WID_VD_DETAILS_CARGO_CARRIED:
2189 case WID_VD_DETAILS_TRAIN_VEHICLES:
2190 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2191 case WID_VD_DETAILS_TOTAL_CARGO:
2192 this->SetWidgetsDisabledState(false,
2193 WID_VD_DETAILS_CARGO_CARRIED,
2194 WID_VD_DETAILS_TRAIN_VEHICLES,
2195 WID_VD_DETAILS_CAPACITY_OF_EACH,
2196 WID_VD_DETAILS_TOTAL_CARGO,
2197 widget,
2198 WIDGET_LIST_END);
2200 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2201 this->SetDirty();
2202 break;
2206 void OnDropdownSelect(int widget, int index) override
2208 switch (widget) {
2209 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2210 const Vehicle *v = Vehicle::Get(this->window_number);
2211 bool iscustom = index != 0;
2212 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2213 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2214 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2215 break;
2220 void OnQueryTextFinished(char *str) override
2222 if (str == nullptr) return;
2224 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);
2227 void OnResize() override
2229 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2230 if (nwi != nullptr) {
2231 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2236 /** Vehicle details window descriptor. */
2237 static WindowDesc _train_vehicle_details_desc(
2238 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2239 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2241 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2244 /** Vehicle details window descriptor for other vehicles than a train. */
2245 static WindowDesc _nontrain_vehicle_details_desc(
2246 WDP_AUTO, "view_vehicle_details", 405, 113,
2247 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2249 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2252 /** Shows the vehicle details window of the given vehicle. */
2253 static void ShowVehicleDetailsWindow(const Vehicle *v)
2255 DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
2256 DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2257 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2261 /* Unified vehicle GUI - Vehicle View Window */
2263 /** Vehicle view widgets. */
2264 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2265 NWidget(NWID_HORIZONTAL),
2266 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2267 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2268 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2269 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2270 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2271 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2272 EndContainer(),
2273 NWidget(NWID_HORIZONTAL),
2274 NWidget(WWT_PANEL, COLOUR_GREY),
2275 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2276 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
2277 EndContainer(),
2278 EndContainer(),
2279 NWidget(NWID_VERTICAL),
2280 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
2281 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2282 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2283 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2284 EndContainer(),
2285 /* For trains only, 'ignore signal' button. */
2286 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18),
2287 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2288 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2289 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2290 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18),
2291 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2292 EndContainer(),
2293 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2294 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2295 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2296 EndContainer(),
2297 EndContainer(),
2298 NWidget(NWID_HORIZONTAL),
2299 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2300 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2301 EndContainer(),
2304 /** Vehicle view window descriptor for all vehicles but trains. */
2305 static WindowDesc _vehicle_view_desc(
2306 WDP_AUTO, "view_vehicle", 250, 116,
2307 WC_VEHICLE_VIEW, WC_NONE,
2309 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2313 * Vehicle view window descriptor for trains. Only minimum_height and
2314 * default_height are different for train view.
2316 static WindowDesc _train_view_desc(
2317 WDP_AUTO, "view_vehicle_train", 250, 134,
2318 WC_VEHICLE_VIEW, WC_NONE,
2320 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2324 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2325 using them for array indexing in a number of places here. */
2326 assert_compile(VEH_TRAIN == 0);
2327 assert_compile(VEH_ROAD == 1);
2328 assert_compile(VEH_SHIP == 2);
2329 assert_compile(VEH_AIRCRAFT == 3);
2331 /** Zoom levels for vehicle views indexed by vehicle type. */
2332 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2333 ZOOM_LVL_TRAIN,
2334 ZOOM_LVL_ROADVEH,
2335 ZOOM_LVL_SHIP,
2336 ZOOM_LVL_AIRCRAFT,
2339 /* Constants for geometry of vehicle view viewport */
2340 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2341 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2342 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2344 /** Command indices for the _vehicle_command_translation_table. */
2345 enum VehicleCommandTranslation {
2346 VCT_CMD_START_STOP = 0,
2347 VCT_CMD_CLONE_VEH,
2348 VCT_CMD_TURN_AROUND,
2351 /** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
2352 static const uint32 _vehicle_command_translation_table[][4] = {
2353 { // VCT_CMD_START_STOP
2354 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
2355 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
2356 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
2357 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
2359 { // VCT_CMD_CLONE_VEH
2360 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
2361 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
2362 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
2363 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
2365 { // VCT_CMD_TURN_AROUND
2366 CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
2367 CMD_TURN_ROADVEH | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
2368 0xffffffff, // invalid for ships
2369 0xffffffff // invalid for aircraft
2374 * This is the Callback method after attempting to start/stop a vehicle
2375 * @param result the result of the start/stop command
2376 * @param tile unused
2377 * @param p1 vehicle ID
2378 * @param p2 unused
2380 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2382 if (result.Failed()) return;
2384 const Vehicle *v = Vehicle::GetIfValid(p1);
2385 if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2387 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2388 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2389 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2393 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2394 * @param v Vehicle to start/stop
2395 * @param texteffect Should a texteffect be shown?
2397 void StartStopVehicle(const Vehicle *v, bool texteffect)
2399 assert(v->IsPrimaryVehicle());
2400 DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr);
2403 /** Checks whether the vehicle may be refitted at the moment.*/
2404 static bool IsVehicleRefitable(const Vehicle *v)
2406 if (!v->IsStoppedInDepot()) return false;
2408 do {
2409 if (IsEngineRefittable(v->engine_type)) return true;
2410 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
2412 return false;
2415 /** Window manager class for viewing a vehicle. */
2416 struct VehicleViewWindow : Window {
2417 private:
2418 /** Display planes available in the vehicle view window. */
2419 enum PlaneSelections {
2420 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2421 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2423 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2424 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2426 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2427 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2431 * Display a plane in the window.
2432 * @param plane Plane to show.
2434 void SelectPlane(PlaneSelections plane)
2436 switch (plane) {
2437 case SEL_DC_GOTO_DEPOT:
2438 case SEL_DC_CLONE:
2439 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2440 break;
2442 case SEL_RT_REFIT:
2443 case SEL_RT_TURN_AROUND:
2444 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2445 break;
2447 default:
2448 NOT_REACHED();
2452 public:
2453 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2455 this->flags |= WF_DISABLE_VP_SCROLL;
2456 this->CreateNestedTree();
2458 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2459 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2460 SPR_SEND_TRAIN_TODEPOT,
2461 SPR_SEND_ROADVEH_TODEPOT,
2462 SPR_SEND_SHIP_TODEPOT,
2463 SPR_SEND_AIRCRAFT_TODEPOT,
2465 const Vehicle *v = Vehicle::Get(window_number);
2466 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2468 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2469 static const SpriteID vehicle_view_clone_sprites[] = {
2470 SPR_CLONE_TRAIN,
2471 SPR_CLONE_ROADVEH,
2472 SPR_CLONE_SHIP,
2473 SPR_CLONE_AIRCRAFT,
2475 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2477 switch (v->type) {
2478 case VEH_TRAIN:
2479 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2480 break;
2482 case VEH_ROAD:
2483 break;
2485 case VEH_SHIP:
2486 case VEH_AIRCRAFT:
2487 this->SelectPlane(SEL_RT_REFIT);
2488 break;
2490 default: NOT_REACHED();
2492 this->FinishInitNested(window_number);
2493 this->owner = v->owner;
2494 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2496 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
2497 this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
2498 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2499 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2500 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2501 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2502 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2504 this->UpdateButtonStatus();
2507 ~VehicleViewWindow()
2509 DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2510 DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2511 DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2512 DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2515 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2517 const Vehicle *v = Vehicle::Get(this->window_number);
2518 switch (widget) {
2519 case WID_VV_START_STOP:
2520 size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
2521 break;
2523 case WID_VV_FORCE_PROCEED:
2524 if (v->type != VEH_TRAIN) {
2525 size->height = 0;
2526 size->width = 0;
2528 break;
2530 case WID_VV_VIEWPORT:
2531 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2532 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2533 break;
2537 void OnPaint() override
2539 const Vehicle *v = Vehicle::Get(this->window_number);
2540 bool is_localcompany = v->owner == _local_company;
2541 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2543 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2544 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2545 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2547 if (v->type == VEH_TRAIN) {
2548 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2549 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2550 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2553 this->DrawWidgets();
2556 void SetStringParameters(int widget) const override
2558 if (widget != WID_VV_CAPTION) return;
2560 const Vehicle *v = Vehicle::Get(this->window_number);
2561 SetDParam(0, v->index);
2564 void DrawWidget(const Rect &r, int widget) const override
2566 if (widget != WID_VV_START_STOP) return;
2568 const Vehicle *v = Vehicle::Get(this->window_number);
2569 StringID str;
2570 if (v->vehstatus & VS_CRASHED) {
2571 str = STR_VEHICLE_STATUS_CRASHED;
2572 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2573 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2574 } else if (v->vehstatus & VS_STOPPED) {
2575 if (v->type == VEH_TRAIN) {
2576 if (v->cur_speed == 0) {
2577 if (Train::From(v)->gcache.cached_power == 0) {
2578 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2579 } else {
2580 str = STR_VEHICLE_STATUS_STOPPED;
2582 } else {
2583 SetDParam(0, v->GetDisplaySpeed());
2584 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2586 } else { // no train
2587 str = STR_VEHICLE_STATUS_STOPPED;
2589 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2590 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2591 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2592 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2593 } else { // vehicle is in a "normal" state, show current order
2594 switch (v->current_order.GetType()) {
2595 case OT_GOTO_STATION: {
2596 SetDParam(0, v->current_order.GetDestination());
2597 SetDParam(1, v->GetDisplaySpeed());
2598 str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2599 break;
2602 case OT_GOTO_DEPOT: {
2603 SetDParam(0, v->type);
2604 SetDParam(1, v->current_order.GetDestination());
2605 SetDParam(2, v->GetDisplaySpeed());
2606 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2607 /* This case *only* happens when multiple nearest depot orders
2608 * follow each other (including an order list only one order: a
2609 * nearest depot order) and there are no reachable depots.
2610 * It is primarily to guard for the case that there is no
2611 * depot with index 0, which would be used as fallback for
2612 * evaluating the string in the status bar. */
2613 str = STR_EMPTY;
2614 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2615 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2616 } else {
2617 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2619 break;
2622 case OT_LOADING:
2623 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2624 break;
2626 case OT_GOTO_WAYPOINT: {
2627 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2628 SetDParam(0, v->current_order.GetDestination());
2629 str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2630 SetDParam(1, v->GetDisplaySpeed());
2631 break;
2634 case OT_LEAVESTATION:
2635 if (v->type != VEH_AIRCRAFT) {
2636 str = STR_VEHICLE_STATUS_LEAVING;
2637 break;
2639 FALLTHROUGH;
2640 default:
2641 if (v->GetNumManualOrders() == 0) {
2642 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2643 SetDParam(0, v->GetDisplaySpeed());
2644 } else {
2645 str = STR_EMPTY;
2647 break;
2651 /* Draw the flag plus orders. */
2652 bool rtl = (_current_text_dir == TD_RTL);
2653 uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2654 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2655 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2656 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2657 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
2658 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2659 DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
2660 DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
2663 void OnClick(Point pt, int widget, int click_count) override
2665 const Vehicle *v = Vehicle::Get(this->window_number);
2667 switch (widget) {
2668 case WID_VV_START_STOP: // start stop
2669 if (_ctrl_pressed) {
2670 /* Scroll to current order destination */
2671 TileIndex tile = v->current_order.GetLocation(v);
2672 if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
2673 } else {
2674 /* Start/Stop */
2675 StartStopVehicle(v, false);
2677 break;
2678 case WID_VV_CENTER_MAIN_VIEW: {// center main view
2679 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2680 /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
2681 if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2682 mainwindow->viewport->follow_vehicle = v->index;
2683 } else {
2684 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2686 break;
2689 case WID_VV_GOTO_DEPOT: // goto hangar
2690 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
2691 break;
2692 case WID_VV_REFIT: // refit
2693 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
2694 break;
2695 case WID_VV_SHOW_ORDERS: // show orders
2696 if (_ctrl_pressed) {
2697 ShowTimetableWindow(v);
2698 } else {
2699 ShowOrdersWindow(v);
2701 break;
2702 case WID_VV_SHOW_DETAILS: // show details
2703 ShowVehicleDetailsWindow(v);
2704 break;
2705 case WID_VV_CLONE: // clone vehicle
2706 /* Suppress the vehicle GUI when share-cloning.
2707 * There is no point to it except for starting the vehicle.
2708 * For starting the vehicle the player has to open the depot GUI, which is
2709 * most likely already open, but is also visible in the vehicle viewport. */
2710 DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
2711 _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
2712 _ctrl_pressed ? nullptr : CcCloneVehicle);
2713 break;
2714 case WID_VV_TURN_AROUND: // turn around
2715 assert(v->IsGroundVehicle());
2716 DoCommandP(v->tile, v->index, 0,
2717 _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
2718 break;
2719 case WID_VV_FORCE_PROCEED: // force proceed
2720 assert(v->type == VEH_TRAIN);
2721 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
2722 break;
2726 void OnResize() override
2728 if (this->viewport != nullptr) {
2729 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
2730 nvp->UpdateViewportCoordinates(this);
2734 void UpdateButtonStatus()
2736 const Vehicle *v = Vehicle::Get(this->window_number);
2737 bool veh_stopped = v->IsStoppedInDepot();
2739 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
2740 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
2742 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
2743 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
2744 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
2745 this->SelectPlane(plane);
2746 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
2748 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
2749 if (v->IsGroundVehicle()) {
2750 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
2751 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
2752 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
2753 this->SelectPlane(plane);
2754 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
2760 * Some data on this window has become invalid.
2761 * @param data Information about the changed data.
2762 * @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.
2764 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2766 if (data == VIWD_AUTOREPLACE) {
2767 /* Autoreplace replaced the vehicle.
2768 * Nothing to do for this window. */
2769 return;
2772 this->UpdateButtonStatus();
2775 bool IsNewGRFInspectable() const override
2777 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2780 void ShowNewGRFInspectWindow() const override
2782 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2787 /** Shows the vehicle view window of the given vehicle. */
2788 void ShowVehicleViewWindow(const Vehicle *v)
2790 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
2794 * Dispatch a "vehicle selected" event if any window waits for it.
2795 * @param v selected vehicle;
2796 * @return did any window accept vehicle selection?
2798 bool VehicleClicked(const Vehicle *v)
2800 assert(v != nullptr);
2801 if (!(_thd.place_mode & HT_VEHICLE)) return false;
2803 v = v->First();
2804 if (!v->IsPrimaryVehicle()) return false;
2806 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
2809 void StopGlobalFollowVehicle(const Vehicle *v)
2811 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2812 if (w != nullptr && w->viewport->follow_vehicle == v->index) {
2813 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
2814 w->viewport->follow_vehicle = INVALID_VEHICLE;
2820 * This is the Callback method after the construction attempt of a primary vehicle
2821 * @param result indicates completion (or not) of the operation
2822 * @param tile unused
2823 * @param p1 unused
2824 * @param p2 unused
2826 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2828 if (result.Failed()) return;
2830 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
2831 ShowVehicleViewWindow(v);
2835 * Get the width of a vehicle (part) in pixels.
2836 * @param v Vehicle to get the width for.
2837 * @return Width of the vehicle.
2839 int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
2841 switch (v->type) {
2842 case VEH_TRAIN:
2843 return Train::From(v)->GetDisplayImageWidth();
2845 case VEH_ROAD:
2846 return RoadVehicle::From(v)->GetDisplayImageWidth();
2848 default:
2849 bool rtl = _current_text_dir == TD_RTL;
2850 VehicleSpriteSeq seq;
2851 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
2852 Rect rec;
2853 seq.GetBounds(&rec);
2854 return UnScaleGUI(rec.right - rec.left + 1);
2859 * Get the width of a vehicle (including all parts of the consist) in pixels.
2860 * @param v Vehicle to get the width for.
2861 * @return Width of the vehicle.
2863 int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
2865 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
2866 int vehicle_width = 0;
2867 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2868 vehicle_width += GetSingleVehicleWidth(u, image_type);
2870 return vehicle_width;
2871 } else {
2872 return GetSingleVehicleWidth(v, image_type);
2877 * Set the mouse cursor to look like a vehicle.
2878 * @param v Vehicle
2879 * @param image_type Type of vehicle image to use.
2881 void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
2883 bool rtl = _current_text_dir == TD_RTL;
2885 _cursor.sprite_count = 0;
2886 int total_width = 0;
2887 for (; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
2888 if (total_width >= 2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH) break;
2890 PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
2891 VehicleSpriteSeq seq;
2892 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
2894 if (_cursor.sprite_count + seq.count > lengthof(_cursor.sprite_seq)) break;
2896 for (uint i = 0; i < seq.count; ++i) {
2897 PaletteID pal2 = (v->vehstatus & VS_CRASHED) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
2898 _cursor.sprite_seq[_cursor.sprite_count].sprite = seq.seq[i].sprite;
2899 _cursor.sprite_seq[_cursor.sprite_count].pal = pal2;
2900 _cursor.sprite_pos[_cursor.sprite_count].x = rtl ? -total_width : total_width;
2901 _cursor.sprite_pos[_cursor.sprite_count].y = 0;
2902 _cursor.sprite_count++;
2905 total_width += GetSingleVehicleWidth(v, image_type);
2908 int offs = ((int)VEHICLEINFO_FULL_VEHICLE_WIDTH - total_width) / 2;
2909 if (rtl) offs = -offs;
2910 for (uint i = 0; i < _cursor.sprite_count; ++i) {
2911 _cursor.sprite_pos[i].x += offs;
2914 UpdateCursorSize();