build_vehicle_gui.cpp

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