Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / vehicle_gui.cpp
blobd596ee2df0b6041eb447c61b29104a3727c41e9e
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 "tbtr_template_gui_main.h"
41 #include "triphistory.h"
42 #include "zoom_func.h"
43 #include "tracerestrict.h"
45 #include <vector>
47 #include "safeguards.h"
50 Sorting _sorting;
52 static GUIVehicleList::SortFunction VehicleNumberSorter;
53 static GUIVehicleList::SortFunction VehicleNameSorter;
54 static GUIVehicleList::SortFunction VehicleAgeSorter;
55 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
56 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
57 static GUIVehicleList::SortFunction VehicleProfitLifetimeSorter;
58 static GUIVehicleList::SortFunction VehicleCargoSorter;
59 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
60 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
61 static GUIVehicleList::SortFunction VehicleModelSorter;
62 static GUIVehicleList::SortFunction VehicleValueSorter;
63 static GUIVehicleList::SortFunction VehicleLengthSorter;
64 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
65 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
67 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
68 &VehicleNumberSorter,
69 &VehicleNameSorter,
70 &VehicleAgeSorter,
71 &VehicleProfitThisYearSorter,
72 &VehicleProfitLastYearSorter,
73 &VehicleProfitLifetimeSorter,
74 &VehicleCargoSorter,
75 &VehicleReliabilitySorter,
76 &VehicleMaxSpeedSorter,
77 &VehicleModelSorter,
78 &VehicleValueSorter,
79 &VehicleLengthSorter,
80 &VehicleTimeToLiveSorter,
81 &VehicleTimetableDelaySorter,
84 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
85 STR_SORT_BY_NUMBER,
86 STR_SORT_BY_NAME,
87 STR_SORT_BY_AGE,
88 STR_SORT_BY_PROFIT_THIS_YEAR,
89 STR_SORT_BY_PROFIT_LAST_YEAR,
90 STR_SORT_BY_PROFIT_LIFETIME,
91 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
92 STR_SORT_BY_RELIABILITY,
93 STR_SORT_BY_MAX_SPEED,
94 STR_SORT_BY_MODEL,
95 STR_SORT_BY_VALUE,
96 STR_SORT_BY_LENGTH,
97 STR_SORT_BY_LIFE_TIME,
98 STR_SORT_BY_TIMETABLE_DELAY,
99 INVALID_STRING_ID
102 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
103 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
104 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
105 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
106 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
110 * Get the number of digits the biggest unit number of a set of vehicles has.
111 * @param vehicles The list of vehicles.
112 * @return The number of digits to allocate space for.
114 uint GetUnitNumberDigits(VehicleList &vehicles)
116 uint unitnumber = 0;
117 for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) {
118 unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
121 if (unitnumber >= 10000) return 5;
122 if (unitnumber >= 1000) return 4;
123 if (unitnumber >= 100) return 3;
126 * When the smallest unit number is less than 10, it is
127 * quite likely that it will expand to become more than
128 * 10 quite soon.
130 return 2;
133 void BaseVehicleListWindow::BuildVehicleList()
135 if (!this->vehicles.NeedRebuild()) return;
137 DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
139 GenerateVehicleSortList(&this->vehicles, this->vli);
141 this->FilterVehicleList();
143 this->unitnumber_digits = GetUnitNumberDigits(this->vehicles);
145 this->vehicles.RebuildDone();
146 this->vscroll->SetCount(this->vehicles.Length());
149 /** Cargo filter functions */
150 static bool CDECL CargoFilter(const Vehicle * const *vid, const CargoID cid)
152 if (cid == BaseVehicleListWindow::CF_ANY) {
153 return true;
154 } else if (cid == BaseVehicleListWindow::CF_NONE) {
155 for (const Vehicle *w = (*vid); w != nullptr; w = w->Next()) {
156 if (w->cargo_cap > 0) {
157 return false;
160 return true;
161 } else if (cid == BaseVehicleListWindow::CF_FREIGHT) {
162 bool have_capacity = false;
163 for (const Vehicle *w = (*vid); w != nullptr; w = w->Next()) {
164 if (w->cargo_cap) {
165 if (IsCargoInClass(w->cargo_type, CC_PASSENGERS)) {
166 return false;
167 } else {
168 have_capacity = true;
172 return have_capacity;
173 } else {
174 for (const Vehicle *w = (*vid); w != nullptr; w = w->Next()) {
175 if (w->cargo_cap > 0 && w->cargo_type == cid) {
176 return true;
179 return false;
183 static GUIVehicleList::FilterFunction * const _filter_funcs[] = {
184 &CargoFilter,
187 /** Set cargo filter list item index. */
188 void BaseVehicleListWindow::SetCargoFilterIndex(int index)
190 if (this->cargo_filter_criteria != index) {
191 this->cargo_filter_criteria = index;
192 /* deactivate filter if criteria is 'Show All', activate it otherwise */
193 this->vehicles.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
194 this->vehicles.SetFilterType(0);
195 this->vehicles.ForceRebuild();
199 /** Populate the filter list and set the cargo filter criteria. */
200 void BaseVehicleListWindow::SetCargoFilterArray()
202 uint filter_items = 0;
204 /* Add item for disabling filtering. */
205 this->cargo_filter[filter_items] = CF_ANY;
206 this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
207 this->cargo_filter_criteria = filter_items;
208 filter_items++;
210 /* Add item for freight (i.e. vehicles with cargo capacity and with no passenger capacity) */
211 this->cargo_filter[filter_items] = CF_FREIGHT;
212 this->cargo_filter_texts[filter_items] = STR_CARGO_TYPE_FREIGHT;
213 filter_items++;
215 /* Add item for vehicles not carrying anything, e.g. train engines.
216 * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */
217 this->cargo_filter[filter_items] = CF_NONE;
218 this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE;
219 filter_items++;
221 /* Collect available cargo types for filtering. */
222 const CargoSpec *cs;
223 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
224 this->cargo_filter[filter_items] = cs->Index();
225 this->cargo_filter_texts[filter_items] = cs->name;
226 filter_items++;
229 /* Terminate the filter list. */
230 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
232 this->vehicles.SetFilterFuncs(_filter_funcs);
233 this->vehicles.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
236 /** Filter the engine list against the currently selected cargo filter */
237 void BaseVehicleListWindow::FilterVehicleList()
239 this->vehicles.Filter(this->cargo_filter[this->cargo_filter_criteria]);
240 if (0 == this->vehicles.Length()) {
241 // no vehicle passed through the filter, invalidate the previously selected vehicle
242 this->vehicle_sel = INVALID_VEHICLE;
243 } else if (this->vehicle_sel != INVALID_VEHICLE && !this->vehicles.Contains(Vehicle::Get(this->vehicle_sel))) { // previously selected engine didn't pass the filter, remove selection
244 this->vehicle_sel = INVALID_VEHICLE;
248 void BaseVehicleListWindow::OnInit()
250 this->SetCargoFilterArray();
254 * Compute the size for the Action dropdown.
255 * @param show_autoreplace If true include the autoreplace item.
256 * @param show_group If true include group-related stuff.
257 * @param show_template_replace If true include the template replace item.
258 * @return Required size.
260 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_template_replace)
262 Dimension d = {0, 0};
264 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
265 if (show_autoreplace && show_template_replace) {
266 d = maxdim(d, GetStringBoundingBox(STR_TMPL_TEMPLATE_REPLACEMENT));
268 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
269 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
271 if (show_group) {
272 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
273 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
276 return d;
280 * Whether the Action dropdown window should be shown/available.
281 * @return Whether available
283 bool BaseVehicleListWindow::ShouldShowActionDropdownList() const
285 return (this->vehicles.Length() != 0) || (this->vli.vtype == VEH_TRAIN);
289 * Display the Action dropdown window.
290 * @param show_autoreplace If true include the autoreplace item.
291 * @param show_group If true include group-related stuff.
292 * @param show_template_replace If true include template replace item.
293 * @param show_sell If true include sell all item.
294 * @return Itemlist for dropdown
296 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_template_replace, bool show_sell)
298 DropDownList *list = new DropDownList();
299 bool disable = this->vehicles.Length() == 0;
301 *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_SET_ALL_ON_TIME, ADI_SET_ALL_ON_TIME, disable);
303 if (show_autoreplace) *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, disable);
304 if (show_autoreplace && show_template_replace) {
305 *list->Append() = new DropDownListStringItem(STR_TMPL_TEMPLATE_REPLACEMENT, ADI_TEMPLATE_REPLACE, disable);
308 *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, disable);
309 *list->Append() = new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, disable);
311 if (show_group) {
312 *list->Append() = new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, disable);
313 *list->Append() = new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, disable);
316 if (show_sell) {
317 *list->Append() = new DropDownListStringItem(STR_GROUP_SELL_ALL_VEHICLES, ADI_SELL_ALL, disable);
320 if (this->vli.vtype == VEH_TRAIN) {
321 *list->Append() = new DropDownListStringItem(STR_TRACE_RESTRICT_SLOT_MANAGE, ADI_TRACERESTRICT_SLOT_MGMT, false);
324 return list;
327 /* cached values for VehicleNameSorter to spare many GetString() calls */
328 static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
330 void BaseVehicleListWindow::SortVehicleList()
332 if (this->vehicles.Sort()) return;
334 /* invalidate cached values for name sorter - vehicle names could change */
335 _last_vehicle[0] = _last_vehicle[1] = nullptr;
338 void DepotSortList(VehicleList *list)
340 if (list->Length() < 2) return;
341 QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
344 /** draw the vehicle profit button in the vehicle list window. */
345 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
347 SpriteID spr;
349 /* draw profit-based coloured icons */
350 if (v->age <= VEHICLE_PROFIT_MIN_AGE) {
351 spr = SPR_PROFIT_NA;
352 } else if (v->GetDisplayProfitLastYear() < 0) {
353 spr = SPR_PROFIT_NEGATIVE;
354 } else if (v->GetDisplayProfitLastYear() < VEHICLE_PROFIT_THRESHOLD) {
355 spr = SPR_PROFIT_SOME;
356 } else {
357 spr = SPR_PROFIT_LOT;
359 DrawSprite(spr, PAL_NONE, x, y);
362 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
363 static const uint MAX_REFIT_CYCLE = 256;
366 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
367 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
368 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
369 * @param v_from the vehicle to match the subtype from
370 * @param v_for the vehicle to get the subtype for
371 * @param dest_cargo_type Destination cargo type.
372 * @return the best sub type
374 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
376 v_from = v_from->GetFirstEnginePart();
377 v_for = v_for->GetFirstEnginePart();
379 /* Create a list of subtypes used by the various parts of v_for */
380 static SmallVector<StringID, 4> subtypes;
381 subtypes.Clear();
382 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
383 const Engine *e_from = v_from->GetEngine();
384 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
385 subtypes.Include(GetCargoSubtypeText(v_from));
388 byte ret_refit_cyc = 0;
389 bool success = false;
390 if (subtypes.Length() > 0) {
391 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
392 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
393 const Engine *e = v->GetEngine();
394 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
395 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
397 CargoID old_cargo_type = v->cargo_type;
398 byte old_cargo_subtype = v->cargo_subtype;
400 /* Set the 'destination' cargo */
401 v->cargo_type = dest_cargo_type;
403 /* Cycle through the refits */
404 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
405 v->cargo_subtype = refit_cyc;
407 /* Make sure we don't pick up anything cached. */
408 v->First()->InvalidateNewGRFCache();
409 v->InvalidateNewGRFCache();
411 StringID subtype = GetCargoSubtypeText(v);
412 if (subtype == STR_EMPTY) break;
414 if (!subtypes.Contains(subtype)) continue;
416 /* We found something matching. */
417 ret_refit_cyc = refit_cyc;
418 success = true;
419 break;
422 /* Reset the vehicle's cargo type */
423 v->cargo_type = old_cargo_type;
424 v->cargo_subtype = old_cargo_subtype;
426 /* Make sure we don't taint the vehicle. */
427 v->First()->InvalidateNewGRFCache();
428 v->InvalidateNewGRFCache();
430 if (success) break;
434 return ret_refit_cyc;
437 /** Option to refit a vehicle chain */
438 struct RefitOption {
439 CargoID cargo; ///< Cargo to refit to
440 byte subtype; ///< Subcargo to use
441 StringID string; ///< GRF-local String to display for the cargo
444 * Inequality operator for #RefitOption.
445 * @param other Compare to this #RefitOption.
446 * @return True if both #RefitOption are different.
448 inline bool operator != (const RefitOption &other) const
450 return other.cargo != this->cargo || other.string != this->string;
454 * Equality operator for #RefitOption.
455 * @param other Compare to this #RefitOption.
456 * @return True if both #RefitOption are equal.
458 inline bool operator == (const RefitOption &other) const
460 return other.cargo == this->cargo && other.string == this->string;
464 typedef SmallVector<RefitOption, 32> SubtypeList; ///< List of refit subtypes associated to a cargo.
467 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
468 * @param list List of subtype options for each (sorted) cargo.
469 * @param sel Selected refit cargo-type in the window
470 * @param pos Position of the selected item in caller widow
471 * @param rows Number of rows(capacity) in caller window
472 * @param delta Step height in caller window
473 * @param r Rectangle of the matrix widget.
475 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
477 uint y = r.top + WD_MATRIX_TOP;
478 uint current = 0;
480 bool rtl = _current_text_dir == TD_RTL;
481 uint iconwidth = max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
482 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
483 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
485 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
486 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
487 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
489 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
490 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
492 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
493 for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
494 for (uint j = 0; current < pos + rows && j < list[i].Length(); j++) {
495 const RefitOption &refit = list[i][j];
497 /* Hide subtypes if sel[0] does not match */
498 if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
500 /* Refit options with a position smaller than pos don't have to be drawn. */
501 if (current < pos) {
502 current++;
503 continue;
506 if (list[i].Length() > 1) {
507 if (refit.subtype != 0xFF) {
508 /* Draw tree lines */
509 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
510 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].Length() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
511 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
512 } else {
513 /* Draw expand/collapse icon */
514 DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
518 TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
519 /* Get the cargo name. */
520 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
521 SetDParam(1, refit.string);
522 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
524 y += delta;
525 current++;
530 /** Refit cargo window. */
531 struct RefitWindow : public Window {
532 int sel[2]; ///< Index in refit options, sel[0] == -1 if nothing is selected.
533 RefitOption *cargo; ///< Refit option selected by #sel.
534 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
535 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
536 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
537 Scrollbar *vscroll; ///< The main scrollbar.
538 Scrollbar *hscroll; ///< Only used for long vehicles.
539 int vehicle_width; ///< Width of the vehicle being drawn.
540 int sprite_left; ///< Left position of the vehicle sprite.
541 int sprite_right; ///< Right position of the vehicle sprite.
542 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
543 int click_x; ///< Position of the first click while dragging.
544 VehicleID selected_vehicle; ///< First vehicle in the current selection.
545 uint8 num_vehicles; ///< Number of selected vehicles.
546 bool auto_refit; ///< Select cargo for auto-refitting.
547 bool is_virtual_train; ///< TemplateReplacement, whether the selected vehicle is virtual
550 * Collects all (cargo, subcargo) refit options of a vehicle chain.
552 void BuildRefitList()
554 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
555 Vehicle *v = Vehicle::Get(this->window_number);
557 /* Check only the selected vehicles. */
558 VehicleSet vehicles_to_refit;
559 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
561 do {
562 if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
563 const Engine *e = v->GetEngine();
564 uint32 cmask = e->info.refit_mask;
565 byte callback_mask = e->info.callback_mask;
567 /* Skip this engine if it does not carry anything */
568 if (!e->CanCarryCargo()) continue;
569 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
570 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
572 /* Loop through all cargoes in the refit mask */
573 int current_index = 0;
574 const CargoSpec *cs;
575 FOR_ALL_SORTED_CARGOSPECS(cs) {
576 CargoID cid = cs->Index();
577 /* Skip cargo type if it's not listed */
578 if (!HasBit(cmask, cid)) {
579 current_index++;
580 continue;
583 bool first_vehicle = this->list[current_index].Length() == 0;
584 if (first_vehicle) {
585 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
586 RefitOption *option = this->list[current_index].Append();
587 option->cargo = cid;
588 option->subtype = 0xFF;
589 option->string = STR_EMPTY;
592 /* Check the vehicle's callback mask for cargo suffixes.
593 * This is not supported for ordered refits, since subtypes only have a meaning
594 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
595 * autoreplace, autorenew, clone, order restoration, ... */
596 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
597 /* Make a note of the original cargo type. It has to be
598 * changed to test the cargo & subtype... */
599 CargoID temp_cargo = v->cargo_type;
600 byte temp_subtype = v->cargo_subtype;
602 v->cargo_type = cid;
604 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
605 v->cargo_subtype = refit_cyc;
607 /* Make sure we don't pick up anything cached. */
608 v->First()->InvalidateNewGRFCache();
609 v->InvalidateNewGRFCache();
611 StringID subtype = GetCargoSubtypeText(v);
613 if (first_vehicle) {
614 /* Append new subtype (don't add duplicates though) */
615 if (subtype == STR_EMPTY) break;
617 RefitOption option;
618 option.cargo = cid;
619 option.subtype = refit_cyc;
620 option.string = subtype;
621 this->list[current_index].Include(option);
622 } else {
623 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
624 if (subtype == STR_EMPTY) {
625 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
626 SubtypeList &l = this->list[current_index];
627 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
628 for (uint i = 1; i < l.Length(); i++) {
629 if (l[i].subtype >= refit_cyc) {
630 l.Resize(i);
631 break;
634 break;
635 } else {
636 /* Check whether the subtype matches with the subtype of earlier vehicles. */
637 uint pos = 1;
638 SubtypeList &l = this->list[current_index];
639 while (pos < l.Length() && l[pos].subtype != refit_cyc) pos++;
640 if (pos < l.Length() && l[pos].string != subtype) {
641 /* String mismatch, remove item keeping the order */
642 l.ErasePreservingOrder(pos);
648 /* Reset the vehicle's cargo type */
649 v->cargo_type = temp_cargo;
650 v->cargo_subtype = temp_subtype;
652 /* And make sure we haven't tainted the cache */
653 v->First()->InvalidateNewGRFCache();
654 v->InvalidateNewGRFCache();
656 current_index++;
658 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
662 * Refresh scrollbar after selection changed
664 void RefreshScrollbar()
666 uint scroll_row = 0;
667 uint row = 0;
669 for (uint i = 0; i < NUM_CARGO; i++) {
670 for (uint j = 0; j < this->list[i].Length(); j++) {
671 const RefitOption &refit = this->list[i][j];
673 /* Hide subtypes if sel[0] does not match */
674 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
676 if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
678 row++;
682 this->vscroll->SetCount(row);
683 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
687 * Select a row.
688 * @param click_row Clicked row
690 void SetSelection(uint click_row)
692 uint row = 0;
694 for (uint i = 0; i < NUM_CARGO; i++) {
695 for (uint j = 0; j < this->list[i].Length(); j++) {
696 const RefitOption &refit = this->list[i][j];
698 /* Hide subtypes if sel[0] does not match */
699 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
701 if (row == click_row) {
702 this->sel[0] = i;
703 this->sel[1] = j;
704 return;
707 row++;
711 this->sel[0] = -1;
712 this->sel[1] = 0;
716 * Gets the #RefitOption placed in the selected index.
717 * @return Pointer to the #RefitOption currently in use.
719 RefitOption *GetRefitOption()
721 if (this->sel[0] < 0) return nullptr;
723 SubtypeList &l = this->list[this->sel[0]];
724 if ((uint)this->sel[1] >= l.Length()) return nullptr;
726 return &l[this->sel[1]];
729 RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit, bool is_virtual) : Window(desc)
731 this->sel[0] = -1;
732 this->sel[1] = 0;
733 this->auto_refit = auto_refit;
734 this->is_virtual_train = is_virtual;
735 this->order = order;
736 this->CreateNestedTree();
738 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
739 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
740 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
741 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
742 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
743 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
744 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
745 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
746 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
748 this->FinishInitNested(v->index);
749 this->owner = v->owner;
751 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
754 ~RefitWindow()
756 if (this->window_number != INVALID_VEHICLE) {
757 if (!FocusWindowById(WC_VEHICLE_VIEW, this->window_number)) {
758 if (this->window_number != INVALID_VEHICLE) {
759 const Vehicle *v = Vehicle::Get(this->window_number);
760 MarkAllRoutePathsDirty(v);
761 MarkAllRouteStepsDirty(v);
767 virtual void OnFocus(Window *previously_focused_window)
769 if (HasFocusedVehicleChanged(this->window_number, previously_focused_window)) {
770 if (this->window_number != INVALID_VEHICLE) {
771 const Vehicle *v = Vehicle::Get(this->window_number);
772 MarkAllRoutePathsDirty(v);
773 MarkAllRouteStepsDirty(v);
778 virtual void OnFocusLost(Window *newly_focused_window)
780 if (HasFocusedVehicleChanged(this->window_number, newly_focused_window)) {
781 if (this->window_number != INVALID_VEHICLE) {
782 const Vehicle *v = Vehicle::Get(this->window_number);
783 MarkAllRoutePathsDirty(v);
784 MarkAllRouteStepsDirty(v);
789 virtual void OnInit()
791 if (this->cargo != nullptr) {
792 /* Store the RefitOption currently in use. */
793 RefitOption current_refit_option = *(this->cargo);
795 /* Rebuild the refit list */
796 this->BuildRefitList();
797 this->sel[0] = -1;
798 this->sel[1] = 0;
799 this->cargo = nullptr;
800 for (uint i = 0; this->cargo == nullptr && i < NUM_CARGO; i++) {
801 for (uint j = 0; j < list[i].Length(); j++) {
802 if (list[i][j] == current_refit_option) {
803 this->sel[0] = i;
804 this->sel[1] = j;
805 this->cargo = &list[i][j];
806 break;
811 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
812 this->RefreshScrollbar();
813 } else {
814 /* Rebuild the refit list */
815 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
819 virtual void OnPaint()
821 /* Determine amount of items for scroller. */
822 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
824 /* Calculate sprite position. */
825 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
826 int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
827 this->sprite_left = vehicle_panel_display->pos_x;
828 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
829 if (_current_text_dir == TD_RTL) {
830 this->sprite_right -= sprite_width;
831 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
832 } else {
833 this->sprite_left += sprite_width;
834 this->vehicle_margin = sprite_left;
837 this->DrawWidgets();
840 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
842 switch (widget) {
843 case WID_VR_MATRIX:
844 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
845 size->height = resize->height * 8;
846 break;
848 case WID_VR_VEHICLE_PANEL_DISPLAY:
849 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
850 break;
852 case WID_VR_INFO:
853 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
854 break;
858 virtual void SetStringParameters(int widget) const
860 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
864 * Gets the #StringID to use for displaying capacity.
865 * @param Cargo and cargo subtype to check for capacity.
866 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
867 * @post String parameters have been set.
869 StringID GetCapacityString(RefitOption *option) const
871 assert(_current_company == _local_company);
872 Vehicle *v = Vehicle::Get(this->window_number);
873 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
874 this->num_vehicles << 16, DC_QUERY_COST, GetCmdRefitVeh(v->type));
876 if (cost.Failed()) return INVALID_STRING_ID;
878 SetDParam(0, option->cargo);
879 SetDParam(1, _returned_refit_capacity);
881 Money money = cost.GetCost();
882 if (_returned_mail_refit_capacity > 0) {
883 SetDParam(2, CT_MAIL);
884 SetDParam(3, _returned_mail_refit_capacity);
885 if (this->order != INVALID_VEH_ORDER_ID) {
886 /* No predictable cost */
887 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
888 } else if (money <= 0) {
889 SetDParam(4, -money);
890 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
891 } else {
892 SetDParam(4, money);
893 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
895 } else {
896 if (this->order != INVALID_VEH_ORDER_ID) {
897 /* No predictable cost */
898 SetDParam(2, STR_EMPTY);
899 return STR_PURCHASE_INFO_CAPACITY;
900 } else if (money <= 0) {
901 SetDParam(2, -money);
902 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
903 } else {
904 SetDParam(2, money);
905 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
910 virtual void DrawWidget(const Rect &r, int widget) const
912 switch (widget) {
913 case WID_VR_VEHICLE_PANEL_DISPLAY: {
914 Vehicle *v = Vehicle::Get(this->window_number);
915 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
916 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
918 /* Highlight selected vehicles. */
919 if (this->order != INVALID_VEH_ORDER_ID) break;
920 int x = 0;
921 switch (v->type) {
922 case VEH_TRAIN: {
923 VehicleSet vehicles_to_refit;
924 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
926 int left = INT32_MIN;
927 int width = 0;
929 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
930 /* Start checking. */
931 if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
932 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
933 width = 0;
936 /* Draw a selection. */
937 if ((!vehicles_to_refit.Contains(u->index) || u->Next() == nullptr) && left != INT32_MIN) {
938 if (u->Next() == nullptr && vehicles_to_refit.Contains(u->index)) {
939 int current_width = u->GetDisplayImageWidth();
940 width += current_width;
941 x += current_width;
944 int right = Clamp(left + width, 0, r.right);
945 left = max(0, left);
947 if (_current_text_dir == TD_RTL) {
948 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
949 left = right - width;
952 if (left != right) {
953 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
956 left = INT32_MIN;
959 int current_width = u->GetDisplayImageWidth();
960 width += current_width;
961 x += current_width;
963 break;
966 default: break;
968 break;
971 case WID_VR_MATRIX:
972 DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
973 break;
975 case WID_VR_INFO:
976 if (this->cargo != nullptr) {
977 StringID string = this->GetCapacityString(this->cargo);
978 if (string != INVALID_STRING_ID) {
979 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
980 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
983 break;
988 * Some data on this window has become invalid.
989 * @param data Information about the changed data.
990 * @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.
992 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
994 switch (data) {
995 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
996 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
997 /* Clear the selection. */
998 Vehicle *v = Vehicle::Get(this->window_number);
999 this->selected_vehicle = v->index;
1000 this->num_vehicles = UINT8_MAX;
1002 FALLTHROUGH;
1004 case 2: { // The vehicle selection has changed; rebuild the entire list.
1005 if (!gui_scope) break;
1006 this->BuildRefitList();
1008 /* The vehicle width has changed too. */
1009 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1010 uint max_width = 0;
1012 /* Check the width of all cargo information strings. */
1013 for (uint i = 0; i < NUM_CARGO; i++) {
1014 for (uint j = 0; j < this->list[i].Length(); j++) {
1015 StringID string = this->GetCapacityString(&list[i][j]);
1016 if (string != INVALID_STRING_ID) {
1017 Dimension dim = GetStringBoundingBox(string);
1018 max_width = max(dim.width, max_width);
1023 if (this->information_width < max_width) {
1024 this->information_width = max_width;
1025 this->ReInit();
1028 FALLTHROUGH;
1030 case 1: // A new cargo has been selected.
1031 if (!gui_scope) break;
1032 this->cargo = GetRefitOption();
1033 this->RefreshScrollbar();
1034 break;
1038 int GetClickPosition(int click_x)
1040 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
1041 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
1042 click_x -= this->vehicle_margin;
1043 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
1045 return click_x;
1048 void SetSelectedVehicles(int drag_x)
1050 drag_x = GetClickPosition(drag_x);
1052 int left_x = min(this->click_x, drag_x);
1053 int right_x = max(this->click_x, drag_x);
1054 this->num_vehicles = 0;
1056 Vehicle *v = Vehicle::Get(this->window_number);
1057 /* Find the vehicle part that was clicked. */
1058 switch (v->type) {
1059 case VEH_TRAIN: {
1060 /* Don't select anything if we are not clicking in the vehicle. */
1061 if (left_x >= 0) {
1062 const Train *u = Train::From(v);
1063 bool start_counting = false;
1064 for (; u != nullptr; u = u->Next()) {
1065 int current_width = u->GetDisplayImageWidth();
1066 left_x -= current_width;
1067 right_x -= current_width;
1069 if (left_x < 0 && !start_counting) {
1070 this->selected_vehicle = u->index;
1071 start_counting = true;
1073 /* Count the first vehicle, even if articulated part */
1074 this->num_vehicles++;
1075 } else if (start_counting && !u->IsArticulatedPart()) {
1076 /* Do not count articulated parts */
1077 this->num_vehicles++;
1080 if (right_x < 0) break;
1084 /* If the selection is not correct, clear it. */
1085 if (this->num_vehicles != 0) {
1086 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
1087 break;
1090 FALLTHROUGH;
1092 default:
1093 /* Clear the selection. */
1094 this->selected_vehicle = v->index;
1095 this->num_vehicles = UINT8_MAX;
1096 break;
1100 virtual void OnClick(Point pt, int widget, int click_count)
1102 switch (widget) {
1103 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1104 if (this->order != INVALID_VEH_ORDER_ID) break;
1105 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1106 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
1107 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1108 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1109 if (!_ctrl_pressed) {
1110 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1111 } else {
1112 /* The vehicle selection has changed. */
1113 this->InvalidateData(2);
1115 break;
1118 case WID_VR_MATRIX: { // listbox
1119 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
1120 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
1121 this->InvalidateData(1);
1123 if (click_count == 1) break;
1125 FALLTHROUGH;
1127 case WID_VR_REFIT: // refit button
1128 if (this->cargo != nullptr) {
1129 const Vehicle *v = Vehicle::Get(this->window_number);
1131 if (this->order == INVALID_VEH_ORDER_ID) {
1132 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1133 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16 | this->is_virtual_train << 5, GetCmdRefitVeh(v)) && delete_window) delete this;
1134 } else {
1135 if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16 | this->is_virtual_train << 5, CMD_ORDER_REFIT)) delete this;
1138 break;
1142 virtual void OnMouseDrag(Point pt, int widget)
1144 switch (widget) {
1145 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1146 if (this->order != INVALID_VEH_ORDER_ID) break;
1147 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1148 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1149 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1150 break;
1155 virtual void OnDragDrop(Point pt, int widget)
1157 switch (widget) {
1158 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1159 if (this->order != INVALID_VEH_ORDER_ID) break;
1160 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1161 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1162 this->InvalidateData(2);
1163 break;
1168 virtual void OnResize()
1170 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1171 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1172 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1176 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
1177 NWidget(NWID_HORIZONTAL),
1178 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1179 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1180 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1181 EndContainer(),
1182 /* Vehicle display + scrollbar. */
1183 NWidget(NWID_VERTICAL),
1184 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1185 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1186 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1187 EndContainer(),
1188 EndContainer(),
1189 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1190 /* Matrix + scrollbar. */
1191 NWidget(NWID_HORIZONTAL),
1192 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),
1193 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1194 EndContainer(),
1195 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1196 NWidget(NWID_HORIZONTAL),
1197 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1198 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1199 EndContainer(),
1202 static WindowDesc _vehicle_refit_desc(
1203 WDP_AUTO, "view_vehicle_refit", 240, 174,
1204 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1205 WDF_CONSTRUCTION,
1206 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1210 * Show the refit window for a vehicle
1211 * @param *v The vehicle to show the refit window for
1212 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1213 * @param parent the parent window of the refit window
1214 * @param auto_refit Choose cargo for auto-refitting
1216 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit, bool is_virtual_train)
1218 DeleteWindowById(WC_VEHICLE_REFIT, v->index);
1219 RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit, is_virtual_train);
1220 w->parent = parent;
1223 /** Display list of cargo types of the engine, for the purchase information window */
1224 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1226 /* List of cargo types of this engine */
1227 uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1228 /* List of cargo types available in this climate */
1229 uint32 lmask = _cargo_mask;
1231 /* Draw nothing if the engine is not refittable */
1232 if (HasAtMostOneBit(cmask)) return y;
1234 if (cmask == lmask) {
1235 /* Engine can be refitted to all types in this climate */
1236 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1237 } else {
1238 /* Check if we are able to refit to more cargo types and unable to. If
1239 * so, invert the cargo types to list those that we can't refit to. */
1240 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1241 cmask ^= lmask;
1242 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1243 } else {
1244 SetDParam(0, STR_JUST_CARGO_LIST);
1246 SetDParam(1, cmask);
1249 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1252 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1253 StringID GetCargoSubtypeText(const Vehicle *v)
1255 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1256 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1257 if (cb != CALLBACK_FAILED) {
1258 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1259 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1261 if (cb != CALLBACK_FAILED) {
1262 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1265 return STR_EMPTY;
1268 /** Sort vehicles by their number */
1269 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
1271 return (*a)->unitnumber - (*b)->unitnumber;
1274 /** Sort vehicles by their name */
1275 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
1277 static char last_name[2][64];
1279 if (*a != _last_vehicle[0]) {
1280 _last_vehicle[0] = *a;
1281 SetDParam(0, (*a)->index);
1282 GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
1285 if (*b != _last_vehicle[1]) {
1286 _last_vehicle[1] = *b;
1287 SetDParam(0, (*b)->index);
1288 GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
1291 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1292 return (r != 0) ? r : VehicleNumberSorter(a, b);
1295 /** Sort vehicles by their age */
1296 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
1298 int r = (*a)->age - (*b)->age;
1299 return (r != 0) ? r : VehicleNumberSorter(a, b);
1302 /** Sort vehicles by this year profit */
1303 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1305 int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
1306 return (r != 0) ? r : VehicleNumberSorter(a, b);
1309 /** Sort vehicles by last year profit */
1310 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1312 int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
1313 return (r != 0) ? r : VehicleNumberSorter(a, b);
1316 /** Sort vehicles by lifetime profit */
1317 static int CDECL VehicleProfitLifetimeSorter(const Vehicle * const *a, const Vehicle * const *b)
1319 int r = ClampToI32((*a)->GetDisplayProfitLifetime() - (*b)->GetDisplayProfitLifetime());
1320 return (r != 0) ? r : VehicleNumberSorter(a, b);
1323 /** Sort vehicles by their cargo */
1324 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
1326 const Vehicle *v;
1327 CargoArray diff;
1329 /* Append the cargo of the connected waggons */
1330 for (v = *a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1331 for (v = *b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1333 int r = 0;
1334 for (CargoID i = 0; i < NUM_CARGO; i++) {
1335 r = diff[i];
1336 if (r != 0) break;
1339 return (r != 0) ? r : VehicleNumberSorter(a, b);
1342 /** Sort vehicles by their reliability */
1343 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
1345 int r = (*a)->reliability - (*b)->reliability;
1346 return (r != 0) ? r : VehicleNumberSorter(a, b);
1349 /** Sort vehicles by their max speed */
1350 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
1352 int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
1353 return (r != 0) ? r : VehicleNumberSorter(a, b);
1356 /** Sort vehicles by model */
1357 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
1359 int r = (*a)->engine_type - (*b)->engine_type;
1360 return (r != 0) ? r : VehicleNumberSorter(a, b);
1363 /** Sort vehicles by their value */
1364 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
1366 const Vehicle *u;
1367 Money diff = 0;
1369 for (u = *a; u != nullptr; u = u->Next()) diff += u->value;
1370 for (u = *b; u != nullptr; u = u->Next()) diff -= u->value;
1372 int r = ClampToI32(diff);
1373 return (r != 0) ? r : VehicleNumberSorter(a, b);
1376 /** Sort vehicles by their length */
1377 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
1379 int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
1380 return (r != 0) ? r : VehicleNumberSorter(a, b);
1383 /** Sort vehicles by the time they can still live */
1384 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
1386 int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
1387 return (r != 0) ? r : VehicleNumberSorter(a, b);
1390 /** Sort vehicles by the timetable delay */
1391 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
1393 auto a_lateness_counter = HasBit((*a)->vehicle_flags, VF_SEPARATION_IN_PROGRESS) ? 0 : (*a)->lateness_counter;
1394 auto b_lateness_counter = HasBit((*b)->vehicle_flags, VF_SEPARATION_IN_PROGRESS) ? 0 : (*b)->lateness_counter;
1396 int r = a_lateness_counter - b_lateness_counter;
1397 return (r != 0) ? r : VehicleNumberSorter(a, b);
1400 void InitializeGUI()
1402 MemSetT(&_sorting, 0);
1406 * Assign a vehicle window a new vehicle
1407 * @param window_class WindowClass to search for
1408 * @param from_index the old vehicle ID
1409 * @param to_index the new vehicle ID
1411 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1413 Window *w = FindWindowById(window_class, from_index);
1414 if (w != nullptr) {
1415 /* Update window_number */
1416 w->window_number = to_index;
1417 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1419 /* Update vehicle drag data */
1420 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1421 _thd.window_number = to_index;
1424 /* Notify the window. */
1425 w->InvalidateData(VIWD_AUTOREPLACE, false);
1430 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1431 * @param from_index the old vehicle ID
1432 * @param to_index the new vehicle ID
1434 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1436 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1437 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1438 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1439 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1440 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1443 static const NWidgetPart _nested_vehicle_list[] = {
1444 NWidget(NWID_HORIZONTAL),
1445 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1446 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1447 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1448 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1449 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1450 EndContainer(),
1452 NWidget(NWID_HORIZONTAL),
1453 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1454 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1455 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_FILTER_BY_CARGO_SEL),
1456 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_FILTER_BY_CARGO), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
1457 EndContainer(),
1458 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VL_REFRESH_SORTING), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_REFRESH_SORTING, STR_TOOLTIP_REFRESH_SORTING),
1459 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
1460 EndContainer(),
1461 EndContainer(),
1463 NWidget(NWID_HORIZONTAL),
1464 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),
1465 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1466 EndContainer(),
1468 NWidget(NWID_HORIZONTAL),
1469 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1470 NWidget(NWID_HORIZONTAL),
1471 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1472 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1473 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1474 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1475 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1476 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1477 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1478 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1479 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1480 EndContainer(),
1481 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1482 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1483 EndContainer(),
1484 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1485 EndContainer(),
1488 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
1490 const Order *order = v->GetOrder(start);
1491 if (order == nullptr) return;
1493 bool rtl = _current_text_dir == TD_RTL;
1494 int l_offset = rtl ? 0 : ScaleGUITrad(6);
1495 int r_offset = rtl ? ScaleGUITrad(6) : 0;
1496 int i = 0;
1497 VehicleOrderID oid = start;
1499 do {
1500 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1502 if (order->IsType(OT_GOTO_STATION)) {
1503 SetDParam(0, order->GetDestination());
1504 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1506 y += FONT_HEIGHT_SMALL;
1507 if (++i == 4) break;
1510 oid++;
1511 order = order->next;
1512 if (order == nullptr) {
1513 order = v->GetFirstOrder();
1514 oid = 0;
1516 } while (oid != start);
1520 * Draws an image of a vehicle chain
1521 * @param v Front vehicle
1522 * @param left The minimum horizontal position
1523 * @param right The maximum horizontal position
1524 * @param y Vertical position to draw at
1525 * @param selection Selected vehicle to draw a frame around
1526 * @param skip Number of pixels to skip at the front (for scrolling)
1528 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1530 switch (v->type) {
1531 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1532 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1533 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1534 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1535 default: NOT_REACHED();
1540 * Get the height of a vehicle in the vehicle list GUIs.
1541 * @param type the vehicle type to look at
1542 * @param divisor the resulting height must be dividable by this
1543 * @return the height
1545 uint GetVehicleListHeight(VehicleType type, uint divisor)
1547 /* Name + vehicle + profit */
1548 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1549 /* Drawing of the 4 small orders + profit*/
1550 if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
1552 if (divisor == 1) return base;
1554 /* Make sure the height is dividable by divisor */
1555 uint rem = base % divisor;
1556 return base + (rem == 0 ? 0 : divisor - rem);
1560 * Draw all the vehicle list items.
1561 * @param selected_vehicle The vehicle that is to be highlighted.
1562 * @param line_height Height of a single item line.
1563 * @param r Rectangle with edge positions of the matrix widget.
1565 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1567 int left = r.left + WD_MATRIX_LEFT;
1568 int right = r.right - WD_MATRIX_RIGHT;
1569 int width = right - left;
1570 bool rtl = _current_text_dir == TD_RTL;
1572 int text_offset = max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits + 1) + WD_FRAMERECT_RIGHT;
1573 int text_left = left + (rtl ? 0 : text_offset);
1574 int text_right = right - (rtl ? text_offset : 0);
1576 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1577 int orderlist_left = left + (rtl ? 0 : max(ScaleGUITrad(100) + text_offset, width / 2));
1578 int orderlist_right = right - (rtl ? max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1580 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1581 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1583 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1585 int y = r.top;
1586 uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
1587 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1588 const Vehicle *v = this->vehicles[i];
1590 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1592 switch (this->vehicles.SortType()) {
1593 case VST_AGE: {
1594 SetDParam(0, v->age / DAYS_IN_LEAP_YEAR);
1595 SetDParam(1, v->max_age / DAYS_IN_LEAP_YEAR);
1596 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_LIST_AGE : STR_VEHICLE_LIST_AGE_RED);
1597 break;
1600 case VST_CARGO: {
1601 CargoArray cargo_manifest;
1603 for (auto temp_v = v; temp_v != nullptr; temp_v = temp_v->Next()) {
1604 const Engine* engine = temp_v->GetEngine();
1606 assert(engine != nullptr);
1608 if (!engine->CanCarryCargo()) continue;
1609 if (temp_v->cargo_cap <= 0) continue;
1611 cargo_manifest[temp_v->cargo_type] += temp_v->cargo_cap;
1614 std::string cargo_manifest_string;
1615 char buffer[1024];
1617 for (CargoID cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++)
1619 if (cargo_manifest[cargo_type] <= 0) continue;
1621 if (!cargo_manifest_string.empty()) {
1622 cargo_manifest_string.append(", ");
1625 SetDParam(0, cargo_type);
1626 SetDParam(1, cargo_manifest[cargo_type]);
1628 GetString(buffer, STR_JUST_CARGO, lastof(buffer));
1629 cargo_manifest_string.append(buffer);
1632 SetDParamStr(0, cargo_manifest_string.c_str());
1633 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_CARGO);
1634 break;
1637 case VST_RELIABILITY: {
1638 SetDParam(0, ToPercent16(v->reliability));
1639 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, ToPercent16(v->reliability) >= 50 ? STR_VEHICLE_LIST_RELIABILITY : STR_VEHICLE_LIST_RELIABILITY_RED);
1640 break;
1643 case VST_MAX_SPEED: {
1644 SetDParam(0, v->GetDisplayMaxSpeed());
1645 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_MAX_SPEED);
1646 break;
1649 case VST_MODEL: {
1650 SetDParam(0, v->engine_type);
1651 SetDParam(1, v->build_year);
1652 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_ENGINE_BUILT);
1653 break;
1656 case VST_VALUE: {
1657 Money total_value = 0;
1658 for (auto temp_v = v; temp_v != nullptr; temp_v = temp_v->GetNextVehicle()) {
1659 total_value += temp_v->value;
1662 SetDParam(0, total_value);
1663 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_VALUE);
1664 break;
1667 case VST_LENGTH: {
1668 const GroundVehicleCache* gcache = v->GetGroundVehicleCache();
1669 assert(gcache != nullptr);
1670 SetDParam(0, CeilDiv(gcache->cached_total_length * 10, TILE_SIZE));
1671 SetDParam(1, 1);
1672 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_LENGTH);
1673 break;
1676 case VST_TIME_TO_LIVE: {
1677 auto years_remaining = (v->max_age / DAYS_IN_LEAP_YEAR) - (v->age / DAYS_IN_LEAP_YEAR);
1678 SetDParam(0, std::abs(years_remaining));
1679 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, (years_remaining > 1) ? STR_VEHICLE_LIST_TIME_TO_LIVE : ((years_remaining < 0) ? STR_VEHICLE_LIST_TIME_TO_LIVE_OVERDUE : STR_VEHICLE_LIST_TIME_TO_LIVE_RED));
1680 break;
1683 case VST_TIMETABLE_DELAY: {
1684 auto lateness_counter = HasBit(v->vehicle_flags, VF_SEPARATION_IN_PROGRESS) ? 0 : v->lateness_counter;
1686 if (lateness_counter == 0) {
1687 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_TIMETABLE_DELAY_ON_TIME);
1688 } else {
1689 SetDParam(0, std::abs(lateness_counter));
1690 SetDParam(1, std::abs(lateness_counter));
1691 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, lateness_counter > 0 ? STR_VEHICLE_LIST_TIMETABLE_DELAY_LATE : STR_VEHICLE_LIST_TIMETABLE_DELAY_EARLY);
1693 break;
1696 default: {
1697 SetDParam(0, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1698 SetDParam(1, v->GetDisplayProfitThisYear());
1699 SetDParam(2, v->GetDisplayProfitLastYear());
1700 SetDParam(3, v->GetDisplayProfitLifetime());
1702 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR_LIFETIME);
1703 break;
1707 uint32 vehicle_cargoes = 0;
1708 auto temp_v = v;
1710 do {
1711 if (temp_v->cargo_cap == 0) continue;
1713 SetBit(vehicle_cargoes, temp_v->cargo_type);
1714 } while ((temp_v = temp_v->Next()) != nullptr);
1716 if (v->name != nullptr) {
1717 /* The vehicle got a name so we will print it */
1718 SetDParam(0, STR_TINY_BLACK_VEHICLE);
1719 SetDParam(1, v->index);
1720 SetDParam(2, vehicle_cargoes);
1721 DrawString(text_left, text_right, y, STR_VEHICLE_NAME_AND_CARGO);
1722 } else if (v->group_id != DEFAULT_GROUP) {
1723 /* The vehicle has no name, but is member of a group, so print group name */
1724 SetDParam(0, STR_TINY_GROUP);
1725 SetDParam(1, v->group_id);
1726 SetDParam(2, vehicle_cargoes);
1727 DrawString(text_left, text_right, y, STR_VEHICLE_NAME_AND_CARGO);
1730 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
1732 StringID str;
1734 if (v->IsChainInDepot()) {
1735 str = STR_BLUE_COMMA;
1736 } else {
1737 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1740 SetDParam(0, v->unitnumber);
1741 DrawString(left, right, y + 2, str);
1743 DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1745 y += line_height;
1750 * Window for the (old) vehicle listing.
1752 * bitmask for w->window_number
1753 * 0-7 CompanyID (owner)
1754 * 8-10 window type (use flags in vehicle_gui.h)
1755 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1756 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1758 struct VehicleListWindow : public BaseVehicleListWindow {
1759 private:
1760 /** Enumeration of planes of the button row at the bottom. */
1761 enum ButtonPlanes {
1762 BP_SHOW_BUTTONS, ///< Show the buttons.
1763 BP_HIDE_BUTTONS, ///< Show the empty panel.
1766 bool live_refresh_sorting;
1768 public:
1769 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1771 /* Set up sorting. Make the window-specific _sorting variable
1772 * point to the correct global _sorting struct so we are freed
1773 * from having conditionals during window operation */
1774 switch (this->vli.vtype) {
1775 case VEH_TRAIN: this->sorting = &_sorting.train; break;
1776 case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
1777 case VEH_SHIP: this->sorting = &_sorting.ship; break;
1778 case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
1779 default: NOT_REACHED();
1782 this->CreateNestedTree();
1784 this->GetWidget<NWidgetStacked>(WID_VL_FILTER_BY_CARGO_SEL)->SetDisplayedPlane((this->vli.type == VL_SHARED_ORDERS) ? SZSP_NONE : 0);
1786 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1788 this->vehicles.SetListing(*this->sorting);
1789 this->vehicles.ForceRebuild();
1790 this->vehicles.NeedResort();
1791 this->BuildVehicleList();
1792 this->SortVehicleList();
1794 /* Set up the window widgets */
1795 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1797 if (this->vli.type == VL_SHARED_ORDERS) {
1798 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1799 } else {
1800 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1803 this->FinishInitNested(window_number);
1804 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1807 ~VehicleListWindow()
1809 *this->sorting = this->vehicles.GetListing();
1812 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1814 switch (widget) {
1815 case WID_VL_LIST:
1816 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1818 switch (this->vli.vtype) {
1819 case VEH_TRAIN:
1820 case VEH_ROAD:
1821 size->height = 6 * resize->height;
1822 break;
1823 case VEH_SHIP:
1824 case VEH_AIRCRAFT:
1825 size->height = 4 * resize->height;
1826 break;
1827 default: NOT_REACHED();
1829 break;
1831 case WID_VL_SORT_ORDER: {
1832 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1833 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1834 d.height += padding.height;
1835 *size = maxdim(*size, d);
1836 break;
1839 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1840 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false, this->vli.vtype == VEH_TRAIN);
1841 d.height += padding.height;
1842 d.width += padding.width;
1843 *size = maxdim(*size, d);
1844 break;
1849 virtual void SetStringParameters(int widget) const
1851 switch (widget) {
1852 case WID_VL_AVAILABLE_VEHICLES:
1853 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1854 break;
1856 case WID_VL_FILTER_BY_CARGO:
1857 SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]);
1858 break;
1860 case WID_VL_CAPTION: {
1861 switch (this->vli.type) {
1862 case VL_SHARED_ORDERS: // Shared Orders
1863 if (this->vehicles.Length() == 0) {
1864 /* We can't open this window without vehicles using this order
1865 * and we should close the window when deleting the order. */
1866 NOT_REACHED();
1868 SetDParam(0, this->vscroll->GetCount());
1869 break;
1871 case VL_STANDARD: // Company Name
1872 SetDParam(0, STR_COMPANY_NAME);
1873 SetDParam(1, this->vli.index);
1874 SetDParam(3, this->vscroll->GetCount());
1875 break;
1877 case VL_STATION_LIST: // Station/Waypoint Name
1878 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
1879 SetDParam(1, this->vli.index);
1880 SetDParam(3, this->vscroll->GetCount());
1881 break;
1883 case VL_DEPOT_LIST:
1884 SetDParam(0, STR_DEPOT_CAPTION);
1885 SetDParam(1, this->vli.vtype);
1886 SetDParam(2, this->vli.index);
1887 SetDParam(3, this->vscroll->GetCount());
1888 break;
1889 default: NOT_REACHED();
1891 break;
1896 virtual void DrawWidget(const Rect &r, int widget) const
1898 switch (widget) {
1899 case WID_VL_SORT_ORDER:
1900 /* draw arrow pointing up/down for ascending/descending sorting */
1901 this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1902 break;
1904 case WID_VL_LIST:
1905 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1906 break;
1910 virtual void OnPaint()
1912 this->BuildVehicleList();
1913 this->SortVehicleList();
1915 if (!this->ShouldShowActionDropdownList() && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1916 HideDropDownMenu(this);
1919 /* Hide the widgets that we will not use in this window
1920 * Some windows contains actions only fit for the owner */
1921 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1922 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1923 if (plane_to_show != nwi->shown_plane) {
1924 nwi->SetDisplayedPlane(plane_to_show);
1925 nwi->SetDirty(this);
1927 if (this->owner == _local_company) {
1928 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1929 this->SetWidgetDisabledState(WID_VL_MANAGE_VEHICLES_DROPDOWN, !this->ShouldShowActionDropdownList());
1930 this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
1931 WID_VL_STOP_ALL,
1932 WID_VL_START_ALL,
1933 WIDGET_LIST_END);
1936 /* Set text of sort by dropdown widget. */
1937 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
1939 this->GetWidget<NWidgetCore>(WID_VL_FILTER_BY_CARGO)->widget_data = this->cargo_filter_texts[this->cargo_filter_criteria];
1941 this->SetWidgetLoweredState(WID_VL_REFRESH_SORTING, this->live_refresh_sorting);
1943 this->DrawWidgets();
1946 virtual void OnClick(Point pt, int widget, int click_count)
1948 switch (widget) {
1949 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1950 this->vehicles.ToggleSortOrder();
1951 this->vehicles.ForceResort();
1952 this->SetDirty();
1953 break;
1955 case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
1956 ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1957 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : this->vehicle_sorter_non_ground_veh_disable_mask);
1958 return;
1960 case WID_VL_FILTER_BY_CARGO: // Cargo filter dropdown
1961 ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, WID_VL_FILTER_BY_CARGO, 0, 0);
1962 break;
1964 case WID_VL_LIST: { // Matrix to show vehicles
1965 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1966 if (id_v >= this->vehicles.Length()) return; // click out of list bound
1968 const Vehicle *v = this->vehicles[id_v];
1969 if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
1970 break;
1973 case WID_VL_AVAILABLE_VEHICLES:
1974 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1975 break;
1977 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1978 DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier::UnPack(this->window_number).type == VL_STANDARD,
1979 false, this->vli.vtype == VEH_TRAIN);
1980 ShowDropDownList(this, list, -1, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1981 break;
1984 case WID_VL_STOP_ALL:
1985 case WID_VL_START_ALL:
1986 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1987 break;
1989 case WID_VL_REFRESH_SORTING: {
1990 this->live_refresh_sorting = !this->live_refresh_sorting;
1991 this->SetWidgetDirty(WID_VL_REFRESH_SORTING);
1992 break;
1997 virtual void OnDropdownSelect(int widget, int index)
1999 switch (widget) {
2000 case WID_VL_SORT_BY_PULLDOWN:
2001 this->vehicles.SetSortType(index);
2002 break;
2004 case WID_VL_FILTER_BY_CARGO:
2005 this->SetCargoFilterIndex(index);
2006 break;
2008 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
2009 assert(this->ShouldShowActionDropdownList());
2011 switch (index) {
2012 case ADI_SET_ALL_ON_TIME: { // Reset all late timers
2013 int num_vehicles = this->vehicles.Length();
2015 for (int v_index = 0; v_index < num_vehicles; ++v_index) {
2016 DoCommandP(0, this->vehicles[v_index]->index, 0, CMD_SET_VEHICLE_ON_TIME | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE));
2019 break;
2022 case ADI_REPLACE: // Replace window
2023 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
2024 break;
2025 case ADI_TEMPLATE_REPLACE:
2026 if (vli.vtype == VEH_TRAIN) {
2027 ShowTemplateReplaceWindow(this->unitnumber_digits, this->resize.step_height);
2029 break;
2030 case ADI_SERVICE: // Send for servicing
2031 case ADI_DEPOT: // Send to Depots
2032 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
2033 break;
2035 case ADI_TRACERESTRICT_SLOT_MGMT: {
2036 extern void ShowTraceRestrictSlotWindow(CompanyID company);
2037 ShowTraceRestrictSlotWindow(this->owner);
2038 break;
2041 default: NOT_REACHED();
2043 break;
2044 default: NOT_REACHED();
2046 this->SetDirty();
2049 virtual void OnTick()
2051 if (_pause_mode != PM_UNPAUSED) return;
2053 if (live_refresh_sorting) {
2054 this->vehicles.ForceResort();
2057 if (this->vehicles.NeedResort()) {
2058 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
2060 DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
2061 this->SetDirty();
2065 virtual void OnResize()
2067 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
2071 * Some data on this window has become invalid.
2072 * @param data Information about the changed data.
2073 * @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.
2075 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2077 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
2078 /* Needs to be done in command-scope, so everything stays valid */
2079 this->vli.index = GB(data, 0, 20);
2080 this->window_number = this->vli.Pack();
2081 this->vehicles.ForceRebuild();
2082 return;
2085 if (data == 0) {
2086 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
2087 this->vehicles.ForceRebuild();
2088 } else {
2089 this->vehicles.ForceResort();
2094 static WindowDesc _vehicle_list_other_desc(
2095 WDP_AUTO, "list_vehicles", 260, 246,
2096 WC_INVALID, WC_NONE,
2098 _nested_vehicle_list, lengthof(_nested_vehicle_list)
2101 static WindowDesc _vehicle_list_train_desc(
2102 WDP_AUTO, "list_vehicles_train", 325, 246,
2103 WC_TRAINS_LIST, WC_NONE,
2105 _nested_vehicle_list, lengthof(_nested_vehicle_list)
2108 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
2110 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
2112 WindowNumber window_number = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
2114 if (vehicle_type == VEH_TRAIN) {
2115 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, window_number);
2116 } else {
2117 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
2118 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, window_number);
2122 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
2124 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
2125 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
2126 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
2129 if (_settings_client.gui.advanced_vehicle_list > static_cast<uint>(company != _local_company) != _ctrl_pressed) {
2130 ShowCompanyGroup(company, vehicle_type);
2131 } else {
2132 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
2136 void ShowVehicleListWindow(const Vehicle *v)
2138 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
2141 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
2143 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
2146 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
2148 uint16 depot_airport_index;
2150 if (vehicle_type == VEH_AIRCRAFT) {
2151 depot_airport_index = GetStationIndex(depot_tile);
2152 } else {
2153 depot_airport_index = GetDepotIndex(depot_tile);
2155 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
2159 /* Unified vehicle GUI - Vehicle Details Window */
2161 assert_compile(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
2162 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
2163 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
2164 assert_compile(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
2166 /** Vehicle details widgets (other than train). */
2167 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
2168 NWidget(NWID_HORIZONTAL),
2169 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2170 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2171 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_TRIP_HISTORY),SetMinimalSize(44, 0),SetDataTip(STR_TRIP_HISTORY, STR_TRIP_HISTORY_TOOLTIP),
2172 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 */),
2173 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2174 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2175 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2176 EndContainer(),
2177 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
2178 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
2179 NWidget(NWID_HORIZONTAL),
2180 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2181 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2182 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2183 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2184 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2185 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2186 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2187 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2188 EndContainer(),
2191 /** Train details widgets. */
2192 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
2193 NWidget(NWID_HORIZONTAL),
2194 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2195 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2196 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_TRIP_HISTORY),SetMinimalSize(44, 0),SetDataTip(STR_TRIP_HISTORY, STR_TRIP_HISTORY_TOOLTIP),
2197 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 */),
2198 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2199 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2200 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2201 EndContainer(),
2202 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
2203 NWidget(NWID_HORIZONTAL),
2204 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(420, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
2205 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
2206 EndContainer(),
2207 NWidget(NWID_HORIZONTAL),
2208 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2209 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2210 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2211 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2212 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2213 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2214 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2215 EndContainer(),
2216 NWidget(NWID_HORIZONTAL),
2217 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
2218 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2219 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
2220 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2221 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
2222 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2223 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
2224 SetDataTip(STR_VEHICLE_DETAIL_TAB_PERFORMANCE, STR_VEHICLE_DETAILS_TRAIN_PERFORMANCE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2225 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2226 EndContainer(),
2230 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
2231 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
2232 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
2233 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
2234 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
2236 static StringID _service_interval_dropdown[] = {
2237 STR_VEHICLE_DETAILS_DEFAULT,
2238 STR_VEHICLE_DETAILS_DAYS,
2239 STR_VEHICLE_DETAILS_PERCENT,
2240 INVALID_STRING_ID,
2243 /** Class for managing the vehicle details window. */
2244 struct VehicleDetailsWindow : Window {
2245 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
2246 Scrollbar *vscroll;
2247 bool vehicle_slots_line_shown;
2249 /** Initialize a newly created vehicle details window */
2250 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2252 const Vehicle *v = Vehicle::Get(window_number);
2254 this->CreateNestedTree();
2255 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
2256 this->FinishInitNested(window_number);
2258 this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
2260 this->owner = v->owner;
2261 this->tab = TDW_TAB_CARGO;
2264 ~VehicleDetailsWindow()
2266 if (this->window_number != INVALID_VEHICLE) {
2267 if (!FocusWindowById(WC_VEHICLE_VIEW, this->window_number)) {
2268 if (this->window_number != INVALID_VEHICLE) {
2269 const Vehicle *v = Vehicle::Get(this->window_number);
2270 MarkAllRoutePathsDirty(v);
2271 MarkAllRouteStepsDirty(v);
2278 * Some data on this window has become invalid.
2279 * @param data Information about the changed data.
2280 * @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.
2282 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2284 if (data == VIWD_AUTOREPLACE) {
2285 /* Autoreplace replaced the vehicle.
2286 * Nothing to do for this window. */
2287 return;
2289 if (!gui_scope) return;
2290 const Vehicle *v = Vehicle::Get(this->window_number);
2291 if (v->type == VEH_ROAD) {
2292 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
2293 uint aimed_height = this->GetRoadVehDetailsHeight(v);
2294 /* If the number of articulated parts changes, the size of the window must change too. */
2295 if (aimed_height != nwid_info->current_y) {
2296 this->ReInit();
2302 * Gets the desired height for the road vehicle details panel.
2303 * @param v Road vehicle being shown.
2304 * @return Desired height in pixels.
2306 uint GetRoadVehDetailsHeight(const Vehicle *v)
2308 uint desired_height;
2309 if (v->HasArticulatedPart()) {
2310 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2311 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
2312 /* Add space for the cargo amount for each part. */
2313 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2314 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
2316 } else {
2317 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2319 return desired_height;
2322 bool ShouldShowSlotsLine(const Vehicle *v) const
2324 if (v->type != VEH_TRAIN) return false;
2325 return HasBit(Train::From(v)->flags, VRF_HAVE_SLOT);
2328 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2330 switch (widget) {
2331 case WID_VD_TOP_DETAILS: {
2332 const Vehicle *v = Vehicle::Get(this->window_number);
2333 Dimension dim = { 0, 0 };
2334 this->vehicle_slots_line_shown = ShouldShowSlotsLine(v);
2335 int lines = 5;
2336 if (this->vehicle_slots_line_shown) lines++;
2338 size->height = WD_FRAMERECT_TOP + lines * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2340 for (uint i = 0; i < 5; i++) SetDParamMaxValue(i, INT16_MAX);
2341 static const StringID info_strings[] = {
2342 STR_VEHICLE_INFO_MAX_SPEED,
2343 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
2344 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
2345 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
2347 for (uint i = 0; i < lengthof(info_strings); i++) {
2348 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
2350 SetDParam(0, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2351 for (uint i = 1; i < 4; i++) SetDParamMaxValue(i, 1 << 24);
2352 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_LIFETIME));
2354 if (v->type == VEH_TRAIN) {
2355 SetDParamMaxValue(0, _settings_game.vehicle.max_train_length * 10);
2356 SetDParam(1, 1);
2357 SetDParam(2, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2358 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_TRAIN_LENGTH));
2359 } else {
2360 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR));
2363 SetDParam(0, v->group_id);
2364 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_GROUP));
2365 SetDParam(0, STR_VEHICLE_INFO_AGE);
2366 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2367 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2368 break;
2371 case WID_VD_MIDDLE_DETAILS: {
2372 const Vehicle *v = Vehicle::Get(this->window_number);
2373 switch (v->type) {
2374 case VEH_ROAD:
2375 size->height = this->GetRoadVehDetailsHeight(v);
2376 break;
2378 case VEH_SHIP:
2379 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2380 break;
2382 case VEH_AIRCRAFT:
2383 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
2384 break;
2386 default:
2387 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2389 break;
2392 case WID_VD_MATRIX:
2393 resize->height = max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
2394 size->height = 4 * resize->height;
2395 break;
2397 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2398 StringID *strs = _service_interval_dropdown;
2399 while (*strs != INVALID_STRING_ID) {
2400 *size = maxdim(*size, GetStringBoundingBox(*strs++));
2402 size->width += padding.width;
2403 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2404 break;
2407 case WID_VD_SERVICING_INTERVAL:
2408 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2409 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
2410 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;
2411 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2412 break;
2416 /** Checks whether service interval is enabled for the vehicle. */
2417 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2419 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2420 switch (vehicle_type) {
2421 default: NOT_REACHED();
2422 case VEH_TRAIN: return vds->servint_trains != 0;
2423 case VEH_ROAD: return vds->servint_roadveh != 0;
2424 case VEH_SHIP: return vds->servint_ships != 0;
2425 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2430 * Draw the details for the given vehicle at the position of the Details windows
2432 * @param v current vehicle
2433 * @param left The left most coordinate to draw
2434 * @param right The right most coordinate to draw
2435 * @param y The y coordinate
2436 * @param vscroll_pos Position of scrollbar (train only)
2437 * @param vscroll_cap Number of lines currently displayed (train only)
2438 * @param det_tab Selected details tab (train only)
2440 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2442 switch (v->type) {
2443 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2444 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2445 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2446 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2447 default: NOT_REACHED();
2451 virtual void SetStringParameters(int widget) const
2453 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2456 virtual void DrawWidget(const Rect &r, int widget) const
2458 const Vehicle *v = Vehicle::Get(this->window_number);
2460 switch (widget) {
2461 case WID_VD_TOP_DETAILS: {
2462 int y = r.top + WD_FRAMERECT_TOP;
2464 /* Draw running cost */
2465 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2466 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2467 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2468 SetDParam(3, v->GetDisplayRunningCost());
2469 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2470 y += FONT_HEIGHT_NORMAL;
2472 /* Draw max speed */
2473 StringID string;
2474 if (v->type == VEH_TRAIN ||
2475 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2476 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2477 SetDParam(2, v->GetDisplayMaxSpeed());
2478 SetDParam(1, gcache->cached_power);
2479 SetDParam(0, gcache->cached_weight);
2480 SetDParam(3, gcache->cached_max_te / 1000);
2481 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2482 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2483 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2484 } else {
2485 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2487 } else {
2488 SetDParam(0, v->GetDisplayMaxSpeed());
2489 if (v->type == VEH_AIRCRAFT) {
2490 SetDParam(1, v->GetEngine()->GetAircraftTypeText());
2491 if (Aircraft::From(v)->GetRange() > 0) {
2492 SetDParam(2, Aircraft::From(v)->GetRange());
2493 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE;
2494 } else {
2495 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE;
2497 } else {
2498 string = STR_VEHICLE_INFO_MAX_SPEED;
2501 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2502 y += FONT_HEIGHT_NORMAL;
2504 /* Draw profit */
2505 if (v->type == VEH_TRAIN) {
2506 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2507 SetDParam(0, CeilDiv(gcache->cached_total_length * 10, TILE_SIZE));
2508 SetDParam(1, 1);
2509 SetDParam(2, v->GetDisplayProfitThisYear());
2510 SetDParam(3, v->GetDisplayProfitLastYear());
2511 SetDParam(4, v->GetDisplayProfitLifetime());
2512 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_TRAIN_LENGTH);
2513 } else {
2514 SetDParam(0, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2515 SetDParam(1, v->GetDisplayProfitThisYear());
2516 SetDParam(2, v->GetDisplayProfitLastYear());
2517 SetDParam(3, v->GetDisplayProfitLifetime());
2518 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_LIFETIME);
2520 y += FONT_HEIGHT_NORMAL;
2522 /* Draw breakdown & reliability */
2523 SetDParam(0, ToPercent16(v->reliability));
2524 SetDParam(1, v->breakdowns_since_last_service);
2525 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2526 y += FONT_HEIGHT_NORMAL;
2528 bool should_show_slots = this->ShouldShowSlotsLine(v);
2529 if (should_show_slots) {
2530 std::vector<TraceRestrictSlotID> slots;
2531 TraceRestrictGetVehicleSlots(v->index, slots);
2533 char text_buffer[512];
2534 char *buffer = text_buffer;
2535 const char * const last = lastof(text_buffer);
2536 SetDParam(0, slots.size());
2537 buffer = GetString(buffer, STR_TRACE_RESTRICT_SLOT_LIST_HEADER, last);
2539 for (size_t i = 0; i < slots.size(); i++) {
2540 if (i != 0) buffer = GetString(buffer, STR_TRACE_RESTRICT_SLOT_LIST_SEPARATOR, last);
2541 buffer = strecpy(buffer, TraceRestrictSlot::Get(slots[i])->name.c_str(), last);
2543 SetDParamStr(0, text_buffer);
2544 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_JUST_RAW_STRING);
2545 y += FONT_HEIGHT_NORMAL;
2548 SetDParam(0, v->group_id);
2549 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_GROUP);
2551 if (this->vehicle_slots_line_shown != should_show_slots) {
2552 const_cast<VehicleDetailsWindow *>(this)->ReInit();
2554 break;
2557 case WID_VD_MATRIX:
2558 /* For trains only. */
2559 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);
2560 break;
2562 case WID_VD_MIDDLE_DETAILS: {
2563 /* For other vehicles, at the place of the matrix. */
2564 bool rtl = _current_text_dir == TD_RTL;
2565 uint sprite_width = GetSingleVehicleWidth(v, EIT_IN_DETAILS) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2567 uint text_left = r.left + (rtl ? 0 : sprite_width);
2568 uint text_right = r.right - (rtl ? sprite_width : 0);
2570 /* Articulated road vehicles use a complete line. */
2571 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2572 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2573 } else {
2574 uint sprite_left = rtl ? text_right : r.left;
2575 uint sprite_right = rtl ? r.right : text_left;
2577 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2579 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2580 break;
2583 case WID_VD_SERVICING_INTERVAL:
2584 /* Draw service interval text */
2585 SetDParam(0, v->GetServiceInterval());
2586 SetDParam(1, v->date_of_last_service);
2587 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2588 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2589 break;
2593 /** Repaint vehicle details window. */
2594 virtual void OnPaint()
2596 const Vehicle *v = Vehicle::Get(this->window_number);
2598 this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
2600 if (v->type == VEH_TRAIN) {
2601 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2602 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2605 /* Disable service-scroller when interval is set to disabled */
2606 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2607 WID_VD_INCREASE_SERVICING_INTERVAL,
2608 WID_VD_DECREASE_SERVICING_INTERVAL,
2609 WIDGET_LIST_END);
2611 StringID str = v->ServiceIntervalIsCustom() ?
2612 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2613 STR_VEHICLE_DETAILS_DEFAULT;
2614 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2616 this->DrawWidgets();
2619 virtual void OnClick(Point pt, int widget, int click_count)
2621 switch (widget) {
2622 case WID_VD_TRIP_HISTORY: {
2623 const Vehicle *v = Vehicle::Get(this->window_number);
2624 ShowTripHistoryWindow(v);
2625 break;
2628 case WID_VD_RENAME_VEHICLE: { // rename
2629 const Vehicle *v = Vehicle::Get(this->window_number);
2630 SetDParam(0, v->index);
2631 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2632 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2633 break;
2636 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2637 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2638 int mod = _ctrl_pressed ? 5 : 10;
2639 const Vehicle *v = Vehicle::Get(this->window_number);
2641 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2642 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2643 if (mod == v->GetServiceInterval()) return;
2645 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2646 break;
2649 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2650 const Vehicle *v = Vehicle::Get(this->window_number);
2651 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0, 0, DDSF_LOST_FOCUS);
2652 break;
2655 case WID_VD_DETAILS_CARGO_CARRIED:
2656 case WID_VD_DETAILS_TRAIN_VEHICLES:
2657 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2658 case WID_VD_DETAILS_TOTAL_CARGO:
2659 this->SetWidgetsDisabledState(false,
2660 WID_VD_DETAILS_CARGO_CARRIED,
2661 WID_VD_DETAILS_TRAIN_VEHICLES,
2662 WID_VD_DETAILS_CAPACITY_OF_EACH,
2663 WID_VD_DETAILS_TOTAL_CARGO,
2664 widget,
2665 WIDGET_LIST_END);
2667 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2668 this->SetDirty();
2669 break;
2673 virtual void OnDropdownSelect(int widget, int index)
2675 switch (widget) {
2676 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2677 const Vehicle *v = Vehicle::Get(this->window_number);
2678 bool iscustom = index != 0;
2679 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2680 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2681 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2682 break;
2687 virtual void OnQueryTextFinished(char *str)
2689 if (str == nullptr) return;
2691 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);
2694 virtual void OnResize()
2696 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2697 if (nwi != nullptr) {
2698 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2702 virtual void OnFocus(Window *previously_focused_window)
2704 if (HasFocusedVehicleChanged(this->window_number, previously_focused_window)) {
2705 if (this->window_number != INVALID_VEHICLE) {
2706 const Vehicle *v = Vehicle::Get(this->window_number);
2707 MarkAllRoutePathsDirty(v);
2708 MarkAllRouteStepsDirty(v);
2713 virtual void OnFocusLost(Window *newly_focused_window)
2715 if (HasFocusedVehicleChanged(this->window_number, newly_focused_window)) {
2716 if (this->window_number != INVALID_VEHICLE) {
2717 const Vehicle *v = Vehicle::Get(this->window_number);
2718 MarkAllRoutePathsDirty(v);
2719 MarkAllRouteStepsDirty(v);
2725 /** Vehicle details window descriptor. */
2726 static WindowDesc _train_vehicle_details_desc(
2727 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2728 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2730 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2733 /** Vehicle details window descriptor for other vehicles than a train. */
2734 static WindowDesc _nontrain_vehicle_details_desc(
2735 WDP_AUTO, "view_vehicle_details", 405, 113,
2736 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2738 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2741 /** Shows the vehicle details window of the given vehicle. */
2742 static void ShowVehicleDetailsWindow(const Vehicle *v)
2744 DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
2745 DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2746 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2750 /* Unified vehicle GUI - Vehicle View Window */
2752 /** Vehicle view widgets. */
2753 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2754 NWidget(NWID_HORIZONTAL),
2755 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2756 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2757 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2758 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2759 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2760 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2761 EndContainer(),
2762 NWidget(NWID_HORIZONTAL),
2763 NWidget(WWT_PANEL, COLOUR_GREY),
2764 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2765 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
2766 EndContainer(),
2767 EndContainer(),
2768 NWidget(NWID_VERTICAL),
2769 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
2770 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2771 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2772 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2773 EndContainer(),
2774 /* For trains only, 'ignore signal' button. */
2775 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18),
2776 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2777 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2778 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2779 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18),
2780 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2781 EndContainer(),
2782 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2783 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2784 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2785 EndContainer(),
2786 EndContainer(),
2787 NWidget(NWID_HORIZONTAL),
2788 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2789 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2790 EndContainer(),
2793 /** Vehicle view window descriptor for all vehicles but trains. */
2794 static WindowDesc _vehicle_view_desc(
2795 WDP_AUTO, "view_vehicle", 250, 116,
2796 WC_VEHICLE_VIEW, WC_NONE,
2798 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2802 * Vehicle view window descriptor for trains. Only minimum_height and
2803 * default_height are different for train view.
2805 static WindowDesc _train_view_desc(
2806 WDP_AUTO, "view_vehicle_train", 250, 134,
2807 WC_VEHICLE_VIEW, WC_NONE,
2809 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2813 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2814 using them for array indexing in a number of places here. */
2815 assert_compile(VEH_TRAIN == 0);
2816 assert_compile(VEH_ROAD == 1);
2817 assert_compile(VEH_SHIP == 2);
2818 assert_compile(VEH_AIRCRAFT == 3);
2820 /** Zoom levels for vehicle views indexed by vehicle type. */
2821 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2822 ZOOM_LVL_TRAIN,
2823 ZOOM_LVL_ROADVEH,
2824 ZOOM_LVL_SHIP,
2825 ZOOM_LVL_AIRCRAFT,
2828 /* Constants for geometry of vehicle view viewport */
2829 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2830 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2831 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2833 /** Command indices for the _vehicle_command_translation_table. */
2834 enum VehicleCommandTranslation {
2835 VCT_CMD_START_STOP = 0,
2836 VCT_CMD_CLONE_VEH,
2837 VCT_CMD_TURN_AROUND,
2840 /** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
2841 static const uint32 _vehicle_command_translation_table[][4] = {
2842 { // VCT_CMD_START_STOP
2843 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
2844 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
2845 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
2846 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
2848 { // VCT_CMD_CLONE_VEH
2849 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
2850 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
2851 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
2852 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
2854 { // VCT_CMD_TURN_AROUND
2855 CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
2856 CMD_TURN_ROADVEH | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
2857 0xffffffff, // invalid for ships
2858 0xffffffff // invalid for aircrafts
2863 * This is the Callback method after attempting to start/stop a vehicle
2864 * @param result the result of the start/stop command
2865 * @param tile unused
2866 * @param p1 vehicle ID
2867 * @param p2 unused
2869 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2871 if (result.Failed()) return;
2873 const Vehicle *v = Vehicle::GetIfValid(p1);
2874 if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2876 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2877 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2878 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2882 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2883 * @param v Vehicle to start/stop
2884 * @param texteffect Should a texteffect be shown?
2886 void StartStopVehicle(const Vehicle *v, bool texteffect)
2888 assert(v->IsPrimaryVehicle());
2889 DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr);
2892 /** Checks whether the vehicle may be refitted at the moment.*/
2893 static bool IsVehicleRefitable(const Vehicle *v)
2895 if (!v->IsStoppedInDepot()) return false;
2897 do {
2898 if (IsEngineRefittable(v->engine_type)) return true;
2899 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
2901 return false;
2904 /** Window manager class for viewing a vehicle. */
2905 struct VehicleViewWindow : Window {
2906 private:
2907 /** Display planes available in the vehicle view window. */
2908 enum PlaneSelections {
2909 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2910 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2912 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2913 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2915 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2916 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2920 * Display a plane in the window.
2921 * @param plane Plane to show.
2923 void SelectPlane(PlaneSelections plane)
2925 switch (plane) {
2926 case SEL_DC_GOTO_DEPOT:
2927 case SEL_DC_CLONE:
2928 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2929 break;
2931 case SEL_RT_REFIT:
2932 case SEL_RT_TURN_AROUND:
2933 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2934 break;
2936 default:
2937 NOT_REACHED();
2941 public:
2942 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2944 this->flags |= WF_DISABLE_VP_SCROLL;
2945 this->CreateNestedTree();
2947 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2948 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2949 SPR_SEND_TRAIN_TODEPOT,
2950 SPR_SEND_ROADVEH_TODEPOT,
2951 SPR_SEND_SHIP_TODEPOT,
2952 SPR_SEND_AIRCRAFT_TODEPOT,
2954 const Vehicle *v = Vehicle::Get(window_number);
2955 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2957 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2958 static const SpriteID vehicle_view_clone_sprites[] = {
2959 SPR_CLONE_TRAIN,
2960 SPR_CLONE_ROADVEH,
2961 SPR_CLONE_SHIP,
2962 SPR_CLONE_AIRCRAFT,
2964 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2966 switch (v->type) {
2967 case VEH_TRAIN:
2968 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2969 break;
2971 case VEH_ROAD:
2972 break;
2974 case VEH_SHIP:
2975 case VEH_AIRCRAFT:
2976 this->SelectPlane(SEL_RT_REFIT);
2977 break;
2979 default: NOT_REACHED();
2981 this->FinishInitNested(window_number);
2982 this->owner = v->owner;
2983 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2985 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
2986 this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
2987 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2988 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2989 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2990 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2991 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2994 ~VehicleViewWindow()
2996 if (this->window_number != INVALID_VEHICLE) {
2997 const Vehicle *v = Vehicle::Get(this->window_number);
2998 MarkAllRoutePathsDirty(v);
2999 MarkAllRouteStepsDirty(v);
3001 DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
3002 DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
3003 DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
3004 DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
3005 DeleteWindowById(WC_VEHICLE_TRIP_HISTORY, this->window_number, false);
3008 virtual void OnFocus(Window *previously_focused_window)
3010 if (HasFocusedVehicleChanged(this->window_number, previously_focused_window)) {
3011 if (this->window_number != INVALID_VEHICLE) {
3012 const Vehicle *v = Vehicle::Get(this->window_number);
3013 MarkAllRoutePathsDirty(v);
3014 MarkAllRouteStepsDirty(v);
3019 virtual void OnFocusLost(Window *newly_focused_window)
3021 if (HasFocusedVehicleChanged(this->window_number, newly_focused_window)) {
3022 if (this->window_number != INVALID_VEHICLE) {
3023 const Vehicle *v = Vehicle::Get(this->window_number);
3024 MarkAllRoutePathsDirty(v);
3025 MarkAllRouteStepsDirty(v);
3030 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
3032 const Vehicle *v = Vehicle::Get(this->window_number);
3033 switch (widget) {
3034 case WID_VV_START_STOP:
3035 size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
3036 break;
3038 case WID_VV_FORCE_PROCEED:
3039 if (v->type != VEH_TRAIN) {
3040 size->height = 0;
3041 size->width = 0;
3043 break;
3045 case WID_VV_VIEWPORT:
3046 size->width = VV_INITIAL_VIEWPORT_WIDTH;
3047 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
3048 break;
3052 virtual void OnPaint()
3054 const Vehicle *v = Vehicle::Get(this->window_number);
3055 bool is_localcompany = v->owner == _local_company;
3056 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
3058 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
3059 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
3060 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
3062 if (v->type == VEH_TRAIN) {
3063 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
3064 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
3065 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
3068 this->DrawWidgets();
3071 virtual void SetStringParameters(int widget) const
3073 if (widget != WID_VV_CAPTION) return;
3075 const Vehicle *v = Vehicle::Get(this->window_number);
3076 SetDParam(0, v->index);
3079 virtual void DrawWidget(const Rect &r, int widget) const
3081 if (widget != WID_VV_START_STOP) return;
3083 const Vehicle *v = Vehicle::Get(this->window_number);
3084 StringID str;
3085 if (v->vehstatus & VS_CRASHED) {
3086 str = STR_VEHICLE_STATUS_CRASHED;
3087 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
3088 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
3089 } else if (v->vehstatus & VS_STOPPED) {
3090 if (v->type == VEH_TRAIN) {
3091 if (v->cur_speed == 0) {
3092 if (Train::From(v)->gcache.cached_power == 0) {
3093 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
3094 } else {
3095 str = STR_VEHICLE_STATUS_STOPPED;
3097 } else {
3098 SetDParam(0, v->GetDisplaySpeed());
3099 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
3101 } else { // no train
3102 str = STR_VEHICLE_STATUS_STOPPED;
3104 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
3105 str = HasBit(Train::From(v)->flags, VRF_WAITING_RESTRICTION) ? STR_VEHICLE_STATUS_TRAIN_STUCK_WAIT_RESTRICTION : STR_VEHICLE_STATUS_TRAIN_STUCK;
3106 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
3107 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
3108 } else { // vehicle is in a "normal" state, show current order
3109 int next_depot_index = -1;
3111 if (v->GetNumOrders() > 0 && (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT))) {
3113 for (int i = 0; i < v->GetNumOrders(); ++i) {
3114 Order* order = v->GetOrder(i);
3116 bool isRegularOrder = (order->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) != 0;
3117 bool isDepotOrder = order->GetType() == OT_GOTO_DEPOT;
3119 if (isRegularOrder && isDepotOrder) {
3120 if (i >= v->cur_implicit_order_index) {
3121 next_depot_index = i;
3122 break;
3124 else if (next_depot_index < 0) {
3125 next_depot_index = i;
3131 if (next_depot_index >= 0) {
3132 SetDParam(0, v->type);
3133 SetDParam(1, v->GetOrder(next_depot_index)->GetDestination());
3134 SetDParam(2, v->GetDisplaySpeed());
3135 if (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT)) {
3136 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
3137 } else {
3138 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
3140 } else {
3141 switch (v->current_order.GetType()) {
3142 case OT_GOTO_STATION: {
3143 SetDParam(0, v->current_order.GetDestination());
3144 SetDParam(1, v->GetDisplaySpeed());
3145 str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
3146 break;
3149 case OT_GOTO_DEPOT: {
3150 SetDParam(0, v->type);
3151 SetDParam(1, v->current_order.GetDestination());
3152 SetDParam(2, v->GetDisplaySpeed());
3153 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
3154 /* This case *only* happens when multiple nearest depot orders
3155 * follow each other (including an order list only one order: a
3156 * nearest depot order) and there are no reachable depots.
3157 * It is primarily to guard for the case that there is no
3158 * depot with index 0, which would be used as fallback for
3159 * evaluating the string in the status bar. */
3160 str = STR_EMPTY;
3162 else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
3163 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
3165 else {
3166 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
3168 break;
3171 case OT_LOADING:
3172 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
3173 break;
3175 case OT_GOTO_WAYPOINT: {
3176 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
3177 SetDParam(0, v->current_order.GetDestination());
3178 str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
3179 SetDParam(1, v->GetDisplaySpeed());
3180 break;
3183 case OT_LEAVESTATION:
3184 if (v->type != VEH_AIRCRAFT) {
3185 str = STR_VEHICLE_STATUS_LEAVING;
3186 break;
3188 FALLTHROUGH;
3189 default:
3190 if (v->GetNumManualOrders() == 0) {
3191 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
3192 SetDParam(0, v->GetDisplaySpeed());
3194 else {
3195 str = STR_EMPTY;
3197 break;
3202 /* Draw the flag plus orders. */
3203 bool rtl = (_current_text_dir == TD_RTL);
3204 uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
3205 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
3206 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
3207 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
3208 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
3209 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
3210 DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
3211 DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
3214 virtual void OnClick(Point pt, int widget, int click_count)
3216 const Vehicle *v = Vehicle::Get(this->window_number);
3218 switch (widget) {
3219 case WID_VV_START_STOP: // start stop
3220 if (_ctrl_pressed) {
3221 /* Scroll to current order destination */
3222 TileIndex tile = v->current_order.GetLocation(v);
3223 if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
3224 } else {
3225 /* Start/Stop */
3226 StartStopVehicle(v, false);
3228 break;
3229 case WID_VV_CENTER_MAIN_VIEW: {// center main view
3230 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
3231 /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
3232 if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
3233 mainwindow->viewport->follow_vehicle = v->index;
3234 } else {
3235 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
3237 break;
3240 case WID_VV_GOTO_DEPOT: // goto hangar
3241 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
3242 break;
3243 case WID_VV_REFIT: // refit
3244 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
3245 break;
3246 case WID_VV_SHOW_ORDERS: // show orders
3247 if (_ctrl_pressed) {
3248 ShowTimetableWindow(v);
3249 } else {
3250 ShowOrdersWindow(v);
3252 break;
3253 case WID_VV_SHOW_DETAILS: // show details
3254 ShowVehicleDetailsWindow(v);
3255 break;
3256 case WID_VV_CLONE: // clone vehicle
3257 /* Suppress the vehicle GUI when share-cloning.
3258 * There is no point to it except for starting the vehicle.
3259 * For starting the vehicle the player has to open the depot GUI, which is
3260 * most likely already open, but is also visible in the vehicle viewport. */
3261 DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
3262 _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
3263 _ctrl_pressed ? nullptr : CcCloneVehicle);
3264 break;
3265 case WID_VV_TURN_AROUND: // turn around
3266 assert(v->IsGroundVehicle());
3267 DoCommandP(v->tile, v->index, 0,
3268 _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
3269 break;
3270 case WID_VV_FORCE_PROCEED: // force proceed
3271 assert(v->type == VEH_TRAIN);
3272 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
3273 break;
3277 virtual void OnResize()
3279 if (this->viewport != nullptr) {
3280 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
3281 nvp->UpdateViewportCoordinates(this);
3285 virtual void OnTick()
3287 const Vehicle *v = Vehicle::Get(this->window_number);
3288 bool veh_stopped = v->IsStoppedInDepot();
3290 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
3291 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
3293 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
3294 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
3295 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
3296 this->SelectPlane(plane);
3297 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
3299 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
3300 if (v->IsGroundVehicle()) {
3301 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
3302 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
3303 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
3304 this->SelectPlane(plane);
3305 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
3311 * Some data on this window has become invalid.
3312 * @param data Information about the changed data.
3313 * @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.
3315 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
3317 if (data == VIWD_AUTOREPLACE) {
3318 /* Autoreplace replaced the vehicle.
3319 * Nothing to do for this window. */
3320 return;
3324 virtual bool IsNewGRFInspectable() const
3326 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3329 virtual void ShowNewGRFInspectWindow() const
3331 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3336 /** Shows the vehicle view window of the given vehicle. */
3337 void ShowVehicleViewWindow(const Vehicle *v)
3339 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
3343 * Dispatch a "vehicle selected" event if any window waits for it.
3344 * @param v selected vehicle;
3345 * @return did any window accept vehicle selection?
3347 bool VehicleClicked(const Vehicle *v)
3349 assert(v != nullptr);
3350 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3352 v = v->First();
3353 if (!v->IsPrimaryVehicle()) return false;
3355 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
3358 void StopGlobalFollowVehicle(const Vehicle *v)
3360 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
3361 if (w != nullptr && w->viewport->follow_vehicle == v->index) {
3362 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
3363 w->viewport->follow_vehicle = INVALID_VEHICLE;
3369 * This is the Callback method after the construction attempt of a primary vehicle
3370 * @param result indicates completion (or not) of the operation
3371 * @param tile unused
3372 * @param p1 unused
3373 * @param p2 unused
3375 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
3377 if (result.Failed()) return;
3379 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
3380 ShowVehicleViewWindow(v);
3384 * Get the width of a vehicle (part) in pixels.
3385 * @param v Vehicle to get the width for.
3386 * @return Width of the vehicle.
3388 int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
3390 switch (v->type) {
3391 case VEH_TRAIN:
3392 return Train::From(v)->GetDisplayImageWidth();
3394 case VEH_ROAD:
3395 return RoadVehicle::From(v)->GetDisplayImageWidth();
3397 default:
3398 bool rtl = _current_text_dir == TD_RTL;
3399 VehicleSpriteSeq seq;
3400 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3401 Rect16 rec = seq.GetBounds();
3402 return UnScaleGUI(rec.right - rec.left + 1);
3407 * Get the width of a vehicle (including all parts of the consist) in pixels.
3408 * @param v Vehicle to get the width for.
3409 * @return Width of the vehicle.
3411 int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
3413 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
3414 int vehicle_width = 0;
3415 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
3416 vehicle_width += GetSingleVehicleWidth(u, image_type);
3418 return vehicle_width;
3419 } else {
3420 return GetSingleVehicleWidth(v, image_type);
3425 * Set the mouse cursor to look like a vehicle.
3426 * @param v Vehicle
3427 * @param image_type Type of vehicle image to use.
3429 void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
3431 bool rtl = _current_text_dir == TD_RTL;
3433 _cursor.sprite_count = 0;
3434 int total_width = 0;
3435 for (; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
3436 if (total_width >= 2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH) break;
3438 PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
3439 VehicleSpriteSeq seq;
3440 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3442 if (_cursor.sprite_count + seq.count > lengthof(_cursor.sprite_seq)) break;
3444 for (uint i = 0; i < seq.count; ++i) {
3445 PaletteID pal2 = (v->vehstatus & VS_CRASHED) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
3446 _cursor.sprite_seq[_cursor.sprite_count].sprite = seq.seq[i].sprite;
3447 _cursor.sprite_seq[_cursor.sprite_count].pal = pal2;
3448 _cursor.sprite_pos[_cursor.sprite_count].x = rtl ? -total_width : total_width;
3449 _cursor.sprite_pos[_cursor.sprite_count].y = 0;
3450 _cursor.sprite_count++;
3453 total_width += GetSingleVehicleWidth(v, image_type);
3456 int offs = ((int)VEHICLEINFO_FULL_VEHICLE_WIDTH - total_width) / 2;
3457 if (rtl) offs = -offs;
3458 for (uint i = 0; i < _cursor.sprite_count; ++i) {
3459 _cursor.sprite_pos[i].x += offs;
3462 UpdateCursorSize();