Add non-animated SSSE3 blitter
[openttd/fttd.git] / src / vehicle_gui.cpp
blobbd7d77034b0416fdb3e146a30ad502c95abef16b
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 "group_gui.h"
26 #include "strings_func.h"
27 #include "vehicle_func.h"
28 #include "autoreplace_gui.h"
29 #include "string_func.h"
30 #include "widgets/dropdown_func.h"
31 #include "timetable.h"
32 #include "articulated_vehicles.h"
33 #include "spritecache.h"
34 #include "core/geometry_func.hpp"
35 #include "company_base.h"
36 #include "engine_func.h"
37 #include "station_base.h"
38 #include "tilehighlight_func.h"
39 #include "zoom_func.h"
42 Sorting _sorting;
44 static GUIVehicleList::SortFunction VehicleNumberSorter;
45 static GUIVehicleList::SortFunction VehicleNameSorter;
46 static GUIVehicleList::SortFunction VehicleAgeSorter;
47 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
48 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
49 static GUIVehicleList::SortFunction VehicleCargoSorter;
50 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
51 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
52 static GUIVehicleList::SortFunction VehicleModelSorter;
53 static GUIVehicleList::SortFunction VehicleValueSorter;
54 static GUIVehicleList::SortFunction VehicleLengthSorter;
55 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
56 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
58 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
59 &VehicleNumberSorter,
60 &VehicleNameSorter,
61 &VehicleAgeSorter,
62 &VehicleProfitThisYearSorter,
63 &VehicleProfitLastYearSorter,
64 &VehicleCargoSorter,
65 &VehicleReliabilitySorter,
66 &VehicleMaxSpeedSorter,
67 &VehicleModelSorter,
68 &VehicleValueSorter,
69 &VehicleLengthSorter,
70 &VehicleTimeToLiveSorter,
71 &VehicleTimetableDelaySorter,
74 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
75 STR_SORT_BY_NUMBER,
76 STR_SORT_BY_NAME,
77 STR_SORT_BY_AGE,
78 STR_SORT_BY_PROFIT_THIS_YEAR,
79 STR_SORT_BY_PROFIT_LAST_YEAR,
80 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
81 STR_SORT_BY_RELIABILITY,
82 STR_SORT_BY_MAX_SPEED,
83 STR_SORT_BY_MODEL,
84 STR_SORT_BY_VALUE,
85 STR_SORT_BY_LENGTH,
86 STR_SORT_BY_LIFE_TIME,
87 STR_SORT_BY_TIMETABLE_DELAY,
88 INVALID_STRING_ID
91 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
92 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
93 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
94 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
95 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
98 void BaseVehicleListWindow::BuildVehicleList()
100 if (!this->vehicles.NeedRebuild()) return;
102 DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
104 GenerateVehicleSortList(&this->vehicles, this->vli);
106 uint unitnumber = 0;
107 for (const Vehicle **v = this->vehicles.Begin(); v != this->vehicles.End(); v++) {
108 unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
111 /* Because 111 is much less wide than e.g. 999 we use the
112 * wider numbers to determine the width instead of just
113 * the random number that it seems to be. */
114 if (unitnumber >= 1000) {
115 this->unitnumber_digits = 4;
116 } else if (unitnumber >= 100) {
117 this->unitnumber_digits = 3;
118 } else {
119 this->unitnumber_digits = 2;
122 this->vehicles.RebuildDone();
123 this->vscroll->SetCount(this->vehicles.Length());
127 * Compute the size for the Action dropdown.
128 * @param show_autoreplace If true include the autoreplace item.
129 * @param show_group If true include group-related stuff.
130 * @return Required size.
132 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
134 Dimension d = {0, 0};
136 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
137 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
138 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
140 if (show_group) {
141 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
142 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
145 return d;
149 * Display the Action dropdown window.
150 * @param show_autoreplace If true include the autoreplace item.
151 * @param show_group If true include group-related stuff.
152 * @return Itemlist for dropdown
154 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
156 DropDownList *list = new DropDownList();
158 if (show_autoreplace) *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false);
159 *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false);
160 *list->Append() = new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false);
162 if (show_group) {
163 *list->Append() = new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false);
164 *list->Append() = new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false);
167 return list;
170 /* cached values for VehicleNameSorter to spare many GetString() calls */
171 static const Vehicle *_last_vehicle[2] = { NULL, NULL };
173 void BaseVehicleListWindow::SortVehicleList()
175 if (this->vehicles.Sort()) return;
177 /* invalidate cached values for name sorter - vehicle names could change */
178 _last_vehicle[0] = _last_vehicle[1] = NULL;
181 void DepotSortList(VehicleList *list)
183 if (list->Length() < 2) return;
184 QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
187 /** draw the vehicle profit button in the vehicle list window. */
188 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
190 SpriteID spr;
192 /* draw profit-based coloured icons */
193 if (v->age <= VEHICLE_PROFIT_MIN_AGE) {
194 spr = SPR_PROFIT_NA;
195 } else if (v->GetDisplayProfitLastYear() < 0) {
196 spr = SPR_PROFIT_NEGATIVE;
197 } else if (v->GetDisplayProfitLastYear() < VEHICLE_PROFIT_THRESHOLD) {
198 spr = SPR_PROFIT_SOME;
199 } else {
200 spr = SPR_PROFIT_LOT;
202 DrawSprite(spr, PAL_NONE, x, y);
205 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
206 static const uint MAX_REFIT_CYCLE = 256;
209 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
210 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
211 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
212 * @param v_from the vehicle to match the subtype from
213 * @param v_for the vehicle to get the subtype for
214 * @param dest_cargo_type Destination cargo type.
215 * @return the best sub type
217 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
219 v_from = v_from->GetFirstEnginePart();
220 v_for = v_for->GetFirstEnginePart();
222 /* Create a list of subtypes used by the various parts of v_for */
223 static SmallVector<StringID, 4> subtypes;
224 subtypes.Clear();
225 for (; v_from != NULL; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : NULL) {
226 const Engine *e_from = v_from->GetEngine();
227 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
228 subtypes.Include(GetCargoSubtypeText(v_from));
231 byte ret_refit_cyc = 0;
232 bool success = false;
233 if (subtypes.Length() > 0) {
234 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
235 for (Vehicle *v = v_for; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
236 const Engine *e = v->GetEngine();
237 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
238 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
240 CargoID old_cargo_type = v->cargo_type;
241 byte old_cargo_subtype = v->cargo_subtype;
243 /* Set the 'destination' cargo */
244 v->cargo_type = dest_cargo_type;
246 /* Cycle through the refits */
247 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
248 v->cargo_subtype = refit_cyc;
250 /* Make sure we don't pick up anything cached. */
251 v->First()->InvalidateNewGRFCache();
252 v->InvalidateNewGRFCache();
254 StringID subtype = GetCargoSubtypeText(v);
255 if (subtype == STR_EMPTY) break;
257 if (!subtypes.Contains(subtype)) continue;
259 /* We found something matching. */
260 ret_refit_cyc = refit_cyc;
261 success = true;
262 break;
265 /* Reset the vehicle's cargo type */
266 v->cargo_type = old_cargo_type;
267 v->cargo_subtype = old_cargo_subtype;
269 /* Make sure we don't taint the vehicle. */
270 v->First()->InvalidateNewGRFCache();
271 v->InvalidateNewGRFCache();
273 if (success) break;
277 return ret_refit_cyc;
280 /** Option to refit a vehicle chain */
281 struct RefitOption {
282 CargoID cargo; ///< Cargo to refit to
283 byte subtype; ///< Subcargo to use
284 StringID string; ///< GRF-local String to display for the cargo
287 * Inequality operator for #RefitOption.
288 * @param other Compare to this #RefitOption.
289 * @return True if both #RefitOption are different.
291 inline bool operator != (const RefitOption &other) const
293 return other.cargo != this->cargo || other.string != this->string;
297 * Equality operator for #RefitOption.
298 * @param other Compare to this #RefitOption.
299 * @return True if both #RefitOption are equal.
301 inline bool operator == (const RefitOption &other) const
303 return other.cargo == this->cargo && other.string == this->string;
307 typedef SmallVector<RefitOption, 32> SubtypeList; ///< List of refit subtypes associated to a cargo.
310 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
311 * @param list List of subtype options for each (sorted) cargo.
312 * @param sel Selected refit cargo-type in the window
313 * @param pos Position of the selected item in caller widow
314 * @param rows Number of rows(capacity) in caller window
315 * @param delta Step height in caller window
316 * @param r Rectangle of the matrix widget.
318 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
320 uint y = r.top + WD_MATRIX_TOP;
321 uint current = 0;
323 bool rtl = _current_text_dir == TD_RTL;
324 uint iconwidth = max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
325 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
326 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
328 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
329 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
330 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
332 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
333 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
335 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
336 for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
337 for (uint j = 0; current < pos + rows && j < list[i].Length(); j++) {
338 const RefitOption &refit = list[i][j];
340 /* Hide subtypes if sel[0] does not match */
341 if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
343 /* Refit options with a position smaller than pos don't have to be drawn. */
344 if (current < pos) {
345 current++;
346 continue;
349 if (list[i].Length() > 1) {
350 if (refit.subtype != 0xFF) {
351 /* Draw tree lines */
352 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
353 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].Length() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
354 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
355 } else {
356 /* Draw expand/collapse icon */
357 DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
361 TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
362 /* Get the cargo name. */
363 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
364 SetDParam(1, refit.string);
365 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
367 y += delta;
368 current++;
373 /** Refit cargo window. */
374 struct RefitWindow : public Window {
375 int sel[2]; ///< Index in refit options, sel[0] == -1 if nothing is selected.
376 RefitOption *cargo; ///< Refit option selected by #sel.
377 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
378 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
379 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
380 Scrollbar *vscroll; ///< The main scrollbar.
381 Scrollbar *hscroll; ///< Only used for long vehicles.
382 int vehicle_width; ///< Width of the vehicle being drawn.
383 int sprite_left; ///< Left position of the vehicle sprite.
384 int sprite_right; ///< Right position of the vehicle sprite.
385 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
386 int click_x; ///< Position of the first click while dragging.
387 VehicleID selected_vehicle; ///< First vehicle in the current selection.
388 uint8 num_vehicles; ///< Number of selected vehicles.
389 bool auto_refit; ///< Select cargo for auto-refitting.
392 * Collects all (cargo, subcargo) refit options of a vehicle chain.
394 void BuildRefitList()
396 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
397 Vehicle *v = Vehicle::Get(this->window_number);
399 /* Check only the selected vehicles. */
400 VehicleSet vehicles_to_refit;
401 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
403 do {
404 if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
405 const Engine *e = v->GetEngine();
406 uint32 cmask = e->info.refit_mask;
407 byte callback_mask = e->info.callback_mask;
409 /* Skip this engine if it does not carry anything */
410 if (!e->CanCarryCargo()) continue;
411 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
412 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
414 /* Loop through all cargoes in the refit mask */
415 int current_index = 0;
416 const CargoSpec *cs;
417 FOR_ALL_SORTED_CARGOSPECS(cs) {
418 CargoID cid = cs->Index();
419 /* Skip cargo type if it's not listed */
420 if (!HasBit(cmask, cid)) {
421 current_index++;
422 continue;
425 bool first_vehicle = this->list[current_index].Length() == 0;
426 if (first_vehicle) {
427 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
428 RefitOption *option = this->list[current_index].Append();
429 option->cargo = cid;
430 option->subtype = 0xFF;
431 option->string = STR_EMPTY;
434 /* Check the vehicle's callback mask for cargo suffixes.
435 * This is not supported for ordered refits, since subtypes only have a meaning
436 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
437 * autoreplace, autorenew, clone, order restoration, ... */
438 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
439 /* Make a note of the original cargo type. It has to be
440 * changed to test the cargo & subtype... */
441 CargoID temp_cargo = v->cargo_type;
442 byte temp_subtype = v->cargo_subtype;
444 v->cargo_type = cid;
446 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
447 v->cargo_subtype = refit_cyc;
449 /* Make sure we don't pick up anything cached. */
450 v->First()->InvalidateNewGRFCache();
451 v->InvalidateNewGRFCache();
453 StringID subtype = GetCargoSubtypeText(v);
455 if (first_vehicle) {
456 /* Append new subtype (don't add duplicates though) */
457 if (subtype == STR_EMPTY) break;
459 RefitOption option;
460 option.cargo = cid;
461 option.subtype = refit_cyc;
462 option.string = subtype;
463 this->list[current_index].Include(option);
464 } else {
465 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
466 if (subtype == STR_EMPTY) {
467 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
468 SubtypeList &l = this->list[current_index];
469 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
470 for (uint i = 1; i < l.Length(); i++) {
471 if (l[i].subtype >= refit_cyc) {
472 l.Resize(i);
473 break;
476 break;
477 } else {
478 /* Check whether the subtype matches with the subtype of earlier vehicles. */
479 uint pos = 1;
480 SubtypeList &l = this->list[current_index];
481 while (pos < l.Length() && l[pos].subtype != refit_cyc) pos++;
482 if (pos < l.Length() && l[pos].string != subtype) {
483 /* String mismatch, remove item keeping the order */
484 l.ErasePreservingOrder(pos);
490 /* Reset the vehicle's cargo type */
491 v->cargo_type = temp_cargo;
492 v->cargo_subtype = temp_subtype;
494 /* And make sure we haven't tainted the cache */
495 v->First()->InvalidateNewGRFCache();
496 v->InvalidateNewGRFCache();
498 current_index++;
500 } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
504 * Refresh scrollbar after selection changed
506 void RefreshScrollbar()
508 uint scroll_row = 0;
509 uint row = 0;
511 for (uint i = 0; i < NUM_CARGO; i++) {
512 for (uint j = 0; j < this->list[i].Length(); j++) {
513 const RefitOption &refit = this->list[i][j];
515 /* Hide subtypes if sel[0] does not match */
516 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
518 if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
520 row++;
524 this->vscroll->SetCount(row);
525 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
529 * Select a row.
530 * @param click_row Clicked row
532 void SetSelection(uint click_row)
534 uint row = 0;
536 for (uint i = 0; i < NUM_CARGO; i++) {
537 for (uint j = 0; j < this->list[i].Length(); j++) {
538 const RefitOption &refit = this->list[i][j];
540 /* Hide subtypes if sel[0] does not match */
541 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
543 if (row == click_row) {
544 this->sel[0] = i;
545 this->sel[1] = j;
546 return;
549 row++;
553 this->sel[0] = -1;
554 this->sel[1] = 0;
558 * Gets the #RefitOption placed in the selected index.
559 * @return Pointer to the #RefitOption currently in use.
561 RefitOption *GetRefitOption()
563 if (this->sel[0] < 0) return NULL;
565 SubtypeList &l = this->list[this->sel[0]];
566 if ((uint)this->sel[1] >= l.Length()) return NULL;
568 return &l[this->sel[1]];
571 RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
573 this->sel[0] = -1;
574 this->sel[1] = 0;
575 this->auto_refit = auto_refit;
576 this->order = order;
577 this->CreateNestedTree();
579 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
580 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
581 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
582 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
583 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
584 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
585 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
586 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
587 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
589 this->FinishInitNested(v->index);
590 this->owner = v->owner;
592 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
595 virtual void OnInit()
597 if (this->cargo != NULL) {
598 /* Store the RefitOption currently in use. */
599 RefitOption current_refit_option = *(this->cargo);
601 /* Rebuild the refit list */
602 this->BuildRefitList();
603 this->sel[0] = -1;
604 this->sel[1] = 0;
605 this->cargo = NULL;
606 for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
607 for (uint j = 0; j < list[i].Length(); j++) {
608 if (list[i][j] == current_refit_option) {
609 this->sel[0] = i;
610 this->sel[1] = j;
611 this->cargo = &list[i][j];
612 break;
617 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
618 this->RefreshScrollbar();
619 } else {
620 /* Rebuild the refit list */
621 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
625 virtual void OnPaint()
627 /* Determine amount of items for scroller. */
628 if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
630 /* Calculate sprite position. */
631 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
632 int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
633 this->sprite_left = vehicle_panel_display->pos_x;
634 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
635 if (_current_text_dir == TD_RTL) {
636 this->sprite_right -= sprite_width;
637 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
638 } else {
639 this->sprite_left += sprite_width;
640 this->vehicle_margin = sprite_left;
643 this->DrawWidgets();
646 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
648 switch (widget) {
649 case WID_VR_MATRIX:
650 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
651 size->height = resize->height * 8;
652 break;
654 case WID_VR_VEHICLE_PANEL_DISPLAY:
655 size->height = GetVehicleHeight(Vehicle::Get(this->window_number)->type);
656 break;
658 case WID_VR_INFO:
659 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
660 break;
664 virtual void SetStringParameters(int widget) const
666 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
670 * Gets the #StringID to use for displaying capacity.
671 * @param Cargo and cargo subtype to check for capacity.
672 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
673 * @post String parameters have been set.
675 StringID GetCapacityString(RefitOption *option) const
677 assert(_current_company == _local_company);
678 Vehicle *v = Vehicle::Get(this->window_number);
679 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
680 this->num_vehicles << 16, DC_QUERY_COST, GetCmdRefitVeh(v->type));
682 if (cost.Failed()) return INVALID_STRING_ID;
684 SetDParam(0, option->cargo);
685 SetDParam(1, _returned_refit_capacity);
687 Money money = cost.GetCost();
688 if (_returned_mail_refit_capacity > 0) {
689 SetDParam(2, CT_MAIL);
690 SetDParam(3, _returned_mail_refit_capacity);
691 if (money <= 0) {
692 SetDParam(4, -money);
693 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
694 } else {
695 SetDParam(4, money);
696 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
698 } else {
699 if (money <= 0) {
700 SetDParam(2, -money);
701 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
702 } else {
703 SetDParam(2, money);
704 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
709 virtual void DrawWidget(const Rect &r, int widget) const
711 switch (widget) {
712 case WID_VR_VEHICLE_PANEL_DISPLAY: {
713 Vehicle *v = Vehicle::Get(this->window_number);
714 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
715 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
717 /* Highlight selected vehicles. */
718 if (this->order != INVALID_VEH_ORDER_ID) break;
719 int x = 0;
720 switch (v->type) {
721 case VEH_TRAIN: {
722 VehicleSet vehicles_to_refit;
723 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
725 int left = INT32_MIN;
726 int width = 0;
728 for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
729 /* Start checking. */
730 if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
731 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
732 width = 0;
735 /* Draw a selection. */
736 if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
737 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
738 int current_width = u->GetDisplayImageWidth();
739 width += current_width;
740 x += current_width;
743 int right = Clamp(left + width, 0, r.right);
744 left = max(0, left);
746 if (_current_text_dir == TD_RTL) {
747 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
748 left = right - width;
751 if (left != right) {
752 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + 13, COLOUR_WHITE, FR_BORDERONLY);
755 left = INT32_MIN;
758 int current_width = u->GetDisplayImageWidth();
759 width += current_width;
760 x += current_width;
762 break;
765 default: break;
767 break;
770 case WID_VR_MATRIX:
771 DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
772 break;
774 case WID_VR_INFO:
775 if (this->cargo != NULL) {
776 StringID string = this->GetCapacityString(this->cargo);
777 if (string != INVALID_STRING_ID) {
778 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
779 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
782 break;
787 * Some data on this window has become invalid.
788 * @param data Information about the changed data.
789 * @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.
791 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
793 switch (data) {
794 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
795 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
796 /* Clear the selection. */
797 Vehicle *v = Vehicle::Get(this->window_number);
798 this->selected_vehicle = v->index;
799 this->num_vehicles = UINT8_MAX;
800 /* FALL THROUGH */
803 case 2: { // The vehicle selection has changed; rebuild the entire list.
804 if (!gui_scope) break;
805 this->BuildRefitList();
807 /* The vehicle width has changed too. */
808 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
809 uint max_width = 0;
811 /* Check the width of all cargo information strings. */
812 for (uint i = 0; i < NUM_CARGO; i++) {
813 for (uint j = 0; j < this->list[i].Length(); j++) {
814 StringID string = this->GetCapacityString(&list[i][j]);
815 if (string != INVALID_STRING_ID) {
816 Dimension dim = GetStringBoundingBox(string);
817 max_width = max(dim.width, max_width);
822 if (this->information_width < max_width) {
823 this->information_width = max_width;
824 this->ReInit();
826 /* FALL THROUGH */
829 case 1: // A new cargo has been selected.
830 if (!gui_scope) break;
831 this->cargo = GetRefitOption();
832 this->RefreshScrollbar();
833 break;
837 int GetClickPosition(int click_x)
839 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
840 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
841 click_x -= this->vehicle_margin;
842 if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
844 return click_x;
847 void SetSelectedVehicles(int drag_x)
849 drag_x = GetClickPosition(drag_x);
851 int left_x = min(this->click_x, drag_x);
852 int right_x = max(this->click_x, drag_x);
853 this->num_vehicles = 0;
855 Vehicle *v = Vehicle::Get(this->window_number);
856 /* Find the vehicle part that was clicked. */
857 switch (v->type) {
858 case VEH_TRAIN: {
859 /* Don't select anything if we are not clicking in the vehicle. */
860 if (left_x >= 0) {
861 const Train *u = Train::From(v);
862 bool start_counting = false;
863 for (; u != NULL; u = u->Next()) {
864 int current_width = u->GetDisplayImageWidth();
865 left_x -= current_width;
866 right_x -= current_width;
868 if (left_x < 0 && !start_counting) {
869 this->selected_vehicle = u->index;
870 start_counting = true;
872 /* Count the first vehicle, even if articulated part */
873 this->num_vehicles++;
874 } else if (start_counting && !u->IsArticulatedPart()) {
875 /* Do not count articulated parts */
876 this->num_vehicles++;
879 if (right_x < 0) break;
883 /* If the selection is not correct, clear it. */
884 if (this->num_vehicles != 0) {
885 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
886 break;
888 /* FALL THROUGH */
891 default:
892 /* Clear the selection. */
893 this->selected_vehicle = v->index;
894 this->num_vehicles = UINT8_MAX;
895 break;
899 virtual void OnClick(Point pt, int widget, int click_count)
901 switch (widget) {
902 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
903 if (this->order != INVALID_VEH_ORDER_ID) break;
904 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
905 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
906 this->SetSelectedVehicles(pt.x - nwi->pos_x);
907 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
908 if (!_ctrl_pressed) {
909 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
910 } else {
911 /* The vehicle selection has changed. */
912 this->InvalidateData(2);
914 break;
917 case WID_VR_MATRIX: { // listbox
918 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
919 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
920 this->InvalidateData(1);
922 if (click_count == 1) break;
923 /* FALL THROUGH */
926 case WID_VR_REFIT: // refit button
927 if (this->cargo != NULL) {
928 const Vehicle *v = Vehicle::Get(this->window_number);
930 if (this->order == INVALID_VEH_ORDER_ID) {
931 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
932 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
933 } else {
934 if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) delete this;
937 break;
941 virtual void OnMouseDrag(Point pt, int widget)
943 switch (widget) {
944 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
945 if (this->order != INVALID_VEH_ORDER_ID) break;
946 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
947 this->SetSelectedVehicles(pt.x - nwi->pos_x);
948 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
949 break;
954 virtual void OnDragDrop(Point pt, int widget)
956 switch (widget) {
957 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
958 if (this->order != INVALID_VEH_ORDER_ID) break;
959 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
960 this->SetSelectedVehicles(pt.x - nwi->pos_x);
961 this->InvalidateData(2);
962 break;
967 virtual void OnResize()
969 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
970 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
971 if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
975 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
976 NWidget(NWID_HORIZONTAL),
977 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
978 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
979 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
980 EndContainer(),
981 /* Vehicle display + scrollbar. */
982 NWidget(NWID_VERTICAL),
983 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
984 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
985 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
986 EndContainer(),
987 EndContainer(),
988 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
989 /* Matrix + scrollbar. */
990 NWidget(NWID_HORIZONTAL),
991 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),
992 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
993 EndContainer(),
994 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
995 NWidget(NWID_HORIZONTAL),
996 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
997 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
998 EndContainer(),
1001 static WindowDesc _vehicle_refit_desc(
1002 WDP_AUTO, "view_vehicle_refit", 240, 174,
1003 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1004 WDF_CONSTRUCTION,
1005 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1009 * Show the refit window for a vehicle
1010 * @param *v The vehicle to show the refit window for
1011 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1012 * @param parent the parent window of the refit window
1013 * @param auto_refit Choose cargo for auto-refitting
1015 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1017 DeleteWindowById(WC_VEHICLE_REFIT, v->index);
1018 RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
1019 w->parent = parent;
1022 /** Display list of cargo types of the engine, for the purchase information window */
1023 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1025 /* List of cargo types of this engine */
1026 uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1027 /* List of cargo types available in this climate */
1028 uint32 lmask = _cargo_mask;
1030 /* Draw nothing if the engine is not refittable */
1031 if (HasAtMostOneBit(cmask)) return y;
1033 if (cmask == lmask) {
1034 /* Engine can be refitted to all types in this climate */
1035 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1036 } else {
1037 /* Check if we are able to refit to more cargo types and unable to. If
1038 * so, invert the cargo types to list those that we can't refit to. */
1039 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1040 cmask ^= lmask;
1041 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1042 } else {
1043 SetDParam(0, STR_JUST_CARGO_LIST);
1045 SetDParam(1, cmask);
1048 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1051 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1052 StringID GetCargoSubtypeText(const Vehicle *v)
1054 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1055 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1056 if (cb != CALLBACK_FAILED) {
1057 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1058 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1060 if (cb != CALLBACK_FAILED) {
1061 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1064 return STR_EMPTY;
1067 /** Sort vehicles by their number */
1068 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
1070 return (*a)->unitnumber - (*b)->unitnumber;
1073 /** Sort vehicles by their name */
1074 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
1076 static char last_name[2][64];
1078 if (*a != _last_vehicle[0]) {
1079 _last_vehicle[0] = *a;
1080 SetDParam(0, (*a)->index);
1081 GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
1084 if (*b != _last_vehicle[1]) {
1085 _last_vehicle[1] = *b;
1086 SetDParam(0, (*b)->index);
1087 GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
1090 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1091 return (r != 0) ? r : VehicleNumberSorter(a, b);
1094 /** Sort vehicles by their age */
1095 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
1097 int r = (*a)->age - (*b)->age;
1098 return (r != 0) ? r : VehicleNumberSorter(a, b);
1101 /** Sort vehicles by this year profit */
1102 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1104 int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
1105 return (r != 0) ? r : VehicleNumberSorter(a, b);
1108 /** Sort vehicles by last year profit */
1109 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1111 int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
1112 return (r != 0) ? r : VehicleNumberSorter(a, b);
1115 /** Sort vehicles by their cargo */
1116 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
1118 const Vehicle *v;
1119 CargoArray diff;
1121 /* Append the cargo of the connected waggons */
1122 for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1123 for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1125 int r = 0;
1126 for (CargoID i = 0; i < NUM_CARGO; i++) {
1127 r = diff[i];
1128 if (r != 0) break;
1131 return (r != 0) ? r : VehicleNumberSorter(a, b);
1134 /** Sort vehicles by their reliability */
1135 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
1137 int r = (*a)->reliability - (*b)->reliability;
1138 return (r != 0) ? r : VehicleNumberSorter(a, b);
1141 /** Sort vehicles by their max speed */
1142 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
1144 int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
1145 return (r != 0) ? r : VehicleNumberSorter(a, b);
1148 /** Sort vehicles by model */
1149 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
1151 int r = (*a)->engine_type - (*b)->engine_type;
1152 return (r != 0) ? r : VehicleNumberSorter(a, b);
1155 /** Sort vehicles by their value */
1156 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
1158 const Vehicle *u;
1159 Money diff = 0;
1161 for (u = *a; u != NULL; u = u->Next()) diff += u->value;
1162 for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
1164 int r = ClampToI32(diff);
1165 return (r != 0) ? r : VehicleNumberSorter(a, b);
1168 /** Sort vehicles by their length */
1169 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
1171 int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
1172 return (r != 0) ? r : VehicleNumberSorter(a, b);
1175 /** Sort vehicles by the time they can still live */
1176 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
1178 int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
1179 return (r != 0) ? r : VehicleNumberSorter(a, b);
1182 /** Sort vehicles by the timetable delay */
1183 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
1185 int r = (*a)->lateness_counter - (*b)->lateness_counter;
1186 return (r != 0) ? r : VehicleNumberSorter(a, b);
1189 void InitializeGUI()
1191 MemSetT(&_sorting, 0);
1195 * Assign a vehicle window a new vehicle
1196 * @param window_class WindowClass to search for
1197 * @param from_index the old vehicle ID
1198 * @param to_index the new vehicle ID
1200 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1202 Window *w = FindWindowById(window_class, from_index);
1203 if (w != NULL) {
1204 /* Update window_number */
1205 w->window_number = to_index;
1206 if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
1208 /* Update vehicle drag data */
1209 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1210 _thd.window_number = to_index;
1213 /* Notify the window. */
1214 w->InvalidateData(VIWD_AUTOREPLACE, false);
1219 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1220 * @param from_index the old vehicle ID
1221 * @param to_index the new vehicle ID
1223 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1225 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1226 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1227 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1228 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1229 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1232 static const NWidgetPart _nested_vehicle_list[] = {
1233 NWidget(NWID_HORIZONTAL),
1234 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1235 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1236 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1237 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1238 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1239 EndContainer(),
1241 NWidget(NWID_HORIZONTAL),
1242 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1243 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1244 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
1245 EndContainer(),
1246 EndContainer(),
1248 NWidget(NWID_HORIZONTAL),
1249 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),
1250 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1251 EndContainer(),
1253 NWidget(NWID_HORIZONTAL),
1254 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1255 NWidget(NWID_HORIZONTAL),
1256 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1257 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1258 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1259 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1260 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1261 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1262 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1263 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1264 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1265 EndContainer(),
1266 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1267 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1268 EndContainer(),
1269 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1270 EndContainer(),
1273 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
1275 const Order *order = v->GetOrder(start);
1276 if (order == NULL) return;
1278 int i = 0;
1279 VehicleOrderID oid = start;
1281 do {
1282 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1284 if (order->IsType(OT_GOTO_STATION)) {
1285 SetDParam(0, order->GetDestination());
1286 DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
1288 y += FONT_HEIGHT_SMALL;
1289 if (++i == 4) break;
1292 oid++;
1293 order = order->next;
1294 if (order == NULL) {
1295 order = v->orders.list->GetFirstOrder();
1296 oid = 0;
1298 } while (oid != start);
1302 * Draws an image of a vehicle chain
1303 * @param v Front vehicle
1304 * @param left The minimum horizontal position
1305 * @param right The maximum horizontal position
1306 * @param y Vertical position to draw at
1307 * @param selection Selected vehicle to draw a frame around
1308 * @param skip Number of pixels to skip at the front (for scrolling)
1310 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1312 switch (v->type) {
1313 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1314 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1315 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1316 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1317 default: NOT_REACHED();
1322 * Get the height of a vehicle in the vehicle list GUIs.
1323 * @param type the vehicle type to look at
1324 * @param divisor the resulting height must be dividable by this
1325 * @return the height
1327 uint GetVehicleListHeight(VehicleType type, uint divisor)
1329 /* Name + vehicle + profit */
1330 uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
1331 /* Drawing of the 4 small orders + profit*/
1332 if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
1334 if (divisor == 1) return base;
1336 /* Make sure the height is dividable by divisor */
1337 uint rem = base % divisor;
1338 return base + (rem == 0 ? 0 : divisor - rem);
1342 * Draw all the vehicle list items.
1343 * @param selected_vehicle The vehicle that is to be highlighted.
1344 * @param line_height Height of a single item line.
1345 * @param r Rectangle with edge positions of the matrix widget.
1347 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1349 int left = r.left + WD_MATRIX_LEFT;
1350 int right = r.right - WD_MATRIX_RIGHT;
1351 int width = right - left;
1352 bool rtl = _current_text_dir == TD_RTL;
1354 int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
1355 int text_left = left + (rtl ? 0 : text_offset);
1356 int text_right = right - (rtl ? text_offset : 0);
1358 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1359 int orderlist_left = left + (rtl ? 0 : max(100 + text_offset, width / 2));
1360 int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
1362 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1363 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1365 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1367 int y = r.top;
1368 uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
1369 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1370 const Vehicle *v = this->vehicles[i];
1371 StringID str;
1373 SetDParam(0, v->GetDisplayProfitThisYear());
1374 SetDParam(1, v->GetDisplayProfitLastYear());
1376 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1377 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1379 if (v->name != NULL) {
1380 /* The vehicle got a name so we will print it */
1381 SetDParam(0, v->index);
1382 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1383 } else if (v->group_id != DEFAULT_GROUP) {
1384 /* The vehicle has no name, but is member of a group, so print group name */
1385 SetDParam(0, v->group_id);
1386 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1389 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
1391 if (v->IsChainInDepot()) {
1392 str = STR_BLUE_COMMA;
1393 } else {
1394 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1397 SetDParam(0, v->unitnumber);
1398 DrawString(left, right, y + 2, str);
1400 DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1402 y += line_height;
1407 * Window for the (old) vehicle listing.
1409 * bitmask for w->window_number
1410 * 0-7 CompanyID (owner)
1411 * 8-10 window type (use flags in vehicle_gui.h)
1412 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1413 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1415 struct VehicleListWindow : public BaseVehicleListWindow {
1416 private:
1417 /** Enumeration of planes of the button row at the bottom. */
1418 enum ButtonPlanes {
1419 BP_SHOW_BUTTONS, ///< Show the buttons.
1420 BP_HIDE_BUTTONS, ///< Show the empty panel.
1423 public:
1424 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1426 /* Set up sorting. Make the window-specific _sorting variable
1427 * point to the correct global _sorting struct so we are freed
1428 * from having conditionals during window operation */
1429 switch (this->vli.vtype) {
1430 case VEH_TRAIN: this->sorting = &_sorting.train; break;
1431 case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
1432 case VEH_SHIP: this->sorting = &_sorting.ship; break;
1433 case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
1434 default: NOT_REACHED();
1437 this->CreateNestedTree();
1439 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1441 this->vehicles.SetListing(*this->sorting);
1442 this->vehicles.ForceRebuild();
1443 this->vehicles.NeedResort();
1444 this->BuildVehicleList();
1445 this->SortVehicleList();
1447 /* Set up the window widgets */
1448 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1450 if (this->vli.type == VL_SHARED_ORDERS) {
1451 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1452 } else {
1453 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1456 this->FinishInitNested(window_number);
1457 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1460 ~VehicleListWindow()
1462 *this->sorting = this->vehicles.GetListing();
1465 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1467 switch (widget) {
1468 case WID_VL_LIST:
1469 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1471 switch (this->vli.vtype) {
1472 case VEH_TRAIN:
1473 case VEH_ROAD:
1474 size->height = 6 * resize->height;
1475 break;
1476 case VEH_SHIP:
1477 case VEH_AIRCRAFT:
1478 size->height = 4 * resize->height;
1479 break;
1480 default: NOT_REACHED();
1482 break;
1484 case WID_VL_SORT_ORDER: {
1485 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1486 d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
1487 d.height += padding.height;
1488 *size = maxdim(*size, d);
1489 break;
1492 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1493 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1494 d.height += padding.height;
1495 d.width += padding.width;
1496 *size = maxdim(*size, d);
1497 break;
1502 virtual void SetStringParameters(int widget) const
1504 switch (widget) {
1505 case WID_VL_AVAILABLE_VEHICLES:
1506 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1507 break;
1509 case WID_VL_CAPTION: {
1510 switch (this->vli.type) {
1511 case VL_SHARED_ORDERS: // Shared Orders
1512 if (this->vehicles.Length() == 0) {
1513 /* We can't open this window without vehicles using this order
1514 * and we should close the window when deleting the order. */
1515 NOT_REACHED();
1517 SetDParam(0, this->vscroll->GetCount());
1518 break;
1520 case VL_STANDARD: // Company Name
1521 SetDParam(0, STR_COMPANY_NAME);
1522 SetDParam(1, this->vli.index);
1523 SetDParam(3, this->vscroll->GetCount());
1524 break;
1526 case VL_STATION_LIST: // Station/Waypoint Name
1527 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
1528 SetDParam(1, this->vli.index);
1529 SetDParam(3, this->vscroll->GetCount());
1530 break;
1532 case VL_DEPOT_LIST:
1533 SetDParam(0, STR_DEPOT_CAPTION);
1534 SetDParam(1, this->vli.vtype);
1535 SetDParam(2, this->vli.index);
1536 SetDParam(3, this->vscroll->GetCount());
1537 break;
1538 default: NOT_REACHED();
1540 break;
1545 virtual void DrawWidget(const Rect &r, int widget) const
1547 switch (widget) {
1548 case WID_VL_SORT_ORDER:
1549 /* draw arrow pointing up/down for ascending/descending sorting */
1550 this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1551 break;
1553 case WID_VL_LIST:
1554 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1555 break;
1559 virtual void OnPaint()
1561 this->BuildVehicleList();
1562 this->SortVehicleList();
1564 if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1565 HideDropDownMenu(this);
1568 /* Hide the widgets that we will not use in this window
1569 * Some windows contains actions only fit for the owner */
1570 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1571 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1572 if (plane_to_show != nwi->shown_plane) {
1573 nwi->SetDisplayedPlane(plane_to_show);
1574 nwi->SetDirty(this);
1576 if (this->owner == _local_company) {
1577 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1578 this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
1579 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1580 WID_VL_STOP_ALL,
1581 WID_VL_START_ALL,
1582 WIDGET_LIST_END);
1585 /* Set text of sort by dropdown widget. */
1586 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
1588 this->DrawWidgets();
1591 virtual void OnClick(Point pt, int widget, int click_count)
1593 switch (widget) {
1594 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1595 this->vehicles.ToggleSortOrder();
1596 this->SetDirty();
1597 break;
1599 case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
1600 ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1601 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1602 return;
1604 case WID_VL_LIST: { // Matrix to show vehicles
1605 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1606 if (id_v >= this->vehicles.Length()) return; // click out of list bound
1608 const Vehicle *v = this->vehicles[id_v];
1609 if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
1610 break;
1613 case WID_VL_AVAILABLE_VEHICLES:
1614 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1615 break;
1617 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1618 DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
1619 ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1620 break;
1623 case WID_VL_STOP_ALL:
1624 case WID_VL_START_ALL:
1625 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1626 break;
1630 virtual void OnDropdownSelect(int widget, int index)
1632 switch (widget) {
1633 case WID_VL_SORT_BY_PULLDOWN:
1634 this->vehicles.SetSortType(index);
1635 break;
1636 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1637 assert(this->vehicles.Length() != 0);
1639 switch (index) {
1640 case ADI_REPLACE: // Replace window
1641 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1642 break;
1643 case ADI_SERVICE: // Send for servicing
1644 case ADI_DEPOT: // Send to Depots
1645 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
1646 break;
1648 default: NOT_REACHED();
1650 break;
1651 default: NOT_REACHED();
1653 this->SetDirty();
1656 virtual void OnTick()
1658 if (_pause_mode != PM_UNPAUSED) return;
1659 if (this->vehicles.NeedResort()) {
1660 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1662 DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
1663 this->SetDirty();
1667 virtual void OnResize()
1669 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1673 * Some data on this window has become invalid.
1674 * @param data Information about the changed data.
1675 * @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.
1677 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1679 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1680 /* Needs to be done in command-scope, so everything stays valid */
1681 this->vli.index = GB(data, 0, 20);
1682 this->window_number = this->vli.Pack();
1683 this->vehicles.ForceRebuild();
1684 return;
1687 if (data == 0) {
1688 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1689 this->vehicles.ForceRebuild();
1690 } else {
1691 this->vehicles.ForceResort();
1696 static WindowDesc _vehicle_list_other_desc(
1697 WDP_AUTO, "list_vehicles", 260, 246,
1698 WC_INVALID, WC_NONE,
1700 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1703 static WindowDesc _vehicle_list_train_desc(
1704 WDP_AUTO, "list_vehicles_train", 325, 246,
1705 WC_TRAINS_LIST, WC_NONE,
1707 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1710 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1712 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1714 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1715 if (vehicle_type == VEH_TRAIN) {
1716 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
1717 } else {
1718 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
1719 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
1723 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
1725 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
1726 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
1727 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
1730 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
1731 ShowCompanyGroup(company, vehicle_type);
1732 } else {
1733 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
1737 void ShowVehicleListWindow(const Vehicle *v)
1739 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
1742 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
1744 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
1747 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
1749 uint16 depot_airport_index;
1751 if (vehicle_type == VEH_AIRCRAFT) {
1752 depot_airport_index = GetStationIndex(depot_tile);
1753 } else {
1754 depot_airport_index = GetDepotIndex(depot_tile);
1756 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
1760 /* Unified vehicle GUI - Vehicle Details Window */
1762 assert_compile(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
1763 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
1764 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
1765 assert_compile(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
1767 /** Vehicle details widgets (other than train). */
1768 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
1769 NWidget(NWID_HORIZONTAL),
1770 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1771 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1772 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 */),
1773 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1774 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1775 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1776 EndContainer(),
1777 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
1778 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
1779 NWidget(NWID_HORIZONTAL),
1780 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1781 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1782 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1783 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
1784 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1785 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1786 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1787 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1788 EndContainer(),
1791 /** Train details widgets. */
1792 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
1793 NWidget(NWID_HORIZONTAL),
1794 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1795 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1796 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 */),
1797 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1798 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1799 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1800 EndContainer(),
1801 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
1802 NWidget(NWID_HORIZONTAL),
1803 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
1804 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
1805 EndContainer(),
1806 NWidget(NWID_HORIZONTAL),
1807 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1808 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1809 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1810 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1811 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1812 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1813 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1814 EndContainer(),
1815 NWidget(NWID_HORIZONTAL),
1816 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
1817 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1818 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
1819 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1820 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
1821 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1822 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
1823 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1824 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1825 EndContainer(),
1829 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
1830 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
1831 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
1832 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
1833 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
1835 static StringID _service_interval_dropdown[] = {
1836 STR_VEHICLE_DETAILS_DEFAULT,
1837 STR_VEHICLE_DETAILS_DAYS,
1838 STR_VEHICLE_DETAILS_PERCENT,
1839 INVALID_STRING_ID,
1842 /** Class for managing the vehicle details window. */
1843 struct VehicleDetailsWindow : Window {
1844 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
1845 Scrollbar *vscroll;
1847 /** Initialize a newly created vehicle details window */
1848 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1850 const Vehicle *v = Vehicle::Get(window_number);
1852 this->CreateNestedTree();
1853 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
1854 this->FinishInitNested(window_number);
1856 this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
1858 this->owner = v->owner;
1859 this->tab = TDW_TAB_CARGO;
1863 * Some data on this window has become invalid.
1864 * @param data Information about the changed data.
1865 * @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.
1867 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1869 if (data == VIWD_AUTOREPLACE) {
1870 /* Autoreplace replaced the vehicle.
1871 * Nothing to do for this window. */
1872 return;
1874 if (!gui_scope) return;
1875 const Vehicle *v = Vehicle::Get(this->window_number);
1876 if (v->type == VEH_ROAD) {
1877 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
1878 uint aimed_height = this->GetRoadVehDetailsHeight(v);
1879 /* If the number of articulated parts changes, the size of the window must change too. */
1880 if (aimed_height != nwid_info->current_y) {
1881 this->ReInit();
1887 * Gets the desired height for the road vehicle details panel.
1888 * @param v Road vehicle being shown.
1889 * @return Desired height in pixels.
1891 uint GetRoadVehDetailsHeight(const Vehicle *v)
1893 uint desired_height;
1894 if (v->HasArticulatedPart()) {
1895 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
1896 desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
1897 /* Add space for the cargo amount for each part. */
1898 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1899 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
1901 } else {
1902 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
1904 return desired_height;
1907 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1909 switch (widget) {
1910 case WID_VD_TOP_DETAILS: {
1911 Dimension dim = { 0, 0 };
1912 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1914 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
1915 static const StringID info_strings[] = {
1916 STR_VEHICLE_INFO_MAX_SPEED,
1917 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
1918 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
1919 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
1920 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
1922 for (uint i = 0; i < lengthof(info_strings); i++) {
1923 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
1925 SetDParam(0, STR_VEHICLE_INFO_AGE);
1926 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
1927 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1928 break;
1931 case WID_VD_MIDDLE_DETAILS: {
1932 const Vehicle *v = Vehicle::Get(this->window_number);
1933 switch (v->type) {
1934 case VEH_ROAD:
1935 size->height = this->GetRoadVehDetailsHeight(v);
1936 break;
1938 case VEH_SHIP:
1939 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
1940 break;
1942 case VEH_AIRCRAFT:
1943 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
1944 break;
1946 default:
1947 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
1949 break;
1952 case WID_VD_MATRIX:
1953 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
1954 size->height = 4 * resize->height;
1955 break;
1957 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
1958 StringID *strs = _service_interval_dropdown;
1959 while (*strs != INVALID_STRING_ID) {
1960 *size = maxdim(*size, GetStringBoundingBox(*strs++));
1962 size->width += padding.width;
1963 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
1964 break;
1967 case WID_VD_SERVICING_INTERVAL:
1968 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
1969 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
1970 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;
1971 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1972 break;
1976 /** Checks whether service interval is enabled for the vehicle. */
1977 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
1979 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
1980 switch (vehicle_type) {
1981 default: NOT_REACHED();
1982 case VEH_TRAIN: return vds->servint_trains != 0;
1983 case VEH_ROAD: return vds->servint_roadveh != 0;
1984 case VEH_SHIP: return vds->servint_ships != 0;
1985 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
1990 * Draw the details for the given vehicle at the position of the Details windows
1992 * @param v current vehicle
1993 * @param left The left most coordinate to draw
1994 * @param right The right most coordinate to draw
1995 * @param y The y coordinate
1996 * @param vscroll_pos Position of scrollbar (train only)
1997 * @param vscroll_cap Number of lines currently displayed (train only)
1998 * @param det_tab Selected details tab (train only)
2000 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2002 switch (v->type) {
2003 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2004 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2005 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2006 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2007 default: NOT_REACHED();
2011 virtual void SetStringParameters(int widget) const
2013 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2016 virtual void DrawWidget(const Rect &r, int widget) const
2018 const Vehicle *v = Vehicle::Get(this->window_number);
2020 switch (widget) {
2021 case WID_VD_TOP_DETAILS: {
2022 int y = r.top + WD_FRAMERECT_TOP;
2024 /* Draw running cost */
2025 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2026 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2027 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2028 SetDParam(3, v->GetDisplayRunningCost());
2029 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2030 y += FONT_HEIGHT_NORMAL;
2032 /* Draw max speed */
2033 StringID string;
2034 if (v->type == VEH_TRAIN ||
2035 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2036 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2037 SetDParam(2, v->GetDisplayMaxSpeed());
2038 SetDParam(1, gcache->cached_power);
2039 SetDParam(0, gcache->cached_weight);
2040 SetDParam(3, gcache->cached_max_te / 1000);
2041 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2042 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2043 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2044 } else {
2045 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2047 } else {
2048 SetDParam(0, v->GetDisplayMaxSpeed());
2049 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
2050 SetDParam(1, Aircraft::From(v)->GetRange());
2051 string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
2052 } else {
2053 string = STR_VEHICLE_INFO_MAX_SPEED;
2056 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2057 y += FONT_HEIGHT_NORMAL;
2059 /* Draw profit */
2060 SetDParam(0, v->GetDisplayProfitThisYear());
2061 SetDParam(1, v->GetDisplayProfitLastYear());
2062 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2063 y += FONT_HEIGHT_NORMAL;
2065 /* Draw breakdown & reliability */
2066 SetDParam(0, ToPercent16(v->reliability));
2067 SetDParam(1, v->breakdowns_since_last_service);
2068 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2069 break;
2072 case WID_VD_MATRIX:
2073 /* For trains only. */
2074 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);
2075 break;
2077 case WID_VD_MIDDLE_DETAILS: {
2078 /* For other vehicles, at the place of the matrix. */
2079 bool rtl = _current_text_dir == TD_RTL;
2080 uint sprite_width = max<uint>(UnScaleByZoom(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W, EIT_IN_DETAILS), ST_NORMAL)->width, ZOOM_LVL_GUI), 70U) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2082 uint text_left = r.left + (rtl ? 0 : sprite_width);
2083 uint text_right = r.right - (rtl ? sprite_width : 0);
2085 /* Articulated road vehicles use a complete line. */
2086 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2087 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2088 } else {
2089 uint sprite_left = rtl ? text_right : r.left;
2090 uint sprite_right = rtl ? r.right : text_left;
2092 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2094 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2095 break;
2098 case WID_VD_SERVICING_INTERVAL:
2099 /* Draw service interval text */
2100 SetDParam(0, v->GetServiceInterval());
2101 SetDParam(1, v->date_of_last_service);
2102 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2103 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2104 break;
2108 /** Repaint vehicle details window. */
2109 virtual void OnPaint()
2111 const Vehicle *v = Vehicle::Get(this->window_number);
2113 this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
2115 if (v->type == VEH_TRAIN) {
2116 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2117 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2120 /* Disable service-scroller when interval is set to disabled */
2121 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2122 WID_VD_INCREASE_SERVICING_INTERVAL,
2123 WID_VD_DECREASE_SERVICING_INTERVAL,
2124 WIDGET_LIST_END);
2126 StringID str = v->ServiceIntervalIsCustom() ?
2127 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2128 STR_VEHICLE_DETAILS_DEFAULT;
2129 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2131 this->DrawWidgets();
2134 virtual void OnClick(Point pt, int widget, int click_count)
2136 switch (widget) {
2137 case WID_VD_RENAME_VEHICLE: { // rename
2138 const Vehicle *v = Vehicle::Get(this->window_number);
2139 SetDParam(0, v->index);
2140 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2141 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2142 break;
2145 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2146 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2147 int mod = _ctrl_pressed ? 5 : 10;
2148 const Vehicle *v = Vehicle::Get(this->window_number);
2150 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2151 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2152 if (mod == v->GetServiceInterval()) return;
2154 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2155 break;
2158 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2159 const Vehicle *v = Vehicle::Get(this->window_number);
2160 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2161 break;
2164 case WID_VD_DETAILS_CARGO_CARRIED:
2165 case WID_VD_DETAILS_TRAIN_VEHICLES:
2166 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2167 case WID_VD_DETAILS_TOTAL_CARGO:
2168 this->SetWidgetsDisabledState(false,
2169 WID_VD_DETAILS_CARGO_CARRIED,
2170 WID_VD_DETAILS_TRAIN_VEHICLES,
2171 WID_VD_DETAILS_CAPACITY_OF_EACH,
2172 WID_VD_DETAILS_TOTAL_CARGO,
2173 widget,
2174 WIDGET_LIST_END);
2176 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2177 this->SetDirty();
2178 break;
2182 virtual void OnDropdownSelect(int widget, int index)
2184 switch (widget) {
2185 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2186 const Vehicle *v = Vehicle::Get(this->window_number);
2187 bool iscustom = index != 0;
2188 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2189 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2190 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
2191 break;
2196 virtual void OnQueryTextFinished(char *str)
2198 if (str == NULL) return;
2200 DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), NULL, str);
2203 virtual void OnResize()
2205 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2206 if (nwi != NULL) {
2207 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2212 /** Vehicle details window descriptor. */
2213 static WindowDesc _train_vehicle_details_desc(
2214 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2215 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2217 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2220 /** Vehicle details window descriptor for other vehicles than a train. */
2221 static WindowDesc _nontrain_vehicle_details_desc(
2222 WDP_AUTO, "view_vehicle_details", 405, 113,
2223 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2225 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2228 /** Shows the vehicle details window of the given vehicle. */
2229 static void ShowVehicleDetailsWindow(const Vehicle *v)
2231 DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
2232 DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2233 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2237 /* Unified vehicle GUI - Vehicle View Window */
2239 /** Vehicle view widgets. */
2240 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2241 NWidget(NWID_HORIZONTAL),
2242 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2243 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2244 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2245 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2246 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2247 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2248 EndContainer(),
2249 NWidget(NWID_HORIZONTAL),
2250 NWidget(WWT_PANEL, COLOUR_GREY),
2251 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2252 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
2253 EndContainer(),
2254 EndContainer(),
2255 NWidget(NWID_VERTICAL),
2256 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
2257 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2258 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2259 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2260 EndContainer(),
2261 /* For trains only, 'ignore signal' button. */
2262 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
2263 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2264 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2265 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2266 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
2267 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2268 EndContainer(),
2269 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2270 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2271 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2272 EndContainer(),
2273 EndContainer(),
2274 NWidget(NWID_HORIZONTAL),
2275 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2276 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2277 EndContainer(),
2280 /** Vehicle view window descriptor for all vehicles but trains. */
2281 static WindowDesc _vehicle_view_desc(
2282 WDP_AUTO, "view_vehicle", 250, 116,
2283 WC_VEHICLE_VIEW, WC_NONE,
2285 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2289 * Vehicle view window descriptor for trains. Only minimum_height and
2290 * default_height are different for train view.
2292 static WindowDesc _train_view_desc(
2293 WDP_AUTO, "view_vehicle_train", 250, 134,
2294 WC_VEHICLE_VIEW, WC_NONE,
2296 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2300 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2301 using them for array indexing in a number of places here. */
2302 assert_compile(VEH_TRAIN == 0);
2303 assert_compile(VEH_ROAD == 1);
2304 assert_compile(VEH_SHIP == 2);
2305 assert_compile(VEH_AIRCRAFT == 3);
2307 /** Zoom levels for vehicle views indexed by vehicle type. */
2308 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2309 ZOOM_LVL_TRAIN,
2310 ZOOM_LVL_ROADVEH,
2311 ZOOM_LVL_SHIP,
2312 ZOOM_LVL_AIRCRAFT,
2315 /* Constants for geometry of vehicle view viewport */
2316 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2317 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2318 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2320 /** Command codes to start/stop a vehicle indexed by vehicle type. */
2321 static const uint32 _vehicle_command_startstop_table[4] = {
2322 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
2323 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
2324 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
2325 CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
2328 /** Command codes to clone a vehicle indexed by vehicle type. */
2329 static const uint32 _vehicle_command_clone_table[4] = {
2330 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
2331 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
2332 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
2333 CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
2336 /** Command codes to turn a vehicle around indexed by vehicle type. */
2337 static const uint32 _vehicle_command_turn_table[4] = {
2338 CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
2339 CMD_TURN_ROADVEH | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
2340 0xffffffff, // invalid for ships
2341 0xffffffff // invalid for aircrafts
2345 * This is the Callback method after the cloning attempt of a vehicle
2346 * @param result the result of the cloning command
2347 * @param tile unused
2348 * @param p1 vehicle ID
2349 * @param p2 unused
2351 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2353 if (result.Failed()) return;
2355 const Vehicle *v = Vehicle::GetIfValid(p1);
2356 if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2358 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2359 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2360 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2364 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2365 * @param v Vehicle to start/stop
2366 * @param texteffect Should a texteffect be shown?
2368 void StartStopVehicle(const Vehicle *v, bool texteffect)
2370 assert(v->IsPrimaryVehicle());
2371 DoCommandP(v->tile, v->index, 0, _vehicle_command_startstop_table[v->type], texteffect ? CcStartStopVehicle : NULL);
2374 /** Checks whether the vehicle may be refitted at the moment.*/
2375 static bool IsVehicleRefitable(const Vehicle *v)
2377 if (!v->IsStoppedInDepot()) return false;
2379 do {
2380 if (IsEngineRefittable(v->engine_type)) return true;
2381 } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
2383 return false;
2386 /** Window manager class for viewing a vehicle. */
2387 struct VehicleViewWindow : Window {
2388 private:
2389 /** Display planes available in the vehicle view window. */
2390 enum PlaneSelections {
2391 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2392 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2394 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2395 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2397 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2398 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2402 * Display a plane in the window.
2403 * @param plane Plane to show.
2405 void SelectPlane(PlaneSelections plane)
2407 switch (plane) {
2408 case SEL_DC_GOTO_DEPOT:
2409 case SEL_DC_CLONE:
2410 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2411 break;
2413 case SEL_RT_REFIT:
2414 case SEL_RT_TURN_AROUND:
2415 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2416 break;
2418 default:
2419 NOT_REACHED();
2423 public:
2424 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2426 this->CreateNestedTree();
2428 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2429 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2430 SPR_SEND_TRAIN_TODEPOT,
2431 SPR_SEND_ROADVEH_TODEPOT,
2432 SPR_SEND_SHIP_TODEPOT,
2433 SPR_SEND_AIRCRAFT_TODEPOT,
2435 const Vehicle *v = Vehicle::Get(window_number);
2436 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2438 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2439 static const SpriteID vehicle_view_clone_sprites[] = {
2440 SPR_CLONE_TRAIN,
2441 SPR_CLONE_ROADVEH,
2442 SPR_CLONE_SHIP,
2443 SPR_CLONE_AIRCRAFT,
2445 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2447 switch (v->type) {
2448 case VEH_TRAIN:
2449 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2450 break;
2452 case VEH_ROAD:
2453 break;
2455 case VEH_SHIP:
2456 case VEH_AIRCRAFT:
2457 this->SelectPlane(SEL_RT_REFIT);
2458 break;
2460 default: NOT_REACHED();
2462 this->FinishInitNested(window_number);
2463 this->owner = v->owner;
2464 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2466 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
2467 this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
2468 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2469 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2470 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2471 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2472 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2475 ~VehicleViewWindow()
2477 DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2478 DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2479 DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2480 DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2483 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2485 const Vehicle *v = Vehicle::Get(this->window_number);
2486 switch (widget) {
2487 case WID_VV_START_STOP:
2488 size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
2489 break;
2491 case WID_VV_FORCE_PROCEED:
2492 if (v->type != VEH_TRAIN) {
2493 size->height = 0;
2494 size->width = 0;
2496 break;
2498 case WID_VV_VIEWPORT:
2499 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2500 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2501 break;
2505 virtual void OnPaint()
2507 const Vehicle *v = Vehicle::Get(this->window_number);
2508 bool is_localcompany = v->owner == _local_company;
2509 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2511 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2512 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2513 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2515 if (v->type == VEH_TRAIN) {
2516 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2517 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2518 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2521 this->DrawWidgets();
2524 virtual void SetStringParameters(int widget) const
2526 if (widget != WID_VV_CAPTION) return;
2528 const Vehicle *v = Vehicle::Get(this->window_number);
2529 SetDParam(0, v->index);
2532 virtual void DrawWidget(const Rect &r, int widget) const
2534 if (widget != WID_VV_START_STOP) return;
2536 const Vehicle *v = Vehicle::Get(this->window_number);
2537 StringID str;
2538 if (v->vehstatus & VS_CRASHED) {
2539 str = STR_VEHICLE_STATUS_CRASHED;
2540 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2541 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2542 } else if (v->vehstatus & VS_STOPPED) {
2543 if (v->type == VEH_TRAIN) {
2544 if (v->cur_speed == 0) {
2545 if (Train::From(v)->gcache.cached_power == 0) {
2546 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2547 } else {
2548 str = STR_VEHICLE_STATUS_STOPPED;
2550 } else {
2551 SetDParam(0, v->GetDisplaySpeed());
2552 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2554 } else { // no train
2555 str = STR_VEHICLE_STATUS_STOPPED;
2557 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2558 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2559 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2560 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2561 } else { // vehicle is in a "normal" state, show current order
2562 switch (v->current_order.GetType()) {
2563 case OT_GOTO_STATION: {
2564 SetDParam(0, v->current_order.GetDestination());
2565 SetDParam(1, v->GetDisplaySpeed());
2566 str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2567 break;
2570 case OT_GOTO_DEPOT: {
2571 SetDParam(0, v->type);
2572 SetDParam(1, v->current_order.GetDestination());
2573 SetDParam(2, v->GetDisplaySpeed());
2574 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2575 /* This case *only* happens when multiple nearest depot orders
2576 * follow each other (including an order list only one order: a
2577 * nearest depot order) and there are no reachable depots.
2578 * It is primarily to guard for the case that there is no
2579 * depot with index 0, which would be used as fallback for
2580 * evaluating the string in the status bar. */
2581 str = STR_EMPTY;
2582 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2583 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2584 } else {
2585 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2587 break;
2590 case OT_LOADING:
2591 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2592 break;
2594 case OT_GOTO_WAYPOINT: {
2595 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2596 SetDParam(0, v->current_order.GetDestination());
2597 str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2598 SetDParam(1, v->GetDisplaySpeed());
2599 break;
2602 case OT_LEAVESTATION:
2603 if (v->type != VEH_AIRCRAFT) {
2604 str = STR_VEHICLE_STATUS_LEAVING;
2605 break;
2607 /* FALL THROUGH, if aircraft. Does this even happen? */
2609 default:
2610 if (v->GetNumManualOrders() == 0) {
2611 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2612 SetDParam(0, v->GetDisplaySpeed());
2613 } else {
2614 str = STR_EMPTY;
2616 break;
2620 /* Draw the flag plus orders. */
2621 bool rtl = (_current_text_dir == TD_RTL);
2622 uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2623 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2624 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2625 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2626 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
2627 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2628 DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
2629 DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
2632 virtual void OnClick(Point pt, int widget, int click_count)
2634 const Vehicle *v = Vehicle::Get(this->window_number);
2636 switch (widget) {
2637 case WID_VV_START_STOP: // start stop
2638 if (_ctrl_pressed) {
2639 /* Scroll to current order destination */
2640 TileIndex tile = v->current_order.GetLocation(v);
2641 if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
2642 } else {
2643 /* Start/Stop */
2644 StartStopVehicle(v, false);
2646 break;
2647 case WID_VV_CENTER_MAIN_VIEW: {// center main view
2648 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2649 /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
2650 if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2651 mainwindow->viewport->follow_vehicle = v->index;
2652 } else {
2653 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2655 break;
2658 case WID_VV_GOTO_DEPOT: // goto hangar
2659 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
2660 break;
2661 case WID_VV_REFIT: // refit
2662 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
2663 break;
2664 case WID_VV_SHOW_ORDERS: // show orders
2665 if (_ctrl_pressed) {
2666 ShowTimetableWindow(v);
2667 } else {
2668 ShowOrdersWindow(v);
2670 break;
2671 case WID_VV_SHOW_DETAILS: // show details
2672 ShowVehicleDetailsWindow(v);
2673 break;
2674 case WID_VV_CLONE: // clone vehicle
2675 /* Suppress the vehicle GUI when share-cloning.
2676 * There is no point to it except for starting the vehicle.
2677 * For starting the vehicle the player has to open the depot GUI, which is
2678 * most likely already open, but is also visible in the vehicle viewport. */
2679 DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
2680 _vehicle_command_clone_table[v->type],
2681 _ctrl_pressed ? NULL : CcCloneVehicle);
2682 break;
2683 case WID_VV_TURN_AROUND: // turn around
2684 assert(v->IsGroundVehicle());
2685 DoCommandP(v->tile, v->index, 0,
2686 _vehicle_command_turn_table[v->type]);
2687 break;
2688 case WID_VV_FORCE_PROCEED: // force proceed
2689 assert(v->type == VEH_TRAIN);
2690 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
2691 break;
2695 virtual void OnResize()
2697 if (this->viewport != NULL) {
2698 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
2699 nvp->UpdateViewportCoordinates(this);
2703 virtual void OnTick()
2705 const Vehicle *v = Vehicle::Get(this->window_number);
2706 bool veh_stopped = v->IsStoppedInDepot();
2708 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
2709 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
2711 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
2712 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
2713 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
2714 this->SelectPlane(plane);
2715 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
2717 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
2718 if (v->IsGroundVehicle()) {
2719 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
2720 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
2721 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
2722 this->SelectPlane(plane);
2723 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
2729 * Some data on this window has become invalid.
2730 * @param data Information about the changed data.
2731 * @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.
2733 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2735 if (data == VIWD_AUTOREPLACE) {
2736 /* Autoreplace replaced the vehicle.
2737 * Nothing to do for this window. */
2738 return;
2742 virtual bool IsNewGRFInspectable() const
2744 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2747 virtual void ShowNewGRFInspectWindow() const
2749 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2754 /** Shows the vehicle view window of the given vehicle. */
2755 void ShowVehicleViewWindow(const Vehicle *v)
2757 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
2761 * Dispatch a "vehicle selected" event if any window waits for it.
2762 * @param v selected vehicle;
2763 * @return did any window accept vehicle selection?
2765 bool VehicleClicked(const Vehicle *v)
2767 assert(v != NULL);
2768 if (!(_thd.place_mode & HT_VEHICLE)) return false;
2770 v = v->First();
2771 if (!v->IsPrimaryVehicle()) return false;
2773 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
2776 void StopGlobalFollowVehicle(const Vehicle *v)
2778 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2779 if (w != NULL && w->viewport->follow_vehicle == v->index) {
2780 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
2781 w->viewport->follow_vehicle = INVALID_VEHICLE;
2787 * This is the Callback method after the construction attempt of a primary vehicle
2788 * @param result indicates completion (or not) of the operation
2789 * @param tile unused
2790 * @param p1 unused
2791 * @param p2 unused
2793 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2795 if (result.Failed()) return;
2797 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
2798 ShowVehicleViewWindow(v);
2802 * Get the width of a vehicle (including all parts of the consist) in pixels.
2803 * @param v Vehicle to get the width for.
2804 * @return Width of the vehicle.
2806 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
2808 int vehicle_width = 0;
2810 switch (v->type) {
2811 case VEH_TRAIN:
2812 for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
2813 vehicle_width += u->GetDisplayImageWidth();
2815 break;
2817 case VEH_ROAD:
2818 for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
2819 vehicle_width += u->GetDisplayImageWidth();
2821 break;
2823 default:
2824 bool rtl = _current_text_dir == TD_RTL;
2825 SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
2826 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
2827 vehicle_width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
2829 break;
2832 return vehicle_width;