bridge_gui.cpp

Go to the documentation of this file.
00001 /* $Id: bridge_gui.cpp 21777 2011-01-14 12:00:07Z terkhen $ */
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 "gui.h"
00014 #include "command_func.h"
00015 #include "bridge.h"
00016 #include "rail.h"
00017 #include "strings_func.h"
00018 #include "window_func.h"
00019 #include "sound_func.h"
00020 #include "gfx_func.h"
00021 #include "tunnelbridge.h"
00022 #include "sortlist_type.h"
00023 #include "widgets/dropdown_func.h"
00024 #include "core/geometry_func.hpp"
00025 #include "openttd.h"
00026 #include "cmd_helper.h"
00027 #include "tunnelbridge_map.h"
00028 #include "road_gui.h"
00029 
00030 #include "table/strings.h"
00031 
00033 static BridgeType _last_railbridge_type = 0;
00035 static BridgeType _last_roadbridge_type = 0;
00036 
00040 struct BuildBridgeData {
00041   BridgeType index;
00042   const BridgeSpec *spec;
00043   Money cost;
00044 };
00045 
00046 typedef GUIList<BuildBridgeData> GUIBridgeList; 
00047 
00059 void CcBuildBridge(const CommandCost &result, TileIndex end_tile, uint32 p1, uint32 p2)
00060 {
00061   if (result.Failed()) return;
00062   SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, end_tile);
00063 
00064   TransportType transport_type = Extract<TransportType, 15, 2>(p2);
00065 
00066   if (transport_type == TRANSPORT_ROAD) {
00067     DiagDirection end_direction = ReverseDiagDir(GetTunnelBridgeDirection(end_tile));
00068     ConnectRoadToStructure(end_tile, end_direction);
00069 
00070     DiagDirection start_direction = ReverseDiagDir(GetTunnelBridgeDirection(p1));
00071     ConnectRoadToStructure(p1, start_direction);
00072   }
00073 }
00074 
00076 enum BuildBridgeSelectionWidgets {
00077   BBSW_CAPTION,
00078   BBSW_DROPDOWN_ORDER,
00079   BBSW_DROPDOWN_CRITERIA,
00080   BBSW_BRIDGE_LIST,
00081   BBSW_SCROLLBAR,
00082 };
00083 
00085 class BuildBridgeWindow : public Window {
00086 private:
00087   /* Runtime saved values */
00088   static uint16 last_size;     
00089   static Listing last_sorting; 
00090 
00091   /* Constants for sorting the bridges */
00092   static const StringID sorter_names[];
00093   static GUIBridgeList::SortFunction * const sorter_funcs[];
00094 
00095   /* Internal variables */
00096   TileIndex start_tile;
00097   TileIndex end_tile;
00098   uint32 type;
00099   GUIBridgeList *bridges;
00100   int bridgetext_offset; 
00101   Scrollbar *vscroll;
00102 
00104   static int CDECL BridgeIndexSorter(const BuildBridgeData *a, const BuildBridgeData *b)
00105   {
00106     return a->index - b->index;
00107   }
00108 
00110   static int CDECL BridgePriceSorter(const BuildBridgeData *a, const BuildBridgeData *b)
00111   {
00112     return a->cost - b->cost;
00113   }
00114 
00116   static int CDECL BridgeSpeedSorter(const BuildBridgeData *a, const BuildBridgeData *b)
00117   {
00118     return a->spec->speed - b->spec->speed;
00119   }
00120 
00121   void BuildBridge(uint8 i)
00122   {
00123     switch ((TransportType)(this->type >> 15)) {
00124       case TRANSPORT_RAIL: _last_railbridge_type = this->bridges->Get(i)->index; break;
00125       case TRANSPORT_ROAD: _last_roadbridge_type = this->bridges->Get(i)->index; break;
00126       default: break;
00127     }
00128     DoCommandP(this->end_tile, this->start_tile, this->type | this->bridges->Get(i)->index,
00129           CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
00130   }
00131 
00133   void SortBridgeList()
00134   {
00135     this->bridges->Sort();
00136 
00137     /* Display the current sort variant */
00138     this->GetWidget<NWidgetCore>(BBSW_DROPDOWN_CRITERIA)->widget_data = this->sorter_names[this->bridges->SortType()];
00139 
00140     /* Set the modified widgets dirty */
00141     this->SetWidgetDirty(BBSW_DROPDOWN_CRITERIA);
00142     this->SetWidgetDirty(BBSW_BRIDGE_LIST);
00143   }
00144 
00145 public:
00146   BuildBridgeWindow(const WindowDesc *desc, TileIndex start, TileIndex end, uint32 br_type, GUIBridgeList *bl) : Window(),
00147     start_tile(start),
00148     end_tile(end),
00149     type(br_type),
00150     bridges(bl)
00151   {
00152     this->CreateNestedTree(desc);
00153     this->vscroll = this->GetScrollbar(BBSW_SCROLLBAR);
00154     /* Change the data, or the caption of the gui. Set it to road or rail, accordingly. */
00155     this->GetWidget<NWidgetCore>(BBSW_CAPTION)->widget_data = (GB(this->type, 15, 2) == TRANSPORT_ROAD) ? STR_SELECT_ROAD_BRIDGE_CAPTION : STR_SELECT_RAIL_BRIDGE_CAPTION;
00156     this->FinishInitNested(desc, GB(br_type, 15, 2)); // Initializes 'this->bridgetext_offset'.
00157 
00158     this->parent = FindWindowById(WC_BUILD_TOOLBAR, GB(this->type, 15, 2));
00159     this->bridges->SetListing(this->last_sorting);
00160     this->bridges->SetSortFuncs(this->sorter_funcs);
00161     this->bridges->NeedResort();
00162     this->SortBridgeList();
00163 
00164     this->vscroll->SetCount(bl->Length());
00165     if (this->last_size < this->vscroll->GetCapacity()) this->last_size = this->vscroll->GetCapacity();
00166     if (this->last_size > this->vscroll->GetCount()) this->last_size = this->vscroll->GetCount();
00167     /* Resize the bridge selection window if we used a bigger one the last time. */
00168     if (this->last_size > this->vscroll->GetCapacity()) {
00169       ResizeWindow(this, 0, (this->last_size - this->vscroll->GetCapacity()) * this->resize.step_height);
00170     }
00171     this->GetWidget<NWidgetCore>(BBSW_BRIDGE_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00172   }
00173 
00174   ~BuildBridgeWindow()
00175   {
00176     this->last_sorting = this->bridges->GetListing();
00177 
00178     delete bridges;
00179   }
00180 
00181   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00182   {
00183     switch (widget) {
00184       case BBSW_DROPDOWN_ORDER: {
00185         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
00186         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
00187         d.height += padding.height;
00188         *size = maxdim(*size, d);
00189         break;
00190       }
00191       case BBSW_DROPDOWN_CRITERIA: {
00192         Dimension d = {0, 0};
00193         for (const StringID *str = this->sorter_names; *str != INVALID_STRING_ID; str++) {
00194           d = maxdim(d, GetStringBoundingBox(*str));
00195         }
00196         d.width += padding.width;
00197         d.height += padding.height;
00198         *size = maxdim(*size, d);
00199         break;
00200       }
00201       case BBSW_BRIDGE_LIST: {
00202         Dimension sprite_dim = {0, 0}; // Biggest bridge sprite dimension
00203         Dimension text_dim   = {0, 0}; // Biggest text dimension
00204         for (int i = 0; i < (int)this->bridges->Length(); i++) {
00205           const BridgeSpec *b = this->bridges->Get(i)->spec;
00206           sprite_dim = maxdim(sprite_dim, GetSpriteSize(b->sprite));
00207 
00208           SetDParam(2, this->bridges->Get(i)->cost);
00209           SetDParam(1, b->speed);
00210           SetDParam(0, b->material);
00211           text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
00212         }
00213         sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
00214         text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
00215         resize->height = max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
00216 
00217         this->bridgetext_offset = WD_MATRIX_LEFT + sprite_dim.width + 1; // Left edge of text, 1 pixel distance from the sprite.
00218         size->width = this->bridgetext_offset + text_dim.width + WD_MATRIX_RIGHT;
00219         size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
00220         break;
00221       }
00222     }
00223   }
00224 
00225   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
00226   {
00227     /* Position the window so hopefully the first bridge from the list is under the mouse pointer. */
00228     NWidgetBase *list = this->GetWidget<NWidgetBase>(BBSW_BRIDGE_LIST);
00229     Point corner; // point of the top left corner of the window.
00230     corner.y = Clamp(_cursor.pos.y - list->pos_y - 5, GetMainViewTop(), GetMainViewBottom() - sm_height);
00231     corner.x = Clamp(_cursor.pos.x - list->pos_x - 5, 0, _screen.width - sm_width);
00232     return corner;
00233   }
00234 
00235   virtual void DrawWidget(const Rect &r, int widget) const
00236   {
00237     switch (widget) {
00238       case BBSW_DROPDOWN_ORDER:
00239         this->DrawSortButtonState(widget, this->bridges->IsDescSortOrder() ? SBS_DOWN : SBS_UP);
00240         break;
00241 
00242       case BBSW_BRIDGE_LIST: {
00243         uint y = r.top;
00244         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < (int)this->bridges->Length(); i++) {
00245           const BridgeSpec *b = this->bridges->Get(i)->spec;
00246 
00247           SetDParam(2, this->bridges->Get(i)->cost);
00248           SetDParam(1, b->speed);
00249           SetDParam(0, b->material);
00250 
00251           DrawSprite(b->sprite, b->pal, r.left + WD_MATRIX_LEFT, y + this->resize.step_height - 1 - GetSpriteSize(b->sprite).height);
00252           DrawStringMultiLine(r.left + this->bridgetext_offset, r.right, y + 2, y + this->resize.step_height,
00253               _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
00254           y += this->resize.step_height;
00255         }
00256         break;
00257       }
00258     }
00259   }
00260 
00261   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
00262   {
00263     const uint8 i = keycode - '1';
00264     if (i < 9 && i < this->bridges->Length()) {
00265       /* Build the requested bridge */
00266       this->BuildBridge(i);
00267       delete this;
00268       return ES_HANDLED;
00269     }
00270     return ES_NOT_HANDLED;
00271   }
00272 
00273   virtual void OnClick(Point pt, int widget, int click_count)
00274   {
00275     switch (widget) {
00276       default: break;
00277       case BBSW_BRIDGE_LIST: {
00278         uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, BBSW_BRIDGE_LIST);
00279         if (i < this->bridges->Length()) {
00280           this->BuildBridge(i);
00281           delete this;
00282         }
00283         break;
00284       }
00285 
00286       case BBSW_DROPDOWN_ORDER:
00287         this->bridges->ToggleSortOrder();
00288         this->SetDirty();
00289         break;
00290 
00291       case BBSW_DROPDOWN_CRITERIA:
00292         ShowDropDownMenu(this, this->sorter_names, this->bridges->SortType(), BBSW_DROPDOWN_CRITERIA, 0, 0);
00293         break;
00294     }
00295   }
00296 
00297   virtual void OnDropdownSelect(int widget, int index)
00298   {
00299     if (widget == BBSW_DROPDOWN_CRITERIA && this->bridges->SortType() != index) {
00300       this->bridges->SetSortType(index);
00301 
00302       this->SortBridgeList();
00303     }
00304   }
00305 
00306   virtual void OnResize()
00307   {
00308     this->vscroll->SetCapacityFromWidget(this, BBSW_BRIDGE_LIST);
00309     this->GetWidget<NWidgetCore>(BBSW_BRIDGE_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00310 
00311     this->last_size = max(this->vscroll->GetCapacity(), this->last_size);
00312   }
00313 };
00314 
00316 uint16 BuildBridgeWindow::last_size = 4;
00318 Listing BuildBridgeWindow::last_sorting = {true, 2};
00319 
00321 GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
00322   &BridgeIndexSorter,
00323   &BridgePriceSorter,
00324   &BridgeSpeedSorter
00325 };
00326 
00328 const StringID BuildBridgeWindow::sorter_names[] = {
00329   STR_SORT_BY_NUMBER,
00330   STR_SORT_BY_COST,
00331   STR_SORT_BY_MAX_SPEED,
00332   INVALID_STRING_ID
00333 };
00334 
00336 static const NWidgetPart _nested_build_bridge_widgets[] = {
00337   /* Header */
00338   NWidget(NWID_HORIZONTAL),
00339     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
00340     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, BBSW_CAPTION), SetDataTip(STR_SELECT_RAIL_BRIDGE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00341   EndContainer(),
00342 
00343   NWidget(NWID_HORIZONTAL),
00344     NWidget(NWID_VERTICAL),
00345       /* Sort order + criteria buttons */
00346       NWidget(NWID_HORIZONTAL),
00347         NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, BBSW_DROPDOWN_ORDER), SetFill(1, 0), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00348         NWidget(WWT_DROPDOWN, COLOUR_DARK_GREEN, BBSW_DROPDOWN_CRITERIA), SetFill(1, 0), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
00349       EndContainer(),
00350       /* Matrix. */
00351       NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, BBSW_BRIDGE_LIST), SetFill(1, 0), SetResize(0, 22), SetDataTip(0x401, STR_SELECT_BRIDGE_SELECTION_TOOLTIP), SetScrollbar(BBSW_SCROLLBAR),
00352     EndContainer(),
00353 
00354     /* scrollbar + resize button */
00355     NWidget(NWID_VERTICAL),
00356       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, BBSW_SCROLLBAR),
00357       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
00358     EndContainer(),
00359   EndContainer(),
00360 };
00361 
00363 static const WindowDesc _build_bridge_desc(
00364   WDP_AUTO, 200, 114,
00365   WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
00366   WDF_CONSTRUCTION,
00367   _nested_build_bridge_widgets, lengthof(_nested_build_bridge_widgets)
00368 );
00369 
00380 void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
00381 {
00382   DeleteWindowByClass(WC_BUILD_BRIDGE);
00383 
00384   /* Data type for the bridge.
00385    * Bit 16,15 = transport type,
00386    *     14..8 = road/rail types,
00387    *      7..0 = type of bridge */
00388   uint32 type = (transport_type << 15) | (road_rail_type << 8);
00389 
00390   /* The bridge length without ramps. */
00391   const uint bridge_len = GetTunnelBridgeLength(start, end);
00392 
00393   /* If Ctrl is being pressed, check wether the last bridge built is available
00394    * If so, return this bridge type. Otherwise continue normally.
00395    * We store bridge types for each transport type, so we have to check for
00396    * the transport type beforehand.
00397    */
00398   BridgeType last_bridge_type = 0;
00399   switch (transport_type) {
00400     case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
00401     case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
00402     default: break; // water ways and air routes don't have bridge types
00403   }
00404   if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
00405     DoCommandP(end, start, type | last_bridge_type, CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
00406     return;
00407   }
00408 
00409   /* only query bridge building possibility once, result is the same for all bridges!
00410    * returns CMD_ERROR on failure, and price on success */
00411   StringID errmsg = INVALID_STRING_ID;
00412   CommandCost ret = DoCommand(end, start, type, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)) | DC_QUERY_COST, CMD_BUILD_BRIDGE);
00413 
00414   GUIBridgeList *bl = NULL;
00415   if (ret.Failed()) {
00416     errmsg = ret.GetErrorMessage();
00417   } else {
00418     /* check which bridges can be built */
00419     const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
00420 
00421     bl = new GUIBridgeList();
00422 
00423     Money infra_cost = 0;
00424     switch (transport_type) {
00425       case TRANSPORT_ROAD: infra_cost = (bridge_len + 2) * _price[PR_BUILD_ROAD] * 2; break;
00426       case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
00427       default: break;
00428     }
00429 
00430     /* loop for all bridgetypes */
00431     for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
00432       if (CheckBridgeAvailability(brd_type, bridge_len).Succeeded()) {
00433         /* bridge is accepted, add to list */
00434         BuildBridgeData *item = bl->Append();
00435         item->index = brd_type;
00436         item->spec = GetBridgeSpec(brd_type);
00437         /* Add to terraforming & bulldozing costs the cost of the
00438          * bridge itself (not computed with DC_QUERY_COST) */
00439         item->cost = ret.GetCost() + (((int64)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item->spec->price) >> 8) + infra_cost;
00440       }
00441     }
00442   }
00443 
00444   if (bl != NULL && bl->Length() != 0) {
00445     new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
00446   } else {
00447     delete bl;
00448     ShowErrorMessage(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, errmsg, WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);
00449   }
00450 }

Generated on Thu Jan 20 22:57:32 2011 for OpenTTD by  doxygen 1.6.1