build_vehicle_gui.cpp

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