build_vehicle_gui.cpp

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