Fix ICU iterators on leading/trailing whitespace
[openttd/fttd.git] / src / bridge_gui.cpp
blob3edf08a7394c1922d27bd28a7f38356396796923
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file bridge_gui.cpp Graphical user interface for bridge construction */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "command_func.h"
15 #include "rail.h"
16 #include "strings_func.h"
17 #include "window_func.h"
18 #include "sound_func.h"
19 #include "gfx_func.h"
20 #include "tunnelbridge.h"
21 #include "sortlist_type.h"
22 #include "widgets/dropdown_func.h"
23 #include "core/geometry_func.hpp"
24 #include "cmd_helper.h"
25 #include "bridge.h"
26 #include "map/common.h"
27 #include "map/road.h"
28 #include "map/tunnelbridge.h"
29 #include "road_gui.h"
31 #include "widgets/bridge_widget.h"
33 #include "table/strings.h"
35 /** The type of the last built rail bridge */
36 static BridgeType _last_railbridge_type = 0;
37 /** The type of the last built road bridge */
38 static BridgeType _last_roadbridge_type = 0;
40 /**
41 * Carriage for the data we need if we want to build a bridge
43 struct BuildBridgeData {
44 BridgeType index;
45 const BridgeSpec *spec;
46 Money cost;
49 typedef GUIList<BuildBridgeData> GUIBridgeList; ///< List of bridges, used in #BuildBridgeWindow.
51 /**
52 * Callback executed after a build Bridge CMD has been called
54 * @param result Whether the build succeeded
55 * @param end_tile End tile of the bridge.
56 * @param p1 packed start tile coords (~ dx)
57 * @param p2 various bitstuffed elements
58 * - p2 = (bit 0- 7) - bridge type (hi bh)
59 * - p2 = (bit 8-11) - rail type or road types.
60 * - p2 = (bit 12-13) - transport type.
62 void CcBuildBridge(const CommandCost &result, TileIndex end_tile, uint32 p1, uint32 p2)
64 if (result.Failed()) return;
65 if (_settings_client.sound.confirm) SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, end_tile);
67 TransportType transport_type = Extract<TransportType, 12, 2>(p2);
69 if (transport_type == TRANSPORT_ROAD) {
70 DiagDirection end_direction = ReverseDiagDir(GetTunnelBridgeDirection(end_tile));
71 ConnectRoadToStructure(end_tile, end_direction);
73 DiagDirection start_direction = ReverseDiagDir(GetTunnelBridgeDirection(p1));
74 ConnectRoadToStructure(p1, start_direction);
78 /** Window class for handling the bridge-build GUI. */
79 class BuildBridgeWindow : public Window {
80 private:
81 /* Runtime saved values */
82 static Listing last_sorting; ///< Last setting of the sort.
84 /* Constants for sorting the bridges */
85 static const StringID sorter_names[];
86 static GUIBridgeList::SortFunction * const sorter_funcs[];
88 /* Internal variables */
89 TileIndex start_tile;
90 TileIndex end_tile;
91 uint32 type;
92 GUIBridgeList *bridges;
93 int bridgetext_offset; ///< Horizontal offset of the text describing the bridge properties in #WID_BBS_BRIDGE_LIST relative to the left edge.
94 Scrollbar *vscroll;
96 /** Sort the bridges by their index */
97 static int CDECL BridgeIndexSorter(const BuildBridgeData *a, const BuildBridgeData *b)
99 return a->index - b->index;
102 /** Sort the bridges by their price */
103 static int CDECL BridgePriceSorter(const BuildBridgeData *a, const BuildBridgeData *b)
105 return a->cost - b->cost;
108 /** Sort the bridges by their maximum speed */
109 static int CDECL BridgeSpeedSorter(const BuildBridgeData *a, const BuildBridgeData *b)
111 return a->spec->speed - b->spec->speed;
114 void BuildBridge(uint8 i)
116 switch ((TransportType)(this->type >> 12)) {
117 case TRANSPORT_RAIL: _last_railbridge_type = this->bridges->Get(i)->index; break;
118 case TRANSPORT_ROAD: _last_roadbridge_type = this->bridges->Get(i)->index; break;
119 default: break;
121 DoCommandP(this->end_tile, this->start_tile, this->type | this->bridges->Get(i)->index,
122 CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
125 /** Sort the builable bridges */
126 void SortBridgeList()
128 this->bridges->Sort();
130 /* Display the current sort variant */
131 this->GetWidget<NWidgetCore>(WID_BBS_DROPDOWN_CRITERIA)->widget_data = this->sorter_names[this->bridges->SortType()];
133 /* Set the modified widgets dirty */
134 this->SetWidgetDirty(WID_BBS_DROPDOWN_CRITERIA);
135 this->SetWidgetDirty(WID_BBS_BRIDGE_LIST);
138 public:
139 BuildBridgeWindow(WindowDesc *desc, TileIndex start, TileIndex end, uint32 br_type, GUIBridgeList *bl) : Window(desc),
140 start_tile(start),
141 end_tile(end),
142 type(br_type),
143 bridges(bl)
145 this->CreateNestedTree();
146 this->vscroll = this->GetScrollbar(WID_BBS_SCROLLBAR);
147 /* Change the data, or the caption of the gui. Set it to road or rail, accordingly. */
148 this->GetWidget<NWidgetCore>(WID_BBS_CAPTION)->widget_data = (GB(this->type, 15, 2) == TRANSPORT_ROAD) ? STR_SELECT_ROAD_BRIDGE_CAPTION : STR_SELECT_RAIL_BRIDGE_CAPTION;
149 this->FinishInitNested(GB(br_type, 12, 2)); // Initializes 'this->bridgetext_offset'.
151 this->parent = FindWindowById(WC_BUILD_TOOLBAR, GB(this->type, 12, 2));
152 this->bridges->SetListing(this->last_sorting);
153 this->bridges->SetSortFuncs(this->sorter_funcs);
154 this->bridges->NeedResort();
155 this->SortBridgeList();
157 this->vscroll->SetCount(bl->Length());
160 ~BuildBridgeWindow()
162 this->last_sorting = this->bridges->GetListing();
164 delete bridges;
167 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
169 switch (widget) {
170 case WID_BBS_DROPDOWN_ORDER: {
171 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
172 d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
173 d.height += padding.height;
174 *size = maxdim(*size, d);
175 break;
177 case WID_BBS_DROPDOWN_CRITERIA: {
178 Dimension d = {0, 0};
179 for (const StringID *str = this->sorter_names; *str != INVALID_STRING_ID; str++) {
180 d = maxdim(d, GetStringBoundingBox(*str));
182 d.width += padding.width;
183 d.height += padding.height;
184 *size = maxdim(*size, d);
185 break;
187 case WID_BBS_BRIDGE_LIST: {
188 Dimension sprite_dim = {0, 0}; // Biggest bridge sprite dimension
189 Dimension text_dim = {0, 0}; // Biggest text dimension
190 for (int i = 0; i < (int)this->bridges->Length(); i++) {
191 const BridgeSpec *b = this->bridges->Get(i)->spec;
192 sprite_dim = maxdim(sprite_dim, GetSpriteSize(b->sprite));
194 SetDParam(2, this->bridges->Get(i)->cost);
195 SetDParam(1, b->speed);
196 SetDParam(0, b->material);
197 text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
199 sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
200 text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
201 resize->height = max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
203 this->bridgetext_offset = WD_MATRIX_LEFT + sprite_dim.width + 1; // Left edge of text, 1 pixel distance from the sprite.
204 size->width = this->bridgetext_offset + text_dim.width + WD_MATRIX_RIGHT;
205 size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
206 break;
211 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
213 /* Position the window so hopefully the first bridge from the list is under the mouse pointer. */
214 NWidgetBase *list = this->GetWidget<NWidgetBase>(WID_BBS_BRIDGE_LIST);
215 Point corner; // point of the top left corner of the window.
216 corner.y = Clamp(_cursor.pos.y - list->pos_y - 5, GetMainViewTop(), GetMainViewBottom() - sm_height);
217 corner.x = Clamp(_cursor.pos.x - list->pos_x - 5, 0, _screen.width - sm_width);
218 return corner;
221 virtual void DrawWidget(const Rect &r, int widget) const
223 switch (widget) {
224 case WID_BBS_DROPDOWN_ORDER:
225 this->DrawSortButtonState(widget, this->bridges->IsDescSortOrder() ? SBS_DOWN : SBS_UP);
226 break;
228 case WID_BBS_BRIDGE_LIST: {
229 uint y = r.top;
230 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < (int)this->bridges->Length(); i++) {
231 const BridgeSpec *b = this->bridges->Get(i)->spec;
233 SetDParam(2, this->bridges->Get(i)->cost);
234 SetDParam(1, b->speed);
235 SetDParam(0, b->material);
237 DrawSprite(b->sprite, b->pal, r.left + WD_MATRIX_LEFT, y + this->resize.step_height - 1 - GetSpriteSize(b->sprite).height);
238 DrawStringMultiLine(r.left + this->bridgetext_offset, r.right, y + 2, y + this->resize.step_height,
239 _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
240 y += this->resize.step_height;
242 break;
247 virtual EventState OnKeyPress(WChar key, uint16 keycode)
249 const uint8 i = keycode - '1';
250 if (i < 9 && i < this->bridges->Length()) {
251 /* Build the requested bridge */
252 this->BuildBridge(i);
253 delete this;
254 return ES_HANDLED;
256 return ES_NOT_HANDLED;
259 virtual void OnClick(Point pt, int widget, int click_count)
261 switch (widget) {
262 default: break;
263 case WID_BBS_BRIDGE_LIST: {
264 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BBS_BRIDGE_LIST);
265 if (i < this->bridges->Length()) {
266 this->BuildBridge(i);
267 delete this;
269 break;
272 case WID_BBS_DROPDOWN_ORDER:
273 this->bridges->ToggleSortOrder();
274 this->SetDirty();
275 break;
277 case WID_BBS_DROPDOWN_CRITERIA:
278 ShowDropDownMenu(this, this->sorter_names, this->bridges->SortType(), WID_BBS_DROPDOWN_CRITERIA, 0, 0);
279 break;
283 virtual void OnDropdownSelect(int widget, int index)
285 if (widget == WID_BBS_DROPDOWN_CRITERIA && this->bridges->SortType() != index) {
286 this->bridges->SetSortType(index);
288 this->SortBridgeList();
292 virtual void OnResize()
294 this->vscroll->SetCapacityFromWidget(this, WID_BBS_BRIDGE_LIST);
298 /** Set the default sorting for the bridges */
299 Listing BuildBridgeWindow::last_sorting = {true, 2};
301 /** Available bridge sorting functions. */
302 GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
303 &BridgeIndexSorter,
304 &BridgePriceSorter,
305 &BridgeSpeedSorter
308 /** Names of the sorting functions. */
309 const StringID BuildBridgeWindow::sorter_names[] = {
310 STR_SORT_BY_NUMBER,
311 STR_SORT_BY_COST,
312 STR_SORT_BY_MAX_SPEED,
313 INVALID_STRING_ID
316 /** Widgets of the bridge gui. */
317 static const NWidgetPart _nested_build_bridge_widgets[] = {
318 /* Header */
319 NWidget(NWID_HORIZONTAL),
320 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
321 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_BBS_CAPTION), SetDataTip(STR_SELECT_RAIL_BRIDGE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
322 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
323 EndContainer(),
325 NWidget(NWID_HORIZONTAL),
326 NWidget(NWID_VERTICAL),
327 /* Sort order + criteria buttons */
328 NWidget(NWID_HORIZONTAL),
329 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_ORDER), SetFill(1, 0), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
330 NWidget(WWT_DROPDOWN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_CRITERIA), SetFill(1, 0), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
331 EndContainer(),
332 /* Matrix. */
333 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_BBS_BRIDGE_LIST), SetFill(1, 0), SetResize(0, 22), SetMatrixDataTip(1, 0, STR_SELECT_BRIDGE_SELECTION_TOOLTIP), SetScrollbar(WID_BBS_SCROLLBAR),
334 EndContainer(),
336 /* scrollbar + resize button */
337 NWidget(NWID_VERTICAL),
338 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BBS_SCROLLBAR),
339 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
340 EndContainer(),
341 EndContainer(),
344 /** Window definition for the rail bridge selection window. */
345 static WindowDesc _build_bridge_desc(
346 WDP_AUTO, "build_bridge", 200, 114,
347 WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
348 WDF_CONSTRUCTION,
349 _nested_build_bridge_widgets, lengthof(_nested_build_bridge_widgets)
353 * Prepare the data for the build a bridge window.
354 * If we can't build a bridge under the given conditions
355 * show an error message.
357 * @param start The start tile of the bridge
358 * @param end The end tile of the bridge
359 * @param transport_type The transport type
360 * @param road_rail_type The road/rail type
362 void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
364 DeleteWindowByClass(WC_BUILD_BRIDGE);
366 /* Data type for the bridge.
367 * Bit 13,12 = transport type,
368 * 11..8 = road/rail types,
369 * 7..0 = type of bridge */
370 uint32 type = (transport_type << 12) | (road_rail_type << 8);
372 /* The bridge length without ramps. */
373 const uint bridge_len = GetTunnelBridgeLength(start, end);
375 /* If Ctrl is being pressed, check whether the last bridge built is available
376 * If so, return this bridge type. Otherwise continue normally.
377 * We store bridge types for each transport type, so we have to check for
378 * the transport type beforehand.
380 BridgeType last_bridge_type = 0;
381 switch (transport_type) {
382 case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
383 case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
384 default: break; // water ways and air routes don't have bridge types
386 if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
387 DoCommandP(end, start, type | last_bridge_type, CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
388 return;
391 /* only query bridge building possibility once, result is the same for all bridges!
392 * returns CMD_ERROR on failure, and price on success */
393 StringID errmsg = INVALID_STRING_ID;
394 CommandCost ret = DoCommand(end, start, type, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)) | DC_QUERY_COST, CMD_BUILD_BRIDGE);
396 GUIBridgeList *bl = NULL;
397 if (ret.Failed()) {
398 errmsg = ret.GetErrorMessage();
399 } else {
400 /* check which bridges can be built */
401 const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
403 bl = new GUIBridgeList();
405 Money infra_cost = 0;
406 switch (transport_type) {
407 case TRANSPORT_ROAD:
408 infra_cost = (bridge_len + 2) * _price[PR_BUILD_ROAD] * 2;
409 /* In case we add a new road type as well, we must be aware of those costs. */
410 if (IsRoadBridgeTile(start)) infra_cost *= CountBits(GetRoadTypes(start) | (RoadTypes)road_rail_type);
411 break;
412 case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
413 default: break;
416 /* loop for all bridgetypes */
417 for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
418 if (CheckBridgeAvailability(brd_type, bridge_len).Succeeded()) {
419 /* bridge is accepted, add to list */
420 BuildBridgeData *item = bl->Append();
421 item->index = brd_type;
422 item->spec = GetBridgeSpec(brd_type);
423 /* Add to terraforming & bulldozing costs the cost of the
424 * bridge itself (not computed with DC_QUERY_COST) */
425 item->cost = ret.GetCost() + (((int64)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item->spec->price) >> 8) + infra_cost;
430 if (bl != NULL && bl->Length() != 0) {
431 new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
432 } else {
433 delete bl;
434 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, errmsg, WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);