# build_vehicle_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: build_vehicle_gui.cpp 26241 2014-01-12 18:00:39Z frosch $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "engine_base.h"
    00014 #include "engine_func.h"
    00015 #include "station_base.h"
    00016 #include "network/network.h"
    00017 #include "articulated_vehicles.h"
    00018 #include "textbuf_gui.h"
    00019 #include "command_func.h"
    00020 #include "company_func.h"
    00021 #include "vehicle_gui.h"
    00022 #include "newgrf_engine.h"
    00023 #include "newgrf_text.h"
    00024 #include "group.h"
    00025 #include "string_func.h"
    00026 #include "strings_func.h"
    00027 #include "window_func.h"
    00028 #include "date_func.h"
    00029 #include "vehicle_func.h"
    00030 #include "widgets/dropdown_func.h"
    00031 #include "engine_gui.h"
    00032 #include "cargotype.h"
    00033 #include "core/geometry_func.hpp"
    00034 #include "autoreplace_func.h"
    00035
    00036 #include "widgets/build_vehicle_widget.h"
    00037
    00038 #include "table/strings.h"
    00039
    00045 uint GetEngineListHeight(VehicleType type)
    00046 {
    00047   return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleImageCellSize(type, EIT_PURCHASE).height);
    00048 }
    00049
    00050 static const NWidgetPart _nested_build_vehicle_widgets[] = {
    00051   NWidget(NWID_HORIZONTAL),
    00052     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00053     NWidget(WWT_CAPTION, COLOUR_GREY, WID_BV_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00054     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00055     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
    00056     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00057   EndContainer(),
    00058   NWidget(WWT_PANEL, COLOUR_GREY),
    00059     NWidget(NWID_HORIZONTAL),
    00060       NWidget(NWID_VERTICAL),
    00061         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_SORT_ASSENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0),
    00062         NWidget(NWID_SPACER), SetFill(1, 1),
    00063       EndContainer(),
    00064       NWidget(NWID_VERTICAL),
    00065         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
    00066         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
    00067       EndContainer(),
    00068     EndContainer(),
    00069   EndContainer(),
    00070   /* Vehicle list. */
    00071   NWidget(NWID_HORIZONTAL),
    00072     NWidget(WWT_MATRIX, COLOUR_GREY, WID_BV_LIST), SetResize(1, 1), SetFill(1, 0), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_BV_SCROLLBAR),
    00073     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_BV_SCROLLBAR),
    00074   EndContainer(),
    00075   /* Panel with details. */
    00076   NWidget(WWT_PANEL, COLOUR_GREY, WID_BV_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(),
    00077   /* Build/rename buttons, resize button. */
    00078   NWidget(NWID_HORIZONTAL),
    00079     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BV_BUILD_SEL),
    00080       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_BUILD), SetResize(1, 0), SetFill(1, 0),
    00081     EndContainer(),
    00082     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_RENAME), SetResize(1, 0), SetFill(1, 0),
    00083     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00084   EndContainer(),
    00085 };
    00086
    00088 static const CargoID CF_ANY  = CT_NO_REFIT;
    00089 static const CargoID CF_NONE = CT_INVALID;
    00090
    00091 static bool _internal_sort_order;
    00092 static byte _last_sort_criteria[]      = {0, 0, 0, 0};
    00093 static bool _last_sort_order[]         = {false, false, false, false};
    00094 static CargoID _last_filter_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY};
    00095
    00102 static int CDECL EngineNumberSorter(const EngineID *a, const EngineID *b)
    00103 {
    00104   int r = Engine::Get(*a)->list_position - Engine::Get(*b)->list_position;
    00105
    00106   return _internal_sort_order ? -r : r;
    00107 }
    00108
    00115 static int CDECL EngineIntroDateSorter(const EngineID *a, const EngineID *b)
    00116 {
    00117   const int va = Engine::Get(*a)->intro_date;
    00118   const int vb = Engine::Get(*b)->intro_date;
    00119   const int r = va - vb;
    00120
    00121   /* Use EngineID to sort instead since we want consistent sorting */
    00122   if (r == 0) return EngineNumberSorter(a, b);
    00123   return _internal_sort_order ? -r : r;
    00124 }
    00125
    00132 static int CDECL EngineNameSorter(const EngineID *a, const EngineID *b)
    00133 {
    00134   static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
    00135   static char     last_name[2][64] = { "\0", "\0" };
    00136
    00137   const EngineID va = *a;
    00138   const EngineID vb = *b;
    00139
    00140   if (va != last_engine[0]) {
    00141     last_engine[0] = va;
    00142     SetDParam(0, va);
    00143     GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0]));
    00144   }
    00145
    00146   if (vb != last_engine[1]) {
    00147     last_engine[1] = vb;
    00148     SetDParam(0, vb);
    00149     GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1]));
    00150   }
    00151
    00152   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
    00153
    00154   /* Use EngineID to sort instead since we want consistent sorting */
    00155   if (r == 0) return EngineNumberSorter(a, b);
    00156   return _internal_sort_order ? -r : r;
    00157 }
    00158
    00165 static int CDECL EngineReliabilitySorter(const EngineID *a, const EngineID *b)
    00166 {
    00167   const int va = Engine::Get(*a)->reliability;
    00168   const int vb = Engine::Get(*b)->reliability;
    00169   const int r = va - vb;
    00170
    00171   /* Use EngineID to sort instead since we want consistent sorting */
    00172   if (r == 0) return EngineNumberSorter(a, b);
    00173   return _internal_sort_order ? -r : r;
    00174 }
    00175
    00182 static int CDECL EngineCostSorter(const EngineID *a, const EngineID *b)
    00183 {
    00184   Money va = Engine::Get(*a)->GetCost();
    00185   Money vb = Engine::Get(*b)->GetCost();
    00186   int r = ClampToI32(va - vb);
    00187
    00188   /* Use EngineID to sort instead since we want consistent sorting */
    00189   if (r == 0) return EngineNumberSorter(a, b);
    00190   return _internal_sort_order ? -r : r;
    00191 }
    00192
    00199 static int CDECL EngineSpeedSorter(const EngineID *a, const EngineID *b)
    00200 {
    00201   int va = Engine::Get(*a)->GetDisplayMaxSpeed();
    00202   int vb = Engine::Get(*b)->GetDisplayMaxSpeed();
    00203   int r = va - vb;
    00204
    00205   /* Use EngineID to sort instead since we want consistent sorting */
    00206   if (r == 0) return EngineNumberSorter(a, b);
    00207   return _internal_sort_order ? -r : r;
    00208 }
    00209
    00216 static int CDECL EnginePowerSorter(const EngineID *a, const EngineID *b)
    00217 {
    00218   int va = Engine::Get(*a)->GetPower();
    00219   int vb = Engine::Get(*b)->GetPower();
    00220   int r = va - vb;
    00221
    00222   /* Use EngineID to sort instead since we want consistent sorting */
    00223   if (r == 0) return EngineNumberSorter(a, b);
    00224   return _internal_sort_order ? -r : r;
    00225 }
    00226
    00233 static int CDECL EngineTractiveEffortSorter(const EngineID *a, const EngineID *b)
    00234 {
    00235   int va = Engine::Get(*a)->GetDisplayMaxTractiveEffort();
    00236   int vb = Engine::Get(*b)->GetDisplayMaxTractiveEffort();
    00237   int r = va - vb;
    00238
    00239   /* Use EngineID to sort instead since we want consistent sorting */
    00240   if (r == 0) return EngineNumberSorter(a, b);
    00241   return _internal_sort_order ? -r : r;
    00242 }
    00243
    00250 static int CDECL EngineRunningCostSorter(const EngineID *a, const EngineID *b)
    00251 {
    00252   Money va = Engine::Get(*a)->GetRunningCost();
    00253   Money vb = Engine::Get(*b)->GetRunningCost();
    00254   int r = ClampToI32(va - vb);
    00255
    00256   /* Use EngineID to sort instead since we want consistent sorting */
    00257   if (r == 0) return EngineNumberSorter(a, b);
    00258   return _internal_sort_order ? -r : r;
    00259 }
    00260
    00267 static int CDECL EnginePowerVsRunningCostSorter(const EngineID *a, const EngineID *b)
    00268 {
    00269   const Engine *e_a = Engine::Get(*a);
    00270   const Engine *e_b = Engine::Get(*b);
    00271
    00272   /* Here we are using a few tricks to get the right sort.
    00273    * We want power/running cost, but since we usually got higher running cost than power and we store the result in an int,
    00274    * we will actually calculate cunning cost/power (to make it more than 1).
    00275    * Because of this, the return value have to be reversed as well and we return b - a instead of a - b.
    00276    * Another thing is that both power and running costs should be doubled for multiheaded engines.
    00277    * Since it would be multiplying with 2 in both numerator and denominator, it will even themselves out and we skip checking for multiheaded. */
    00278   Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower());
    00279   Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower());
    00280   int r = ClampToI32(vb - va);
    00281
    00282   /* Use EngineID to sort instead since we want consistent sorting */
    00283   if (r == 0) return EngineNumberSorter(a, b);
    00284   return _internal_sort_order ? -r : r;
    00285 }
    00286
    00287 /* Train sorting functions */
    00288
    00295 static int CDECL TrainEngineCapacitySorter(const EngineID *a, const EngineID *b)
    00296 {
    00297   const RailVehicleInfo *rvi_a = RailVehInfo(*a);
    00298   const RailVehicleInfo *rvi_b = RailVehInfo(*b);
    00299
    00300   int va = GetTotalCapacityOfArticulatedParts(*a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
    00301   int vb = GetTotalCapacityOfArticulatedParts(*b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
    00302   int r = va - vb;
    00303
    00304   /* Use EngineID to sort instead since we want consistent sorting */
    00305   if (r == 0) return EngineNumberSorter(a, b);
    00306   return _internal_sort_order ? -r : r;
    00307 }
    00308
    00315 static int CDECL TrainEnginesThenWagonsSorter(const EngineID *a, const EngineID *b)
    00316 {
    00317   int val_a = (RailVehInfo(*a)->railveh_type == RAILVEH_WAGON ? 1 : 0);
    00318   int val_b = (RailVehInfo(*b)->railveh_type == RAILVEH_WAGON ? 1 : 0);
    00319   int r = val_a - val_b;
    00320
    00321   /* Use EngineID to sort instead since we want consistent sorting */
    00322   if (r == 0) return EngineNumberSorter(a, b);
    00323   return _internal_sort_order ? -r : r;
    00324 }
    00325
    00326 /* Road vehicle sorting functions */
    00327
    00334 static int CDECL RoadVehEngineCapacitySorter(const EngineID *a, const EngineID *b)
    00335 {
    00336   int va = GetTotalCapacityOfArticulatedParts(*a);
    00337   int vb = GetTotalCapacityOfArticulatedParts(*b);
    00338   int r = va - vb;
    00339
    00340   /* Use EngineID to sort instead since we want consistent sorting */
    00341   if (r == 0) return EngineNumberSorter(a, b);
    00342   return _internal_sort_order ? -r : r;
    00343 }
    00344
    00345 /* Ship vehicle sorting functions */
    00346
    00353 static int CDECL ShipEngineCapacitySorter(const EngineID *a, const EngineID *b)
    00354 {
    00355   const Engine *e_a = Engine::Get(*a);
    00356   const Engine *e_b = Engine::Get(*b);
    00357
    00358   int va = e_a->GetDisplayDefaultCapacity();
    00359   int vb = e_b->GetDisplayDefaultCapacity();
    00360   int r = va - vb;
    00361
    00362   /* Use EngineID to sort instead since we want consistent sorting */
    00363   if (r == 0) return EngineNumberSorter(a, b);
    00364   return _internal_sort_order ? -r : r;
    00365 }
    00366
    00367 /* Aircraft sorting functions */
    00368
    00375 static int CDECL AircraftEngineCargoSorter(const EngineID *a, const EngineID *b)
    00376 {
    00377   const Engine *e_a = Engine::Get(*a);
    00378   const Engine *e_b = Engine::Get(*b);
    00379
    00380   uint16 mail_a, mail_b;
    00381   int va = e_a->GetDisplayDefaultCapacity(&mail_a);
    00382   int vb = e_b->GetDisplayDefaultCapacity(&mail_b);
    00383   int r = va - vb;
    00384
    00385   if (r == 0) {
    00386     /* The planes have the same passenger capacity. Check mail capacity instead */
    00387     r = mail_a - mail_b;
    00388
    00389     if (r == 0) {
    00390       /* Use EngineID to sort instead since we want consistent sorting */
    00391       return EngineNumberSorter(a, b);
    00392     }
    00393   }
    00394   return _internal_sort_order ? -r : r;
    00395 }
    00396
    00403 static int CDECL AircraftRangeSorter(const EngineID *a, const EngineID *b)
    00404 {
    00405   uint16 r_a = Engine::Get(*a)->GetRange();
    00406   uint16 r_b = Engine::Get(*b)->GetRange();
    00407
    00408   int r = r_a - r_b;
    00409
    00410   /* Use EngineID to sort instead since we want consistent sorting */
    00411   if (r == 0) return EngineNumberSorter(a, b);
    00412   return _internal_sort_order ? -r : r;
    00413 }
    00414
    00415 static EngList_SortTypeFunction * const _sorter[][11] = {{
    00416   /* Trains */
    00417   &EngineNumberSorter,
    00418   &EngineCostSorter,
    00419   &EngineSpeedSorter,
    00420   &EnginePowerSorter,
    00421   &EngineTractiveEffortSorter,
    00422   &EngineIntroDateSorter,
    00423   &EngineNameSorter,
    00424   &EngineRunningCostSorter,
    00425   &EnginePowerVsRunningCostSorter,
    00426   &EngineReliabilitySorter,
    00427   &TrainEngineCapacitySorter,
    00428 }, {
    00429   /* Road vehicles */
    00430   &EngineNumberSorter,
    00431   &EngineCostSorter,
    00432   &EngineSpeedSorter,
    00433   &EnginePowerSorter,
    00434   &EngineTractiveEffortSorter,
    00435   &EngineIntroDateSorter,
    00436   &EngineNameSorter,
    00437   &EngineRunningCostSorter,
    00438   &EnginePowerVsRunningCostSorter,
    00439   &EngineReliabilitySorter,
    00440   &RoadVehEngineCapacitySorter,
    00441 }, {
    00442   /* Ships */
    00443   &EngineNumberSorter,
    00444   &EngineCostSorter,
    00445   &EngineSpeedSorter,
    00446   &EngineIntroDateSorter,
    00447   &EngineNameSorter,
    00448   &EngineRunningCostSorter,
    00449   &EngineReliabilitySorter,
    00450   &ShipEngineCapacitySorter,
    00451 }, {
    00452   /* Aircraft */
    00453   &EngineNumberSorter,
    00454   &EngineCostSorter,
    00455   &EngineSpeedSorter,
    00456   &EngineIntroDateSorter,
    00457   &EngineNameSorter,
    00458   &EngineRunningCostSorter,
    00459   &EngineReliabilitySorter,
    00460   &AircraftEngineCargoSorter,
    00461   &AircraftRangeSorter,
    00462 }};
    00463
    00464 static const StringID _sort_listing[][12] = {{
    00465   /* Trains */
    00466   STR_SORT_BY_ENGINE_ID,
    00467   STR_SORT_BY_COST,
    00468   STR_SORT_BY_MAX_SPEED,
    00469   STR_SORT_BY_POWER,
    00470   STR_SORT_BY_TRACTIVE_EFFORT,
    00471   STR_SORT_BY_INTRO_DATE,
    00472   STR_SORT_BY_NAME,
    00473   STR_SORT_BY_RUNNING_COST,
    00474   STR_SORT_BY_POWER_VS_RUNNING_COST,
    00475   STR_SORT_BY_RELIABILITY,
    00476   STR_SORT_BY_CARGO_CAPACITY,
    00477   INVALID_STRING_ID
    00478 }, {
    00479   /* Road vehicles */
    00480   STR_SORT_BY_ENGINE_ID,
    00481   STR_SORT_BY_COST,
    00482   STR_SORT_BY_MAX_SPEED,
    00483   STR_SORT_BY_POWER,
    00484   STR_SORT_BY_TRACTIVE_EFFORT,
    00485   STR_SORT_BY_INTRO_DATE,
    00486   STR_SORT_BY_NAME,
    00487   STR_SORT_BY_RUNNING_COST,
    00488   STR_SORT_BY_POWER_VS_RUNNING_COST,
    00489   STR_SORT_BY_RELIABILITY,
    00490   STR_SORT_BY_CARGO_CAPACITY,
    00491   INVALID_STRING_ID
    00492 }, {
    00493   /* Ships */
    00494   STR_SORT_BY_ENGINE_ID,
    00495   STR_SORT_BY_COST,
    00496   STR_SORT_BY_MAX_SPEED,
    00497   STR_SORT_BY_INTRO_DATE,
    00498   STR_SORT_BY_NAME,
    00499   STR_SORT_BY_RUNNING_COST,
    00500   STR_SORT_BY_RELIABILITY,
    00501   STR_SORT_BY_CARGO_CAPACITY,
    00502   INVALID_STRING_ID
    00503 }, {
    00504   /* Aircraft */
    00505   STR_SORT_BY_ENGINE_ID,
    00506   STR_SORT_BY_COST,
    00507   STR_SORT_BY_MAX_SPEED,
    00508   STR_SORT_BY_INTRO_DATE,
    00509   STR_SORT_BY_NAME,
    00510   STR_SORT_BY_RUNNING_COST,
    00511   STR_SORT_BY_RELIABILITY,
    00512   STR_SORT_BY_CARGO_CAPACITY,
    00513   STR_SORT_BY_RANGE,
    00514   INVALID_STRING_ID
    00515 }};
    00516
    00518 static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid)
    00519 {
    00520   if (cid == CF_ANY) return true;
    00521   uint32 refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true) & _standard_cargo_mask;
    00522   return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid));
    00523 }
    00524
    00525 static GUIEngineList::FilterFunction * const _filter_funcs[] = {
    00526   &CargoFilter,
    00527 };
    00528
    00529 static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, bool refittable)
    00530 {
    00531   CargoArray cap = GetCapacityOfArticulatedParts(engine);
    00532
    00533   for (CargoID c = 0; c < NUM_CARGO; c++) {
    00534     if (cap[c] == 0) continue;
    00535
    00536     SetDParam(0, c);
    00537     SetDParam(1, cap[c]);
    00538     SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
    00539     DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
    00540     y += FONT_HEIGHT_NORMAL;
    00541
    00542     /* Only show as refittable once */
    00543     refittable = false;
    00544   }
    00545
    00546   return y;
    00547 }
    00548
    00549 /* Draw rail wagon specific details */
    00550 static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
    00551 {
    00552   const Engine *e = Engine::Get(engine_number);
    00553
    00554   /* Purchase cost */
    00555   SetDParam(0, e->GetCost());
    00556   DrawString(left, right, y, STR_PURCHASE_INFO_COST);
    00557   y += FONT_HEIGHT_NORMAL;
    00558
    00559   /* Wagon weight - (including cargo) */
    00560   uint weight = e->GetDisplayWeight();
    00561   SetDParam(0, weight);
    00562   uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16 : 0);
    00563   SetDParam(1, cargo_weight + weight);
    00564   DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
    00565   y += FONT_HEIGHT_NORMAL;
    00566
    00567   /* Wagon speed limit, displayed if above zero */
    00568   if (_settings_game.vehicle.wagon_speed_limits) {
    00569     uint max_speed = e->GetDisplayMaxSpeed();
    00570     if (max_speed > 0) {
    00571       SetDParam(0, max_speed);
    00572       DrawString(left, right, y, STR_PURCHASE_INFO_SPEED);
    00573       y += FONT_HEIGHT_NORMAL;
    00574     }
    00575   }
    00576
    00577   /* Running cost */
    00578   if (rvi->running_cost_class != INVALID_PRICE) {
    00579     SetDParam(0, e->GetRunningCost());
    00580     DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
    00581     y += FONT_HEIGHT_NORMAL;
    00582   }
    00583
    00584   return y;
    00585 }
    00586
    00587 /* Draw locomotive specific details */
    00588 static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
    00589 {
    00590   const Engine *e = Engine::Get(engine_number);
    00591
    00592   /* Purchase Cost - Engine weight */
    00593   SetDParam(0, e->GetCost());
    00594   SetDParam(1, e->GetDisplayWeight());
    00595   DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT);
    00596   y += FONT_HEIGHT_NORMAL;
    00597
    00598   /* Max speed - Engine power */
    00599   SetDParam(0, e->GetDisplayMaxSpeed());
    00600   SetDParam(1, e->GetPower());
    00601   DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
    00602   y += FONT_HEIGHT_NORMAL;
    00603
    00604   /* Max tractive effort - not applicable if old acceleration or maglev */
    00605   if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) {
    00606     SetDParam(0, e->GetDisplayMaxTractiveEffort());
    00607     DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
    00608     y += FONT_HEIGHT_NORMAL;
    00609   }
    00610
    00611   /* Running cost */
    00612   if (rvi->running_cost_class != INVALID_PRICE) {
    00613     SetDParam(0, e->GetRunningCost());
    00614     DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
    00615     y += FONT_HEIGHT_NORMAL;
    00616   }
    00617
    00618   /* Powered wagons power - Powered wagons extra weight */
    00619   if (rvi->pow_wag_power != 0) {
    00620     SetDParam(0, rvi->pow_wag_power);
    00621     SetDParam(1, rvi->pow_wag_weight);
    00622     DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT);
    00623     y += FONT_HEIGHT_NORMAL;
    00624   }
    00625
    00626   return y;
    00627 }
    00628
    00629 /* Draw road vehicle specific details */
    00630 static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number)
    00631 {
    00632   const Engine *e = Engine::Get(engine_number);
    00633
    00634   if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
    00635     /* Purchase Cost */
    00636     SetDParam(0, e->GetCost());
    00637     DrawString(left, right, y, STR_PURCHASE_INFO_COST);
    00638     y += FONT_HEIGHT_NORMAL;
    00639
    00640     /* Road vehicle weight - (including cargo) */
    00641     int16 weight = e->GetDisplayWeight();
    00642     SetDParam(0, weight);
    00643     uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16 : 0);
    00644     SetDParam(1, cargo_weight + weight);
    00645     DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
    00646     y += FONT_HEIGHT_NORMAL;
    00647
    00648     /* Max speed - Engine power */
    00649     SetDParam(0, e->GetDisplayMaxSpeed());
    00650     SetDParam(1, e->GetPower());
    00651     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
    00652     y += FONT_HEIGHT_NORMAL;
    00653
    00654     /* Max tractive effort */
    00655     SetDParam(0, e->GetDisplayMaxTractiveEffort());
    00656     DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
    00657     y += FONT_HEIGHT_NORMAL;
    00658   } else {
    00659     /* Purchase cost - Max speed */
    00660     SetDParam(0, e->GetCost());
    00661     SetDParam(1, e->GetDisplayMaxSpeed());
    00662     DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
    00663     y += FONT_HEIGHT_NORMAL;
    00664   }
    00665
    00666   /* Running cost */
    00667   SetDParam(0, e->GetRunningCost());
    00668   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
    00669   y += FONT_HEIGHT_NORMAL;
    00670
    00671   return y;
    00672 }
    00673
    00674 /* Draw ship specific details */
    00675 static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
    00676 {
    00677   const Engine *e = Engine::Get(engine_number);
    00678
    00679   /* Purchase cost - Max speed */
    00680   uint raw_speed = e->GetDisplayMaxSpeed();
    00681   uint ocean_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, true);
    00682   uint canal_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, false);
    00683
    00684   SetDParam(0, e->GetCost());
    00685   if (ocean_speed == canal_speed) {
    00686     SetDParam(1, ocean_speed);
    00687     DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
    00688     y += FONT_HEIGHT_NORMAL;
    00689   } else {
    00690     DrawString(left, right, y, STR_PURCHASE_INFO_COST);
    00691     y += FONT_HEIGHT_NORMAL;
    00692
    00693     SetDParam(0, ocean_speed);
    00694     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_OCEAN);
    00695     y += FONT_HEIGHT_NORMAL;
    00696
    00697     SetDParam(0, canal_speed);
    00698     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_CANAL);
    00699     y += FONT_HEIGHT_NORMAL;
    00700   }
    00701
    00702   /* Cargo type + capacity */
    00703   SetDParam(0, e->GetDefaultCargoType());
    00704   SetDParam(1, e->GetDisplayDefaultCapacity());
    00705   SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
    00706   DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
    00707   y += FONT_HEIGHT_NORMAL;
    00708
    00709   /* Running cost */
    00710   SetDParam(0, e->GetRunningCost());
    00711   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
    00712   y += FONT_HEIGHT_NORMAL;
    00713
    00714   return y;
    00715 }
    00716
    00717 /* Draw aircraft specific details */
    00718 static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
    00719 {
    00720   const Engine *e = Engine::Get(engine_number);
    00721   CargoID cargo = e->GetDefaultCargoType();
    00722
    00723   /* Purchase cost - Max speed */
    00724   SetDParam(0, e->GetCost());
    00725   SetDParam(1, e->GetDisplayMaxSpeed());
    00726   DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
    00727   y += FONT_HEIGHT_NORMAL;
    00728
    00729   /* Cargo capacity */
    00730   uint16 mail_capacity;
    00731   uint capacity = e->GetDisplayDefaultCapacity(&mail_capacity);
    00732   if (mail_capacity > 0) {
    00733     SetDParam(0, cargo);
    00734     SetDParam(1, capacity);
    00735     SetDParam(2, CT_MAIL);
    00736     SetDParam(3, mail_capacity);
    00737     DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY);
    00738   } else {
    00739     /* Note, if the default capacity is selected by the refit capacity
    00740      * callback, then the capacity shown is likely to be incorrect. */
    00741     SetDParam(0, cargo);
    00742     SetDParam(1, capacity);
    00743     SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
    00744     DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
    00745   }
    00746   y += FONT_HEIGHT_NORMAL;
    00747
    00748   /* Running cost */
    00749   SetDParam(0, e->GetRunningCost());
    00750   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
    00751   y += FONT_HEIGHT_NORMAL;
    00752
    00753   uint16 range = e->GetRange();
    00754   if (range != 0) {
    00755     SetDParam(0, range);
    00756     DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_RANGE);
    00757     y += FONT_HEIGHT_NORMAL;
    00758   }
    00759
    00760   return y;
    00761 }
    00762
    00771 static uint ShowAdditionalText(int left, int right, int y, EngineID engine)
    00772 {
    00773   uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL);
    00774   if (callback == CALLBACK_FAILED || callback == 0x400) return y;
    00775   const GRFFile *grffile = Engine::Get(engine)->GetGRF();
    00776   if (callback > 0x400) {
    00777     ErrorUnknownCallbackResult(grffile->grfid, CBID_VEHICLE_ADDITIONAL_TEXT, callback);
    00778     return y;
    00779   }
    00780
    00781   StartTextRefStackUsage(grffile, 6);
    00782   uint result = DrawStringMultiLine(left, right, y, INT32_MAX, GetGRFStringID(grffile->grfid, 0xD000 + callback), TC_BLACK);
    00783   StopTextRefStackUsage();
    00784   return result;
    00785 }
    00786
    00793 int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number)
    00794 {
    00795   const Engine *e = Engine::Get(engine_number);
    00796   YearMonthDay ymd;
    00797   ConvertDateToYMD(e->intro_date, &ymd);
    00798   bool refittable = IsArticulatedVehicleRefittable(engine_number);
    00799   bool articulated_cargo = false;
    00800
    00801   switch (e->type) {
    00802     default: NOT_REACHED();
    00803     case VEH_TRAIN:
    00804       if (e->u.rail.railveh_type == RAILVEH_WAGON) {
    00805         y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail);
    00806       } else {
    00807         y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail);
    00808       }
    00809       articulated_cargo = true;
    00810       break;
    00811
    00812     case VEH_ROAD:
    00813       y = DrawRoadVehPurchaseInfo(left, right, y, engine_number);
    00814       articulated_cargo = true;
    00815       break;
    00816
    00817     case VEH_SHIP:
    00818       y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable);
    00819       break;
    00820
    00821     case VEH_AIRCRAFT:
    00822       y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable);
    00823       break;
    00824   }
    00825
    00826   if (articulated_cargo) {
    00827     /* Cargo type + capacity, or N/A */
    00828     int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, refittable);
    00829
    00830     if (new_y == y) {
    00831       SetDParam(0, CT_INVALID);
    00832       SetDParam(2, STR_EMPTY);
    00833       DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
    00834       y += FONT_HEIGHT_NORMAL;
    00835     } else {
    00836       y = new_y;
    00837     }
    00838   }
    00839
    00840   /* Draw details that apply to all types except rail wagons. */
    00841   if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
    00842     /* Design date - Life length */
    00843     SetDParam(0, ymd.year);
    00844     SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR);
    00845     DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE);
    00846     y += FONT_HEIGHT_NORMAL;
    00847
    00848     /* Reliability */
    00849     SetDParam(0, ToPercent16(e->reliability));
    00850     DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY);
    00851     y += FONT_HEIGHT_NORMAL;
    00852   }
    00853
    00854   if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number);
    00855
    00856   /* Additional text from NewGRF */
    00857   y = ShowAdditionalText(left, right, y, engine_number);
    00858
    00859   return y;
    00860 }
    00861
    00875 void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group)
    00876 {
    00877   static const int sprite_y_offsets[] = { -1, -1, -2, -2 };
    00878
    00879   /* Obligatory sanity checks! */
    00880   assert(max <= eng_list->Length());
    00881
    00882   bool rtl = _current_text_dir == TD_RTL;
    00883   int step_size = GetEngineListHeight(type);
    00884   int sprite_left  = GetVehicleImageCellSize(type, EIT_PURCHASE).extend_left;
    00885   int sprite_right = GetVehicleImageCellSize(type, EIT_PURCHASE).extend_right;
    00886   int sprite_width = sprite_left + sprite_right;
    00887
    00888   int sprite_x        = rtl ? r - sprite_right - 1 : l + sprite_left + 1;
    00889   int sprite_y_offset = sprite_y_offsets[type] + step_size / 2;
    00890
    00891   Dimension replace_icon = {0, 0};
    00892   int count_width = 0;
    00893   if (show_count) {
    00894     replace_icon = GetSpriteSize(SPR_GROUP_REPLACE_ACTIVE);
    00895     SetDParamMaxDigits(0, 3, FS_SMALL);
    00896     count_width = GetStringBoundingBox(STR_TINY_BLACK_COMA).width;
    00897   }
    00898
    00899   int text_left  = l + (rtl ? WD_FRAMERECT_LEFT + replace_icon.width + 8 + count_width : sprite_width + WD_FRAMETEXT_LEFT);
    00900   int text_right = r - (rtl ? sprite_width + WD_FRAMETEXT_RIGHT : WD_FRAMERECT_RIGHT + replace_icon.width + 8 + count_width);
    00901   int replace_icon_left = rtl ? l + WD_FRAMERECT_LEFT : r - WD_FRAMERECT_RIGHT - replace_icon.width;
    00902   int count_left = l;
    00903   int count_right = rtl ? text_left : r - WD_FRAMERECT_RIGHT - replace_icon.width - 8;
    00904
    00905   int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2;
    00906   int small_text_y_offset  = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1;
    00907   int replace_icon_y_offset = (step_size - replace_icon.height) / 2 - 1;
    00908
    00909   for (; min < max; min++, y += step_size) {
    00910     const EngineID engine = (*eng_list)[min];
    00911     /* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
    00912     const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
    00913
    00914     SetDParam(0, engine);
    00915     DrawString(text_left, text_right, y + normal_text_y_offset, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK);
    00916     DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company), EIT_PURCHASE);
    00917     if (show_count) {
    00918       SetDParam(0, num_engines);
    00919       DrawString(count_left, count_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT | SA_FORCE);
    00920       if (EngineHasReplacementForCompany(Company::Get(_local_company), engine, selected_group)) DrawSprite(SPR_GROUP_REPLACE_ACTIVE, num_engines == 0 ? PALETTE_CRASH : PAL_NONE, replace_icon_left, y + replace_icon_y_offset);
    00921     }
    00922   }
    00923 }
    00924
    00925
    00926 struct BuildVehicleWindow : Window {
    00927   VehicleType vehicle_type;
    00928   union {
    00929     RailTypeByte railtype;
    00930     RoadTypes roadtypes;
    00931   } filter;
    00932   bool descending_sort_order;
    00933   byte sort_criteria;
    00934   bool listview_mode;
    00935   EngineID sel_engine;
    00936   EngineID rename_engine;
    00937   GUIEngineList eng_list;
    00938   CargoID cargo_filter[NUM_CARGO + 2];
    00939   StringID cargo_filter_texts[NUM_CARGO + 3];
    00940   byte cargo_filter_criteria;
    00941   int details_height;
    00942   Scrollbar *vscroll;
    00943
    00944   BuildVehicleWindow(WindowDesc *desc, TileIndex tile, VehicleType type) : Window(desc)
    00945   {
    00946     this->vehicle_type = type;
    00947     this->window_number = tile == INVALID_TILE ? (int)type : tile;
    00948
    00949     this->sel_engine      = INVALID_ENGINE;
    00950
    00951     this->sort_criteria         = _last_sort_criteria[type];
    00952     this->descending_sort_order = _last_sort_order[type];
    00953
    00954     switch (type) {
    00955       default: NOT_REACHED();
    00956       case VEH_TRAIN:
    00957         this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile);
    00958         break;
    00959       case VEH_ROAD:
    00960         this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile);
    00961       case VEH_SHIP:
    00962       case VEH_AIRCRAFT:
    00963         break;
    00964     }
    00965
    00966     this->listview_mode = (this->window_number <= VEH_END);
    00967
    00968     this->CreateNestedTree();
    00969
    00970     this->vscroll = this->GetScrollbar(WID_BV_SCROLLBAR);
    00971
    00972     /* If we are just viewing the list of vehicles, we do not need the Build button.
    00973      * So we just hide it, and enlarge the Rename button by the now vacant place. */
    00974     if (this->listview_mode) this->GetWidget<NWidgetStacked>(WID_BV_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE);
    00975
    00976     /* disable renaming engines in network games if you are not the server */
    00977     this->SetWidgetDisabledState(WID_BV_RENAME, _networking && !_network_server);
    00978
    00979     NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_LIST);
    00980     widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type;
    00981
    00982     widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD);
    00983     widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + type;
    00984     widget->tool_tip    = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + type;
    00985
    00986     widget = this->GetWidget<NWidgetCore>(WID_BV_RENAME);
    00987     widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type;
    00988     widget->tool_tip    = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type;
    00989
    00990     this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    00991
    00992     this->FinishInitNested(tile == INVALID_TILE ? (int)type : tile);
    00993
    00994     this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company;
    00995
    00996     this->eng_list.ForceRebuild();
    00997     this->GenerateBuildList(); // generate the list, since we need it in the next line
    00998     /* Select the first engine in the list as default when opening the window */
    00999     if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0];
    01000   }
    01001
    01003   void SetCargoFilterArray()
    01004   {
    01005     uint filter_items = 0;
    01006
    01007     /* Add item for disabling filtering. */
    01008     this->cargo_filter[filter_items] = CF_ANY;
    01009     this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
    01010     filter_items++;
    01011
    01012     /* Add item for vehicles not carrying anything, e.g. train engines.
    01013      * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */
    01014     if (this->vehicle_type == VEH_TRAIN) {
    01015       this->cargo_filter[filter_items] = CF_NONE;
    01016       this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE;
    01017       filter_items++;
    01018     }
    01019
    01020     /* Collect available cargo types for filtering. */
    01021     const CargoSpec *cs;
    01022     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    01023       this->cargo_filter[filter_items] = cs->Index();
    01024       this->cargo_filter_texts[filter_items] = cs->name;
    01025       filter_items++;
    01026     }
    01027
    01028     /* Terminate the filter list. */
    01029     this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
    01030
    01031     /* If not found, the cargo criteria will be set to all cargoes. */
    01032     this->cargo_filter_criteria = 0;
    01033
    01034     /* Find the last cargo filter criteria. */
    01035     for (uint i = 0; i < filter_items; i++) {
    01036       if (this->cargo_filter[i] == _last_filter_criteria[this->vehicle_type]) {
    01037         this->cargo_filter_criteria = i;
    01038         break;
    01039       }
    01040     }
    01041
    01042     this->eng_list.SetFilterFuncs(_filter_funcs);
    01043     this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
    01044   }
    01045
    01046   void OnInit()
    01047   {
    01048     this->SetCargoFilterArray();
    01049   }
    01050
    01052   void FilterEngineList()
    01053   {
    01054     this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]);
    01055     if (0 == this->eng_list.Length()) { // no engine passed through the filter, invalidate the previously selected engine
    01056       this->sel_engine = INVALID_ENGINE;
    01057     } else if (!this->eng_list.Contains(this->sel_engine)) { // previously selected engine didn't pass the filter, select the first engine of the list
    01058       this->sel_engine = this->eng_list[0];
    01059     }
    01060   }
    01061
    01063   bool FilterSingleEngine(EngineID eid)
    01064   {
    01065     CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria];
    01066     return (filter_type == CF_ANY || CargoFilter(&eid, filter_type));
    01067   }
    01068
    01069   /* Figure out what train EngineIDs to put in the list */
    01070   void GenerateBuildTrainList()
    01071   {
    01072     EngineID sel_id = INVALID_ENGINE;
    01073     int num_engines = 0;
    01074     int num_wagons  = 0;
    01075
    01076     this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number);
    01077
    01078     this->eng_list.Clear();
    01079
    01080     /* Make list of all available train engines and wagons.
    01081      * Also check to see if the previously selected engine is still available,
    01082      * and if not, reset selection to INVALID_ENGINE. This could be the case
    01083      * when engines become obsolete and are removed */
    01084     const Engine *e;
    01085     FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
    01086       EngineID eid = e->index;
    01087       const RailVehicleInfo *rvi = &e->u.rail;
    01088
    01089       if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
    01090       if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
    01091
    01092       /* Filter now! So num_engines and num_wagons is valid */
    01093       if (!FilterSingleEngine(eid)) continue;
    01094
    01095       *this->eng_list.Append() = eid;
    01096
    01097       if (rvi->railveh_type != RAILVEH_WAGON) {
    01098         num_engines++;
    01099       } else {
    01100         num_wagons++;
    01101       }
    01102
    01103       if (eid == this->sel_engine) sel_id = eid;
    01104     }
    01105
    01106     this->sel_engine = sel_id;
    01107
    01108     /* make engines first, and then wagons, sorted by selected sort_criteria */
    01109     _internal_sort_order = false;
    01110     EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter);
    01111
    01112     /* and then sort engines */
    01113     _internal_sort_order = this->descending_sort_order;
    01114     EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines);
    01115
    01116     /* and finally sort wagons */
    01117     EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons);
    01118   }
    01119
    01120   /* Figure out what road vehicle EngineIDs to put in the list */
    01121   void GenerateBuildRoadVehList()
    01122   {
    01123     EngineID sel_id = INVALID_ENGINE;
    01124
    01125     this->eng_list.Clear();
    01126
    01127     const Engine *e;
    01128     FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
    01129       EngineID eid = e->index;
    01130       if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
    01131       if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue;
    01132       *this->eng_list.Append() = eid;
    01133
    01134       if (eid == this->sel_engine) sel_id = eid;
    01135     }
    01136     this->sel_engine = sel_id;
    01137   }
    01138
    01139   /* Figure out what ship EngineIDs to put in the list */
    01140   void GenerateBuildShipList()
    01141   {
    01142     EngineID sel_id = INVALID_ENGINE;
    01143     this->eng_list.Clear();
    01144
    01145     const Engine *e;
    01146     FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) {
    01147       EngineID eid = e->index;
    01148       if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
    01149       *this->eng_list.Append() = eid;
    01150
    01151       if (eid == this->sel_engine) sel_id = eid;
    01152     }
    01153     this->sel_engine = sel_id;
    01154   }
    01155
    01156   /* Figure out what aircraft EngineIDs to put in the list */
    01157   void GenerateBuildAircraftList()
    01158   {
    01159     EngineID sel_id = INVALID_ENGINE;
    01160
    01161     this->eng_list.Clear();
    01162
    01163     const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number);
    01164
    01165     /* Make list of all available planes.
    01166      * Also check to see if the previously selected plane is still available,
    01167      * and if not, reset selection to INVALID_ENGINE. This could be the case
    01168      * when planes become obsolete and are removed */
    01169     const Engine *e;
    01170     FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) {
    01171       EngineID eid = e->index;
    01172       if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
    01173       /* First VEH_END window_numbers are fake to allow a window open for all different types at once */
    01174       if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue;
    01175
    01176       *this->eng_list.Append() = eid;
    01177       if (eid == this->sel_engine) sel_id = eid;
    01178     }
    01179
    01180     this->sel_engine = sel_id;
    01181   }
    01182
    01183   /* Generate the list of vehicles */
    01184   void GenerateBuildList()
    01185   {
    01186     if (!this->eng_list.NeedRebuild()) return;
    01187     switch (this->vehicle_type) {
    01188       default: NOT_REACHED();
    01189       case VEH_TRAIN:
    01190         this->GenerateBuildTrainList();
    01191         this->eng_list.Compact();
    01192         this->eng_list.RebuildDone();
    01193         return; // trains should not reach the last sorting
    01194       case VEH_ROAD:
    01195         this->GenerateBuildRoadVehList();
    01196         break;
    01197       case VEH_SHIP:
    01198         this->GenerateBuildShipList();
    01199         break;
    01200       case VEH_AIRCRAFT:
    01201         this->GenerateBuildAircraftList();
    01202         break;
    01203     }
    01204
    01205     this->FilterEngineList();
    01206
    01207     _internal_sort_order = this->descending_sort_order;
    01208     EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]);
    01209
    01210     this->eng_list.Compact();
    01211     this->eng_list.RebuildDone();
    01212   }
    01213
    01214   void OnClick(Point pt, int widget, int click_count)
    01215   {
    01216     switch (widget) {
    01217       case WID_BV_SORT_ASSENDING_DESCENDING:
    01218         this->descending_sort_order ^= true;
    01219         _last_sort_order[this->vehicle_type] = this->descending_sort_order;
    01220         this->eng_list.ForceRebuild();
    01221         this->SetDirty();
    01222         break;
    01223
    01224       case WID_BV_LIST: {
    01225         uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BV_LIST);
    01226         size_t num_items = this->eng_list.Length();
    01227         this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE;
    01228         this->SetDirty();
    01229         if (click_count > 1 && !this->listview_mode) this->OnClick(pt, WID_BV_BUILD, 1);
    01230         break;
    01231       }
    01232
    01233       case WID_BV_SORT_DROPDOWN: { // Select sorting criteria dropdown menu
    01234         uint32 hidden_mask = 0;
    01235         /* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */
    01236         if (this->vehicle_type == VEH_ROAD &&
    01237             _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) {
    01238           SetBit(hidden_mask, 3); // power
    01239           SetBit(hidden_mask, 4); // tractive effort
    01240           SetBit(hidden_mask, 8); // power by running costs
    01241         }
    01242         /* Disable sorting by tractive effort when the original acceleration model for trains is being used. */
    01243         if (this->vehicle_type == VEH_TRAIN &&
    01244             _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
    01245           SetBit(hidden_mask, 4); // tractive effort
    01246         }
    01247         ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, WID_BV_SORT_DROPDOWN, 0, hidden_mask);
    01248         break;
    01249       }
    01250
    01251       case WID_BV_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu
    01252         ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, WID_BV_CARGO_FILTER_DROPDOWN, 0, 0);
    01253         break;
    01254
    01255       case WID_BV_BUILD: {
    01256         EngineID sel_eng = this->sel_engine;
    01257         if (sel_eng != INVALID_ENGINE) {
    01258           CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle;
    01259           DoCommandP(this->window_number, sel_eng, 0, GetCmdBuildVeh(this->vehicle_type), callback);
    01260         }
    01261         break;
    01262       }
    01263
    01264       case WID_BV_RENAME: {
    01265         EngineID sel_eng = this->sel_engine;
    01266         if (sel_eng != INVALID_ENGINE) {
    01267           this->rename_engine = sel_eng;
    01268           SetDParam(0, sel_eng);
    01269           ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    01270         }
    01271         break;
    01272       }
    01273     }
    01274   }
    01275
    01281   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01282   {
    01283     if (!gui_scope) return;
    01284     /* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */
    01285     if (this->vehicle_type == VEH_ROAD &&
    01286         _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL &&
    01287         this->sort_criteria > 7) {
    01288       this->sort_criteria = 0;
    01289       _last_sort_criteria[VEH_ROAD] = 0;
    01290     }
    01291     this->eng_list.ForceRebuild();
    01292   }
    01293
    01294   virtual void SetStringParameters(int widget) const
    01295   {
    01296     switch (widget) {
    01297       case WID_BV_CAPTION:
    01298         if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) {
    01299           const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype);
    01300           SetDParam(0, rti->strings.build_caption);
    01301         } else {
    01302           SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type);
    01303         }
    01304         break;
    01305
    01306       case WID_BV_SORT_DROPDOWN:
    01307         SetDParam(0, _sort_listing[this->vehicle_type][this->sort_criteria]);
    01308         break;
    01309
    01310       case WID_BV_CARGO_FILTER_DROPDOWN:
    01311         SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]);
    01312     }
    01313   }
    01314
    01315   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01316   {
    01317     switch (widget) {
    01318       case WID_BV_LIST:
    01319         resize->height = GetEngineListHeight(this->vehicle_type);
    01320         size->height = 3 * resize->height;
    01321         break;
    01322
    01323       case WID_BV_PANEL:
    01324         size->height = this->details_height;
    01325         break;
    01326
    01327       case WID_BV_SORT_ASSENDING_DESCENDING: {
    01328         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    01329         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    01330         d.height += padding.height;
    01331         *size = maxdim(*size, d);
    01332         break;
    01333       }
    01334     }
    01335   }
    01336
    01337   virtual void DrawWidget(const Rect &r, int widget) const
    01338   {
    01339     switch (widget) {
    01340       case WID_BV_LIST:
    01341         DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP);
    01342         break;
    01343
    01344       case WID_BV_SORT_ASSENDING_DESCENDING:
    01345         this->DrawSortButtonState(WID_BV_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
    01346         break;
    01347     }
    01348   }
    01349
    01350   virtual void OnPaint()
    01351   {
    01352     this->GenerateBuildList();
    01353     this->vscroll->SetCount(this->eng_list.Length());
    01354
    01355     this->DrawWidgets();
    01356
    01357     if (!this->IsShaded()) {
    01358       int needed_height = this->details_height;
    01359       /* Draw details panels. */
    01360       if (this->sel_engine != INVALID_ENGINE) {
    01361         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_BV_PANEL);
    01362         int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
    01363             nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine);
    01364         needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
    01365       }
    01366       if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
    01367         int resize = needed_height - this->details_height;
    01368         this->details_height = needed_height;
    01369         this->ReInit(0, resize);
    01370         return;
    01371       }
    01372     }
    01373   }
    01374
    01375   virtual void OnQueryTextFinished(char *str)
    01376   {
    01377     if (str == NULL) return;
    01378
    01379     DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str);
    01380   }
    01381
    01382   virtual void OnDropdownSelect(int widget, int index)
    01383   {
    01384     switch (widget) {
    01385       case WID_BV_SORT_DROPDOWN:
    01386         if (this->sort_criteria != index) {
    01387           this->sort_criteria = index;
    01388           _last_sort_criteria[this->vehicle_type] = this->sort_criteria;
    01389           this->eng_list.ForceRebuild();
    01390         }
    01391         break;
    01392
    01393       case WID_BV_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria
    01394         if (this->cargo_filter_criteria != index) {
    01395           this->cargo_filter_criteria = index;
    01396           _last_filter_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria];
    01397           /* deactivate filter if criteria is 'Show All', activate it otherwise */
    01398           this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
    01399           this->eng_list.ForceRebuild();
    01400         }
    01401         break;
    01402     }
    01403     this->SetDirty();
    01404   }
    01405
    01406   virtual void OnResize()
    01407   {
    01408     this->vscroll->SetCapacityFromWidget(this, WID_BV_LIST);
    01409   }
    01410 };
    01411
    01412 static WindowDesc _build_vehicle_desc(
    01413   WDP_AUTO, "build_vehicle", 240, 268,
    01414   WC_BUILD_VEHICLE, WC_NONE,
    01415   WDF_CONSTRUCTION,
    01416   _nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets)
    01417 );
    01418
    01419 void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
    01420 {
    01421   /* We want to be able to open both Available Train as Available Ships,
    01422    *  so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number.
    01423    *  As it always is a low value, it won't collide with any real tile
    01424    *  number. */
    01425   uint num = (tile == INVALID_TILE) ? (int)type : tile;
    01426
    01427   assert(IsCompanyBuildableVehicleType(type));
    01428
    01429   DeleteWindowById(WC_BUILD_VEHICLE, num);
    01430
    01431   new BuildVehicleWindow(&_build_vehicle_desc, tile, type);
    01432 }