(svn r27729) -Codechange: Do not count static NewGRF when checking for the maximum...
[openttd.git] / src / industry_gui.cpp
blobc16014224946101eb8bbea19392539cc8c9790e1
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 industry_gui.cpp GUIs related to industries. */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "gui.h"
15 #include "settings_gui.h"
16 #include "sound_func.h"
17 #include "window_func.h"
18 #include "textbuf_gui.h"
19 #include "command_func.h"
20 #include "viewport_func.h"
21 #include "industry.h"
22 #include "town.h"
23 #include "cheat_type.h"
24 #include "newgrf_industries.h"
25 #include "newgrf_text.h"
26 #include "newgrf_debug.h"
27 #include "network/network.h"
28 #include "strings_func.h"
29 #include "company_func.h"
30 #include "tilehighlight_func.h"
31 #include "string_func.h"
32 #include "sortlist_type.h"
33 #include "widgets/dropdown_func.h"
34 #include "company_base.h"
35 #include "core/geometry_func.hpp"
36 #include "core/random_func.hpp"
37 #include "core/backup_type.hpp"
38 #include "genworld.h"
39 #include "smallmap_gui.h"
40 #include "widgets/dropdown_type.h"
41 #include "widgets/industry_widget.h"
43 #include "table/strings.h"
45 #include <bitset>
47 #include "safeguards.h"
49 bool _ignore_restrictions;
50 std::bitset<NUM_INDUSTRYTYPES> _displayed_industries; ///< Communication from the industry chain window to the smallmap window about what industries to display.
52 /** Cargo suffix type (for which window is it requested) */
53 enum CargoSuffixType {
54 CST_FUND, ///< Fund-industry window
55 CST_VIEW, ///< View-industry window
56 CST_DIR, ///< Industry-directory window
59 static void ShowIndustryCargoesWindow(IndustryType id);
61 /**
62 * Gets the string to display after the cargo name (using callback 37)
63 * @param cargo the cargo for which the suffix is requested
64 * - 00 - first accepted cargo type
65 * - 01 - second accepted cargo type
66 * - 02 - third accepted cargo type
67 * - 03 - first produced cargo type
68 * - 04 - second produced cargo type
69 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
70 * @param ind the industry (NULL if in fund window)
71 * @param ind_type the industry type
72 * @param indspec the industry spec
73 * @param suffix is filled with the string to display
74 * @param suffix_last lastof(suffix)
76 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, char *suffix, const char *suffix_last)
78 suffix[0] = '\0';
79 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
80 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, (cst != CST_FUND) ? ind->location.tile : INVALID_TILE);
81 if (callback == CALLBACK_FAILED || callback == 0x400) return;
82 if (callback > 0x400) {
83 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
84 } else if (indspec->grf_prop.grffile->grf_version >= 8 || GB(callback, 0, 8) != 0xFF) {
85 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
86 GetString(suffix, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), suffix_last);
87 StopTextRefStackUsage();
92 /**
93 * Gets all strings to display after the cargoes of industries (using callback 37)
94 * @param cb_offset The offset for the cargo used in cb37, 0 for accepted cargoes, 3 for produced cargoes
95 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
96 * @param ind the industry (NULL if in fund window)
97 * @param ind_type the industry type
98 * @param indspec the industry spec
99 * @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
100 * @param suffixes is filled with the suffixes
102 template <typename TC, typename TS>
103 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
105 assert_compile(lengthof(cargoes) <= lengthof(suffixes));
106 for (uint j = 0; j < lengthof(cargoes); j++) {
107 if (cargoes[j] != CT_INVALID) {
108 GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j], lastof(suffixes[j]));
109 } else {
110 suffixes[j][0] = '\0';
115 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES]; ///< Industry types sorted by name.
117 /** Sort industry types by their name. */
118 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
120 static char industry_name[2][64];
122 const IndustrySpec *indsp1 = GetIndustrySpec(*a);
123 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
125 const IndustrySpec *indsp2 = GetIndustrySpec(*b);
126 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
128 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
130 /* If the names are equal, sort by industry type. */
131 return (r != 0) ? r : (*a - *b);
135 * Initialize the list of sorted industry types.
137 void SortIndustryTypes()
139 /* Add each industry type to the list. */
140 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
141 _sorted_industry_types[i] = i;
144 /* Sort industry types by name. */
145 QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
149 * Command callback. In case of failure to build an industry, show an error message.
150 * @param result Result of the command.
151 * @param tile Tile where the industry is placed.
152 * @param p1 Additional data of the #CMD_BUILD_INDUSTRY command.
153 * @param p2 Additional data of the #CMD_BUILD_INDUSTRY command.
155 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
157 if (result.Succeeded()) return;
159 uint8 indtype = GB(p1, 0, 8);
160 if (indtype < NUM_INDUSTRYTYPES) {
161 const IndustrySpec *indsp = GetIndustrySpec(indtype);
162 if (indsp->enabled) {
163 SetDParam(0, indsp->name);
164 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
169 static const NWidgetPart _nested_build_industry_widgets[] = {
170 NWidget(NWID_HORIZONTAL),
171 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
172 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
173 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
174 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
175 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
176 EndContainer(),
177 NWidget(NWID_HORIZONTAL),
178 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_DPI_MATRIX_WIDGET), SetMatrixDataTip(1, 0, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_DPI_SCROLLBAR),
179 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
180 EndContainer(),
181 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
182 EndContainer(),
183 NWidget(NWID_HORIZONTAL),
184 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
185 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
186 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
187 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
188 EndContainer(),
191 /** Window definition of the dynamic place industries gui */
192 static WindowDesc _build_industry_desc(
193 WDP_AUTO, "build_industry", 170, 212,
194 WC_BUILD_INDUSTRY, WC_NONE,
195 WDF_CONSTRUCTION,
196 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
199 /** Build (fund or prospect) a new industry, */
200 class BuildIndustryWindow : public Window {
201 int selected_index; ///< index of the element in the matrix
202 IndustryType selected_type; ///< industry corresponding to the above index
203 uint16 callback_timer; ///< timer counter for callback eventual verification
204 bool timer_enabled; ///< timer can be used
205 uint16 count; ///< How many industries are loaded
206 IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
207 bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
208 Scrollbar *vscroll;
210 /** The offset for the text in the matrix. */
211 static const int MATRIX_TEXT_OFFSET = 17;
213 void SetupArrays()
215 this->count = 0;
217 for (uint i = 0; i < lengthof(this->index); i++) {
218 this->index[i] = INVALID_INDUSTRYTYPE;
219 this->enabled[i] = false;
222 if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
223 this->index[this->count] = INVALID_INDUSTRYTYPE;
224 this->enabled[this->count] = true;
225 this->count++;
226 this->timer_enabled = false;
228 /* Fill the arrays with industries.
229 * The tests performed after the enabled allow to load the industries
230 * In the same way they are inserted by grf (if any)
232 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
233 IndustryType ind = _sorted_industry_types[i];
234 const IndustrySpec *indsp = GetIndustrySpec(ind);
235 if (indsp->enabled) {
236 /* Rule is that editor mode loads all industries.
237 * In game mode, all non raw industries are loaded too
238 * and raw ones are loaded only when setting allows it */
239 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
240 /* Unselect if the industry is no longer in the list */
241 if (this->selected_type == ind) this->selected_index = -1;
242 continue;
244 this->index[this->count] = ind;
245 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
246 /* Keep the selection to the correct line */
247 if (this->selected_type == ind) this->selected_index = this->count;
248 this->count++;
252 /* first industry type is selected if the current selection is invalid.
253 * I'll be damned if there are none available ;) */
254 if (this->selected_index == -1) {
255 this->selected_index = 0;
256 this->selected_type = this->index[0];
259 this->vscroll->SetCount(this->count);
262 /** Update status of the fund and display-chain widgets. */
263 void SetButtons()
265 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
266 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
269 public:
270 BuildIndustryWindow() : Window(&_build_industry_desc)
272 this->timer_enabled = _loaded_newgrf_features.has_newindustries;
274 this->selected_index = -1;
275 this->selected_type = INVALID_INDUSTRYTYPE;
277 this->callback_timer = DAY_TICKS;
279 this->CreateNestedTree();
280 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
281 this->FinishInitNested(0);
283 this->SetButtons();
286 virtual void OnInit()
288 this->SetupArrays();
291 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
293 switch (widget) {
294 case WID_DPI_MATRIX_WIDGET: {
295 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
296 for (byte i = 0; i < this->count; i++) {
297 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
298 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
300 resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
301 d.width += MATRIX_TEXT_OFFSET + padding.width;
302 d.height = 5 * resize->height;
303 *size = maxdim(*size, d);
304 break;
307 case WID_DPI_INFOPANEL: {
308 /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
309 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
310 Dimension d = {0, 0};
311 for (byte i = 0; i < this->count; i++) {
312 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
314 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
316 char cargo_suffix[3][512];
317 GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
318 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
319 byte p = 0;
320 SetDParam(0, STR_JUST_NOTHING);
321 SetDParamStr(1, "");
322 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
323 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
324 if (p > 0) str++;
325 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
326 SetDParamStr(p++, cargo_suffix[j]);
328 d = maxdim(d, GetStringBoundingBox(str));
330 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
331 GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
332 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
333 p = 0;
334 SetDParam(0, STR_JUST_NOTHING);
335 SetDParamStr(1, "");
336 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
337 if (indsp->produced_cargo[j] == CT_INVALID) continue;
338 if (p > 0) str++;
339 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
340 SetDParamStr(p++, cargo_suffix[j]);
342 d = maxdim(d, GetStringBoundingBox(str));
345 /* Set it to something more sane :) */
346 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
347 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
348 break;
351 case WID_DPI_FUND_WIDGET: {
352 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
353 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
354 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
355 d.width += padding.width;
356 d.height += padding.height;
357 *size = maxdim(*size, d);
358 break;
363 virtual void SetStringParameters(int widget) const
365 switch (widget) {
366 case WID_DPI_FUND_WIDGET:
367 /* Raw industries might be prospected. Show this fact by changing the string
368 * In Editor, you just build, while ingame, or you fund or you prospect */
369 if (_game_mode == GM_EDITOR) {
370 /* We've chosen many random industries but no industries have been specified */
371 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
372 } else {
373 const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
374 SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
376 break;
380 virtual void DrawWidget(const Rect &r, int widget) const
382 switch (widget) {
383 case WID_DPI_MATRIX_WIDGET: {
384 uint text_left, text_right, icon_left, icon_right;
385 if (_current_text_dir == TD_RTL) {
386 icon_right = r.right - WD_MATRIX_RIGHT;
387 icon_left = icon_right - 10;
388 text_right = icon_right - BuildIndustryWindow::MATRIX_TEXT_OFFSET;
389 text_left = r.left + WD_MATRIX_LEFT;
390 } else {
391 icon_left = r.left + WD_MATRIX_LEFT;
392 icon_right = icon_left + 10;
393 text_left = icon_left + BuildIndustryWindow::MATRIX_TEXT_OFFSET;
394 text_right = r.right - WD_MATRIX_RIGHT;
397 for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
398 int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
399 bool selected = this->selected_index == i + this->vscroll->GetPosition();
401 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
402 DrawString(text_left, text_right, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
403 continue;
405 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
407 /* Draw the name of the industry in white is selected, otherwise, in orange */
408 DrawString(text_left, text_right, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
409 GfxFillRect(icon_left, y + 1, icon_right, y + 7, selected ? PC_WHITE : PC_BLACK);
410 GfxFillRect(icon_left + 1, y + 2, icon_right - 1, y + 6, indsp->map_colour);
412 break;
415 case WID_DPI_INFOPANEL: {
416 int y = r.top + WD_FRAMERECT_TOP;
417 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
418 int left = r.left + WD_FRAMERECT_LEFT;
419 int right = r.right - WD_FRAMERECT_RIGHT;
421 if (this->selected_type == INVALID_INDUSTRYTYPE) {
422 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
423 break;
426 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
428 if (_game_mode != GM_EDITOR) {
429 SetDParam(0, indsp->GetConstructionCost());
430 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
431 y += FONT_HEIGHT_NORMAL;
434 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
435 char cargo_suffix[3][512];
436 GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
437 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
438 byte p = 0;
439 SetDParam(0, STR_JUST_NOTHING);
440 SetDParamStr(1, "");
441 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
442 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
443 if (p > 0) str++;
444 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
445 SetDParamStr(p++, cargo_suffix[j]);
447 DrawString(left, right, y, str);
448 y += FONT_HEIGHT_NORMAL;
450 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
451 GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
452 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
453 p = 0;
454 SetDParam(0, STR_JUST_NOTHING);
455 SetDParamStr(1, "");
456 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
457 if (indsp->produced_cargo[j] == CT_INVALID) continue;
458 if (p > 0) str++;
459 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
460 SetDParamStr(p++, cargo_suffix[j]);
462 DrawString(left, right, y, str);
463 y += FONT_HEIGHT_NORMAL;
465 /* Get the additional purchase info text, if it has not already been queried. */
466 str = STR_NULL;
467 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
468 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
469 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
470 if (callback_res > 0x400) {
471 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
472 } else {
473 str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
474 if (str != STR_UNDEFINED) {
475 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
476 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
477 StopTextRefStackUsage();
482 break;
487 virtual void OnClick(Point pt, int widget, int click_count)
489 switch (widget) {
490 case WID_DPI_MATRIX_WIDGET: {
491 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
492 if (y < this->count) { // Is it within the boundaries of available data?
493 this->selected_index = y;
494 this->selected_type = this->index[y];
495 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
497 this->SetDirty();
499 if (_thd.GetCallbackWnd() == this &&
500 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
501 this->selected_type == INVALID_INDUSTRYTYPE ||
502 !this->enabled[this->selected_index])) {
503 /* Reset the button state if going to prospecting or "build many industries" */
504 this->RaiseButtons();
505 ResetObjectToPlace();
508 this->SetButtons();
509 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
511 break;
514 case WID_DPI_DISPLAY_WIDGET:
515 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
516 break;
518 case WID_DPI_FUND_WIDGET: {
519 if (this->selected_type == INVALID_INDUSTRYTYPE) {
520 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
522 if (Town::GetNumItems() == 0) {
523 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
524 } else {
525 extern void GenerateIndustries();
526 _generating_world = true;
527 GenerateIndustries();
528 _generating_world = false;
530 } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
531 DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
532 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
533 } else {
534 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
536 break;
541 virtual void OnResize()
543 /* Adjust the number of items in the matrix depending of the resize */
544 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
547 virtual void OnPlaceObject(Point pt, TileIndex tile)
549 bool success = true;
550 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
551 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
552 uint32 seed = InteractiveRandom();
554 if (_game_mode == GM_EDITOR) {
555 /* Show error if no town exists at all */
556 if (Town::GetNumItems() == 0) {
557 SetDParam(0, indsp->name);
558 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
559 return;
562 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
563 _generating_world = true;
564 _ignore_restrictions = true;
566 DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
567 CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
569 cur_company.Restore();
570 _ignore_restrictions = false;
571 _generating_world = false;
572 } else {
573 success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
576 /* If an industry has been built, just reset the cursor and the system */
577 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
580 virtual void OnTick()
582 if (_pause_mode != PM_UNPAUSED) return;
583 if (!this->timer_enabled) return;
584 if (--this->callback_timer == 0) {
585 /* We have just passed another day.
586 * See if we need to update availability of currently selected industry */
587 this->callback_timer = DAY_TICKS; // restart counter
589 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
591 if (indsp->enabled) {
592 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
594 /* Only if result does match the previous state would it require a redraw. */
595 if (call_back_result != this->enabled[this->selected_index]) {
596 this->enabled[this->selected_index] = call_back_result;
597 this->SetButtons();
598 this->SetDirty();
604 virtual void OnTimeout()
606 this->RaiseButtons();
609 virtual void OnPlaceObjectAbort()
611 this->RaiseButtons();
615 * Some data on this window has become invalid.
616 * @param data Information about the changed data.
617 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
619 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
621 if (!gui_scope) return;
622 this->SetupArrays();
624 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
625 if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
626 this->SetButtons();
630 void ShowBuildIndustryWindow()
632 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
633 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
634 new BuildIndustryWindow();
637 static void UpdateIndustryProduction(Industry *i);
639 static inline bool IsProductionAlterable(const Industry *i)
641 const IndustrySpec *is = GetIndustrySpec(i->type);
642 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
643 (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()) &&
644 !_networking);
647 class IndustryViewWindow : public Window
649 /** Modes for changing production */
650 enum Editability {
651 EA_NONE, ///< Not alterable
652 EA_MULTIPLIER, ///< Allow changing the production multiplier
653 EA_RATE, ///< Allow changing the production rates
656 /** Specific lines in the info panel */
657 enum InfoLine {
658 IL_NONE, ///< No line
659 IL_MULTIPLIER, ///< Production multiplier
660 IL_RATE1, ///< Production rate of cargo 1
661 IL_RATE2, ///< Production rate of cargo 2
664 Editability editable; ///< Mode for changing production
665 InfoLine editbox_line; ///< The line clicked to open the edit box
666 InfoLine clicked_line; ///< The line of the button that has been clicked
667 byte clicked_button; ///< The button that has been clicked (to raise)
668 int production_offset_y; ///< The offset of the production texts/buttons
669 int info_height; ///< Height needed for the #WID_IV_INFO panel
671 public:
672 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
674 this->flags |= WF_DISABLE_VP_SCROLL;
675 this->editbox_line = IL_NONE;
676 this->clicked_line = IL_NONE;
677 this->clicked_button = 0;
678 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
680 this->InitNested(window_number);
681 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
682 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
684 this->InvalidateData();
687 virtual void OnPaint()
689 this->DrawWidgets();
691 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
693 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
694 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
695 if (expected > nwi->current_y - 1) {
696 this->info_height = expected + 1;
697 this->ReInit();
698 return;
703 * Draw the text in the #WID_IV_INFO panel.
704 * @param left Left edge of the panel.
705 * @param right Right edge of the panel.
706 * @param top Top edge of the panel.
707 * @return Expected position of the bottom edge of the panel.
709 int DrawInfo(uint left, uint right, uint top)
711 Industry *i = Industry::Get(this->window_number);
712 const IndustrySpec *ind = GetIndustrySpec(i->type);
713 int y = top + WD_FRAMERECT_TOP;
714 bool first = true;
715 bool has_accept = false;
716 char cargo_suffix[3][512];
718 if (i->prod_level == PRODLEVEL_CLOSURE) {
719 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
720 y += 2 * FONT_HEIGHT_NORMAL;
723 if (HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
724 GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
725 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
726 if (i->accepts_cargo[j] == CT_INVALID) continue;
727 has_accept = true;
728 if (first) {
729 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_FOR_PROCESSING);
730 y += FONT_HEIGHT_NORMAL;
731 first = false;
733 SetDParam(0, i->accepts_cargo[j]);
734 SetDParam(1, i->incoming_cargo_waiting[j]);
735 SetDParamStr(2, cargo_suffix[j]);
736 DrawString(left + WD_FRAMETEXT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_STOCKPILE_CARGO);
737 y += FONT_HEIGHT_NORMAL;
739 } else {
740 GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
741 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
742 byte p = 0;
743 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
744 if (i->accepts_cargo[j] == CT_INVALID) continue;
745 has_accept = true;
746 if (p > 0) str++;
747 SetDParam(p++, CargoSpec::Get(i->accepts_cargo[j])->name);
748 SetDParamStr(p++, cargo_suffix[j]);
750 if (has_accept) {
751 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, str);
752 y += FONT_HEIGHT_NORMAL;
756 GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
757 first = true;
758 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
759 if (i->produced_cargo[j] == CT_INVALID) continue;
760 if (first) {
761 if (has_accept) y += WD_PAR_VSEP_WIDE;
762 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
763 y += FONT_HEIGHT_NORMAL;
764 if (this->editable == EA_RATE) this->production_offset_y = y;
765 first = false;
768 SetDParam(0, i->produced_cargo[j]);
769 SetDParam(1, i->last_month_production[j]);
770 SetDParamStr(2, cargo_suffix[j]);
771 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
772 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
773 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
774 /* Let's put out those buttons.. */
775 if (this->editable == EA_RATE) {
776 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
777 i->production_rate[j] > 0, i->production_rate[j] < 255);
779 y += FONT_HEIGHT_NORMAL;
782 /* Display production multiplier if editable */
783 if (this->editable == EA_MULTIPLIER) {
784 y += WD_PAR_VSEP_WIDE;
785 this->production_offset_y = y;
786 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
787 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
788 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
789 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
790 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
791 y += FONT_HEIGHT_NORMAL;
794 /* Get the extra message for the GUI */
795 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
796 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
797 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
798 if (callback_res > 0x400) {
799 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
800 } else {
801 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
802 if (message != STR_NULL && message != STR_UNDEFINED) {
803 y += WD_PAR_VSEP_WIDE;
805 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
806 /* Use all the available space left from where we stand up to the
807 * end of the window. We ALSO enlarge the window if needed, so we
808 * can 'go' wild with the bottom of the window. */
809 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
810 StopTextRefStackUsage();
815 return y + WD_FRAMERECT_BOTTOM;
818 virtual void SetStringParameters(int widget) const
820 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
823 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
825 if (widget == WID_IV_INFO) size->height = this->info_height;
828 virtual void OnClick(Point pt, int widget, int click_count)
830 switch (widget) {
831 case WID_IV_INFO: {
832 Industry *i = Industry::Get(this->window_number);
833 InfoLine line = IL_NONE;
835 switch (this->editable) {
836 case EA_NONE: break;
838 case EA_MULTIPLIER:
839 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
840 break;
842 case EA_RATE:
843 if (pt.y >= this->production_offset_y) {
844 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
845 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
846 if (i->produced_cargo[j] == CT_INVALID) continue;
847 row--;
848 if (row < 0) {
849 line = (InfoLine)(IL_RATE1 + j);
850 break;
854 break;
856 if (line == IL_NONE) return;
858 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
859 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
860 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
861 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
862 /* Clicked buttons, decrease or increase production */
863 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
864 switch (this->editable) {
865 case EA_MULTIPLIER:
866 if (button == 1) {
867 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
868 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
869 } else {
870 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
871 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
873 break;
875 case EA_RATE:
876 if (button == 1) {
877 if (i->production_rate[line - IL_RATE1] <= 0) return;
878 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
879 } else {
880 if (i->production_rate[line - IL_RATE1] >= 255) return;
881 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
882 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
883 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
885 break;
887 default: NOT_REACHED();
890 UpdateIndustryProduction(i);
891 this->SetDirty();
892 this->SetTimeout();
893 this->clicked_line = line;
894 this->clicked_button = button;
895 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
896 /* clicked the text */
897 this->editbox_line = line;
898 switch (this->editable) {
899 case EA_MULTIPLIER:
900 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
901 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
902 break;
904 case EA_RATE:
905 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
906 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
907 break;
909 default: NOT_REACHED();
912 break;
915 case WID_IV_GOTO: {
916 Industry *i = Industry::Get(this->window_number);
917 if (_ctrl_pressed) {
918 ShowExtraViewPortWindow(i->location.GetCenterTile());
919 } else {
920 ScrollMainWindowToTile(i->location.GetCenterTile());
922 break;
925 case WID_IV_DISPLAY: {
926 Industry *i = Industry::Get(this->window_number);
927 ShowIndustryCargoesWindow(i->type);
928 break;
933 virtual void OnTimeout()
935 this->clicked_line = IL_NONE;
936 this->clicked_button = 0;
937 this->SetDirty();
940 virtual void OnResize()
942 if (this->viewport != NULL) {
943 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
944 nvp->UpdateViewportCoordinates(this);
946 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
950 virtual void OnQueryTextFinished(char *str)
952 if (StrEmpty(str)) return;
954 Industry *i = Industry::Get(this->window_number);
955 uint value = atoi(str);
956 switch (this->editbox_line) {
957 case IL_NONE: NOT_REACHED();
959 case IL_MULTIPLIER:
960 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
961 break;
963 default:
964 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
965 break;
967 UpdateIndustryProduction(i);
968 this->SetDirty();
972 * Some data on this window has become invalid.
973 * @param data Information about the changed data.
974 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
976 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
978 if (!gui_scope) return;
979 const Industry *i = Industry::Get(this->window_number);
980 if (IsProductionAlterable(i)) {
981 const IndustrySpec *ind = GetIndustrySpec(i->type);
982 this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
983 } else {
984 this->editable = EA_NONE;
988 virtual bool IsNewGRFInspectable() const
990 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
993 virtual void ShowNewGRFInspectWindow() const
995 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
999 static void UpdateIndustryProduction(Industry *i)
1001 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1002 if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
1004 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1005 if (i->produced_cargo[j] != CT_INVALID) {
1006 i->last_month_production[j] = 8 * i->production_rate[j];
1011 /** Widget definition of the view industry gui */
1012 static const NWidgetPart _nested_industry_view_widgets[] = {
1013 NWidget(NWID_HORIZONTAL),
1014 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1015 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1016 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1017 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1018 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1019 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1020 EndContainer(),
1021 NWidget(WWT_PANEL, COLOUR_CREAM),
1022 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1023 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
1024 EndContainer(),
1025 EndContainer(),
1026 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1027 EndContainer(),
1028 NWidget(NWID_HORIZONTAL),
1029 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1030 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1031 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1032 EndContainer(),
1035 /** Window definition of the view industry gui */
1036 static WindowDesc _industry_view_desc(
1037 WDP_AUTO, "view_industry", 260, 120,
1038 WC_INDUSTRY_VIEW, WC_NONE,
1040 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1043 void ShowIndustryViewWindow(int industry)
1045 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1048 /** Widget definition of the industry directory gui */
1049 static const NWidgetPart _nested_industry_directory_widgets[] = {
1050 NWidget(NWID_HORIZONTAL),
1051 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1052 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1053 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1054 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1055 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1056 EndContainer(),
1057 NWidget(NWID_HORIZONTAL),
1058 NWidget(NWID_VERTICAL),
1059 NWidget(NWID_HORIZONTAL),
1060 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1061 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1062 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1063 EndContainer(),
1064 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1065 EndContainer(),
1066 NWidget(NWID_VERTICAL),
1067 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1068 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1069 EndContainer(),
1070 EndContainer(),
1073 typedef GUIList<const Industry*> GUIIndustryList;
1077 * The list of industries.
1079 class IndustryDirectoryWindow : public Window {
1080 protected:
1081 /* Runtime saved values */
1082 static Listing last_sorting;
1083 static const Industry *last_industry;
1085 /* Constants for sorting stations */
1086 static const StringID sorter_names[];
1087 static GUIIndustryList::SortFunction * const sorter_funcs[];
1089 GUIIndustryList industries;
1090 Scrollbar *vscroll;
1092 /** (Re)Build industries list */
1093 void BuildSortIndustriesList()
1095 if (this->industries.NeedRebuild()) {
1096 this->industries.Clear();
1098 const Industry *i;
1099 FOR_ALL_INDUSTRIES(i) {
1100 *this->industries.Append() = i;
1103 this->industries.Compact();
1104 this->industries.RebuildDone();
1105 this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
1108 if (!this->industries.Sort()) return;
1109 IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
1110 this->SetWidgetDirty(WID_ID_INDUSTRY_LIST); // Set the modified widget dirty
1114 * Returns percents of cargo transported if industry produces this cargo, else -1
1116 * @param i industry to check
1117 * @param id cargo slot
1118 * @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
1120 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1122 assert(id < lengthof(i->produced_cargo));
1124 if (i->produced_cargo[id] == CT_INVALID) return 101;
1125 return ToPercent8(i->last_month_pct_transported[id]);
1129 * Returns value representing industry's transported cargo
1130 * percentage for industry sorting
1132 * @param i industry to check
1133 * @return value used for sorting
1135 static int GetCargoTransportedSortValue(const Industry *i)
1137 int p1 = GetCargoTransportedPercentsIfValid(i, 0);
1138 int p2 = GetCargoTransportedPercentsIfValid(i, 1);
1140 if (p1 > p2) Swap(p1, p2); // lower value has higher priority
1142 return (p1 << 8) + p2;
1145 /** Sort industries by name */
1146 static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
1148 static char buf_cache[96];
1149 static char buf[96];
1151 SetDParam(0, (*a)->index);
1152 GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
1154 if (*b != last_industry) {
1155 last_industry = *b;
1156 SetDParam(0, (*b)->index);
1157 GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
1160 return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
1163 /** Sort industries by type and name */
1164 static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
1166 int it_a = 0;
1167 while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
1168 int it_b = 0;
1169 while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
1170 int r = it_a - it_b;
1171 return (r == 0) ? IndustryNameSorter(a, b) : r;
1174 /** Sort industries by production and name */
1175 static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
1177 uint prod_a = 0, prod_b = 0;
1178 for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
1179 if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
1180 if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
1182 int r = prod_a - prod_b;
1184 return (r == 0) ? IndustryTypeSorter(a, b) : r;
1187 /** Sort industries by transported cargo and name */
1188 static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
1190 int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
1191 return (r == 0) ? IndustryNameSorter(a, b) : r;
1195 * Get the StringID to draw and set the appropriate DParams.
1196 * @param i the industry to get the StringID of.
1197 * @return the StringID.
1199 StringID GetIndustryString(const Industry *i) const
1201 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1202 byte p = 0;
1204 /* Industry name */
1205 SetDParam(p++, i->index);
1207 static char cargo_suffix[lengthof(i->produced_cargo)][512];
1208 GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1210 /* Industry productions */
1211 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1212 if (i->produced_cargo[j] == CT_INVALID) continue;
1213 SetDParam(p++, i->produced_cargo[j]);
1214 SetDParam(p++, i->last_month_production[j]);
1215 SetDParamStr(p++, cargo_suffix[j]);
1218 /* Transported productions */
1219 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1220 if (i->produced_cargo[j] == CT_INVALID) continue;
1221 SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
1224 /* Drawing the right string */
1225 switch (p) {
1226 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1227 case 5: return STR_INDUSTRY_DIRECTORY_ITEM;
1228 default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
1232 public:
1233 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1235 this->CreateNestedTree();
1236 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1238 this->industries.SetListing(this->last_sorting);
1239 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1240 this->industries.ForceRebuild();
1241 this->BuildSortIndustriesList();
1243 this->FinishInitNested(0);
1246 ~IndustryDirectoryWindow()
1248 this->last_sorting = this->industries.GetListing();
1251 virtual void SetStringParameters(int widget) const
1253 if (widget == WID_ID_DROPDOWN_CRITERIA) SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1256 virtual void DrawWidget(const Rect &r, int widget) const
1258 switch (widget) {
1259 case WID_ID_DROPDOWN_ORDER:
1260 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1261 break;
1263 case WID_ID_INDUSTRY_LIST: {
1264 int n = 0;
1265 int y = r.top + WD_FRAMERECT_TOP;
1266 if (this->industries.Length() == 0) {
1267 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1268 break;
1270 for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
1271 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
1273 y += this->resize.step_height;
1274 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1276 break;
1281 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1283 switch (widget) {
1284 case WID_ID_DROPDOWN_ORDER: {
1285 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1286 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1287 d.height += padding.height;
1288 *size = maxdim(*size, d);
1289 break;
1292 case WID_ID_DROPDOWN_CRITERIA: {
1293 Dimension d = {0, 0};
1294 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1295 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1297 d.width += padding.width;
1298 d.height += padding.height;
1299 *size = maxdim(*size, d);
1300 break;
1303 case WID_ID_INDUSTRY_LIST: {
1304 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1305 for (uint i = 0; i < this->industries.Length(); i++) {
1306 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1308 resize->height = d.height;
1309 d.height *= 5;
1310 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1311 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1312 *size = maxdim(*size, d);
1313 break;
1319 virtual void OnClick(Point pt, int widget, int click_count)
1321 switch (widget) {
1322 case WID_ID_DROPDOWN_ORDER:
1323 this->industries.ToggleSortOrder();
1324 this->SetDirty();
1325 break;
1327 case WID_ID_DROPDOWN_CRITERIA:
1328 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1329 break;
1331 case WID_ID_INDUSTRY_LIST: {
1332 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1333 if (p < this->industries.Length()) {
1334 if (_ctrl_pressed) {
1335 ShowExtraViewPortWindow(this->industries[p]->location.tile);
1336 } else {
1337 ScrollMainWindowToTile(this->industries[p]->location.tile);
1340 break;
1345 virtual void OnDropdownSelect(int widget, int index)
1347 if (this->industries.SortType() != index) {
1348 this->industries.SetSortType(index);
1349 this->BuildSortIndustriesList();
1353 virtual void OnResize()
1355 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1358 virtual void OnPaint()
1360 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1361 this->DrawWidgets();
1364 virtual void OnHundredthTick()
1366 this->industries.ForceResort();
1367 this->BuildSortIndustriesList();
1371 * Some data on this window has become invalid.
1372 * @param data Information about the changed data.
1373 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1375 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1377 if (data == 0) {
1378 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1379 this->industries.ForceRebuild();
1380 } else {
1381 this->industries.ForceResort();
1386 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1387 const Industry *IndustryDirectoryWindow::last_industry = NULL;
1389 /* Available station sorting functions. */
1390 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1391 &IndustryNameSorter,
1392 &IndustryTypeSorter,
1393 &IndustryProductionSorter,
1394 &IndustryTransportedCargoSorter
1397 /* Names of the sorting functions */
1398 const StringID IndustryDirectoryWindow::sorter_names[] = {
1399 STR_SORT_BY_NAME,
1400 STR_SORT_BY_TYPE,
1401 STR_SORT_BY_PRODUCTION,
1402 STR_SORT_BY_TRANSPORTED,
1403 INVALID_STRING_ID
1407 /** Window definition of the industry directory gui */
1408 static WindowDesc _industry_directory_desc(
1409 WDP_AUTO, "list_industries", 428, 190,
1410 WC_INDUSTRY_DIRECTORY, WC_NONE,
1412 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1415 void ShowIndustryDirectory()
1417 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1420 /** Widgets of the industry cargoes window. */
1421 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1422 NWidget(NWID_HORIZONTAL),
1423 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1424 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1425 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1426 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1427 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1428 EndContainer(),
1429 NWidget(NWID_HORIZONTAL),
1430 NWidget(NWID_VERTICAL),
1431 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1432 NWidget(NWID_HORIZONTAL),
1433 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1434 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1435 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1436 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1437 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1438 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1439 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1440 EndContainer(),
1441 EndContainer(),
1442 NWidget(NWID_VERTICAL),
1443 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1444 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1445 EndContainer(),
1446 EndContainer(),
1449 /** Window description for the industry cargoes window. */
1450 static WindowDesc _industry_cargoes_desc(
1451 WDP_AUTO, "industry_cargoes", 300, 210,
1452 WC_INDUSTRY_CARGOES, WC_NONE,
1454 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1457 /** Available types of field. */
1458 enum CargoesFieldType {
1459 CFT_EMPTY, ///< Empty field.
1460 CFT_SMALL_EMPTY, ///< Empty small field (for the header).
1461 CFT_INDUSTRY, ///< Display industry.
1462 CFT_CARGO, ///< Display cargo connections.
1463 CFT_CARGO_LABEL, ///< Display cargo labels.
1464 CFT_HEADER, ///< Header text.
1467 static const uint MAX_CARGOES = 3; ///< Maximum number of cargoes carried in a #CFT_CARGO field in #CargoesField.
1469 /** Data about a single field in the #IndustryCargoesWindow panel. */
1470 struct CargoesField {
1471 static const int VERT_INTER_INDUSTRY_SPACE;
1472 static const int HOR_CARGO_BORDER_SPACE;
1473 static const int CARGO_STUB_WIDTH;
1474 static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
1475 static const int CARGO_FIELD_WIDTH;
1476 static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
1477 static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
1479 static const int INDUSTRY_LINE_COLOUR;
1480 static const int CARGO_LINE_COLOUR;
1482 static int small_height, normal_height;
1483 static int industry_width;
1485 CargoesFieldType type; ///< Type of field.
1486 union {
1487 struct {
1488 IndustryType ind_type; ///< Industry type (#NUM_INDUSTRYTYPES means 'houses').
1489 CargoID other_produced[MAX_CARGOES]; ///< Cargoes produced but not used in this figure.
1490 CargoID other_accepted[MAX_CARGOES]; ///< Cargoes accepted but not used in this figure.
1491 } industry; ///< Industry data (for #CFT_INDUSTRY).
1492 struct {
1493 CargoID vertical_cargoes[MAX_CARGOES]; ///< Cargoes running from top to bottom (cargo ID or #INVALID_CARGO).
1494 byte num_cargoes; ///< Number of cargoes.
1495 CargoID supp_cargoes[MAX_CARGOES]; ///< Cargoes entering from the left (index in #vertical_cargoes, or #INVALID_CARGO).
1496 byte top_end; ///< Stop at the top of the vertical cargoes.
1497 CargoID cust_cargoes[MAX_CARGOES]; ///< Cargoes leaving to the right (index in #vertical_cargoes, or #INVALID_CARGO).
1498 byte bottom_end; ///< Stop at the bottom of the vertical cargoes.
1499 } cargo; ///< Cargo data (for #CFT_CARGO).
1500 struct {
1501 CargoID cargoes[MAX_CARGOES]; ///< Cargoes to display (or #INVALID_CARGO).
1502 bool left_align; ///< Align all cargo texts to the left (else align to the right).
1503 } cargo_label; ///< Label data (for #CFT_CARGO_LABEL).
1504 StringID header; ///< Header text (for #CFT_HEADER).
1505 } u; // Data for each type.
1508 * Make one of the empty fields (#CFT_EMPTY or #CFT_SMALL_EMPTY).
1509 * @param type Type of empty field.
1511 void MakeEmpty(CargoesFieldType type)
1513 this->type = type;
1517 * Make an industry type field.
1518 * @param ind_type Industry type (#NUM_INDUSTRYTYPES means 'houses').
1519 * @note #other_accepted and #other_produced should be filled later.
1521 void MakeIndustry(IndustryType ind_type)
1523 this->type = CFT_INDUSTRY;
1524 this->u.industry.ind_type = ind_type;
1525 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1526 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1530 * Connect a cargo from an industry to the #CFT_CARGO column.
1531 * @param cargo Cargo to connect.
1532 * @param produced Cargo is produced (if \c false, cargo is assumed to be accepted).
1533 * @return Horizontal connection index, or \c -1 if not accepted at all.
1535 int ConnectCargo(CargoID cargo, bool producer)
1537 assert(this->type == CFT_CARGO);
1538 if (cargo == INVALID_CARGO) return -1;
1540 /* Find the vertical cargo column carrying the cargo. */
1541 int column = -1;
1542 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1543 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1544 column = i;
1545 break;
1548 if (column < 0) return -1;
1550 if (producer) {
1551 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1552 this->u.cargo.supp_cargoes[column] = column;
1553 } else {
1554 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1555 this->u.cargo.cust_cargoes[column] = column;
1557 return column;
1561 * Does this #CFT_CARGO field have a horizontal connection?
1562 * @return \c true if a horizontal connection exists, \c false otherwise.
1564 bool HasConnection()
1566 assert(this->type == CFT_CARGO);
1568 for (uint i = 0; i < MAX_CARGOES; i++) {
1569 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
1570 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
1572 return false;
1576 * Make a piece of cargo column.
1577 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1578 * @param length Number of cargoes in \a cargoes.
1579 * @param count Number of cargoes to display (should be at least the number of valid cargoes, or \c -1 to let the method compute it).
1580 * @param top_end This is the first cargo field of this column.
1581 * @param bottom_end This is the last cargo field of this column.
1582 * @note #supp_cargoes and #cust_cargoes should be filled in later.
1584 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
1586 this->type = CFT_CARGO;
1587 uint i;
1588 uint num = 0;
1589 for (i = 0; i < MAX_CARGOES && i < length; i++) {
1590 if (cargoes[i] != INVALID_CARGO) {
1591 this->u.cargo.vertical_cargoes[num] = cargoes[i];
1592 num++;
1595 this->u.cargo.num_cargoes = (count < 0) ? num : count;
1596 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
1597 this->u.cargo.top_end = top_end;
1598 this->u.cargo.bottom_end = bottom_end;
1599 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
1600 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
1604 * Make a field displaying cargo type names.
1605 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1606 * @param length Number of cargoes in \a cargoes.
1607 * @param left_align ALign texts to the left (else to the right).
1609 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
1611 this->type = CFT_CARGO_LABEL;
1612 uint i;
1613 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
1614 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
1615 this->u.cargo_label.left_align = left_align;
1619 * Make a header above an industry column.
1620 * @param textid Text to display.
1622 void MakeHeader(StringID textid)
1624 this->type = CFT_HEADER;
1625 this->u.header = textid;
1629 * For a #CFT_CARGO, compute the left position of the left-most vertical cargo connection.
1630 * @param xpos Left position of the field.
1631 * @return Left position of the left-most vertical cargo column.
1633 int GetCargoBase(int xpos) const
1635 assert(this->type == CFT_CARGO);
1637 switch (this->u.cargo.num_cargoes) {
1638 case 0: return xpos + CARGO_FIELD_WIDTH / 2;
1639 case 1: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH / 2;
1640 case 2: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE / 2;
1641 case 3: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE - HOR_CARGO_WIDTH / 2;
1642 default: NOT_REACHED();
1647 * Draw the field.
1648 * @param xpos Position of the left edge.
1649 * @param vpos Position of the top edge.
1651 void Draw(int xpos, int ypos) const
1653 switch (this->type) {
1654 case CFT_EMPTY:
1655 case CFT_SMALL_EMPTY:
1656 break;
1658 case CFT_HEADER:
1659 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
1660 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
1661 break;
1663 case CFT_INDUSTRY: {
1664 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
1665 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
1666 int xpos2 = xpos + industry_width - 1;
1667 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
1668 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
1669 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1670 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1671 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
1672 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1673 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
1674 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
1676 /* Draw the industry legend. */
1677 int blob_left, blob_right;
1678 if (_current_text_dir == TD_RTL) {
1679 blob_right = xpos2 - BLOB_DISTANCE;
1680 blob_left = blob_right - BLOB_WIDTH;
1681 } else {
1682 blob_left = xpos + BLOB_DISTANCE;
1683 blob_right = blob_left + BLOB_WIDTH;
1685 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
1686 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
1687 } else {
1688 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
1691 /* Draw the other_produced/other_accepted cargoes. */
1692 const CargoID *other_right, *other_left;
1693 if (_current_text_dir == TD_RTL) {
1694 other_right = this->u.industry.other_accepted;
1695 other_left = this->u.industry.other_produced;
1696 } else {
1697 other_right = this->u.industry.other_produced;
1698 other_left = this->u.industry.other_accepted;
1700 ypos1 += VERT_CARGO_EDGE;
1701 for (uint i = 0; i < MAX_CARGOES; i++) {
1702 if (other_right[i] != INVALID_CARGO) {
1703 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
1704 int xp = xpos + industry_width + CARGO_STUB_WIDTH;
1705 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
1706 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1708 if (other_left[i] != INVALID_CARGO) {
1709 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
1710 int xp = xpos - CARGO_STUB_WIDTH;
1711 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
1712 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1714 ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1716 break;
1719 case CFT_CARGO: {
1720 int cargo_base = this->GetCargoBase(xpos);
1721 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
1722 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
1723 int colpos = cargo_base;
1724 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1725 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
1726 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
1727 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1728 colpos++;
1729 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
1730 GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
1731 colpos += HOR_CARGO_WIDTH - 2;
1732 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1733 colpos += 1 + HOR_CARGO_SPACE;
1736 const CargoID *hor_left, *hor_right;
1737 if (_current_text_dir == TD_RTL) {
1738 hor_left = this->u.cargo.cust_cargoes;
1739 hor_right = this->u.cargo.supp_cargoes;
1740 } else {
1741 hor_left = this->u.cargo.supp_cargoes;
1742 hor_right = this->u.cargo.cust_cargoes;
1744 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
1745 for (uint i = 0; i < MAX_CARGOES; i++) {
1746 if (hor_left[i] != INVALID_CARGO) {
1747 int col = hor_left[i];
1748 int dx = 0;
1749 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1750 for (; col > 0; col--) {
1751 int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
1752 DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
1753 dx = 1;
1755 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
1757 if (hor_right[i] != INVALID_CARGO) {
1758 int col = hor_right[i];
1759 int dx = 0;
1760 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1761 for (; col < this->u.cargo.num_cargoes - 1; col++) {
1762 int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
1763 DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
1764 dx = 1;
1766 DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CARGO_FIELD_WIDTH - 1, ypos, csp);
1768 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1770 break;
1773 case CFT_CARGO_LABEL:
1774 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
1775 for (uint i = 0; i < MAX_CARGOES; i++) {
1776 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
1777 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
1778 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
1779 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
1781 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1783 break;
1785 default:
1786 NOT_REACHED();
1791 * Decide which cargo was clicked at in a #CFT_CARGO field.
1792 * @param left Left industry neighbour if available (else \c NULL should be supplied).
1793 * @param right Right industry neighbour if available (else \c NULL should be supplied).
1794 * @param pt Click position in the cargo field.
1795 * @return Cargo clicked at, or #INVALID_CARGO if none.
1797 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
1799 assert(this->type == CFT_CARGO);
1801 /* Vertical matching. */
1802 int cpos = this->GetCargoBase(0);
1803 uint col;
1804 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
1805 if (pt.x < cpos) break;
1806 if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
1807 cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
1809 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
1811 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
1812 uint row;
1813 for (row = 0; row < MAX_CARGOES; row++) {
1814 if (pt.y < vpos) return INVALID_CARGO;
1815 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
1816 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1818 if (row == MAX_CARGOES) return INVALID_CARGO;
1820 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
1821 if (col == 0) {
1822 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
1823 if (left != NULL) {
1824 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
1825 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
1827 return INVALID_CARGO;
1829 if (col == this->u.cargo.num_cargoes) {
1830 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
1831 if (right != NULL) {
1832 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
1833 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
1835 return INVALID_CARGO;
1837 if (row >= col) {
1838 /* Clicked somewhere in-between vertical cargo connection.
1839 * Since the horizontal connection is made in the same order as the vertical list, the above condition
1840 * ensures we are left-below the main diagonal, thus at the supplying side.
1842 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
1843 } else {
1844 /* Clicked at a customer connection. */
1845 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
1850 * Decide what cargo the user clicked in the cargo label field.
1851 * @param pt Click position in the cargo label field.
1852 * @return Cargo clicked at, or #INVALID_CARGO if none.
1854 CargoID CargoLabelClickedAt(Point pt) const
1856 assert(this->type == CFT_CARGO_LABEL);
1858 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
1859 uint row;
1860 for (row = 0; row < MAX_CARGOES; row++) {
1861 if (pt.y < vpos) return INVALID_CARGO;
1862 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
1863 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1865 if (row == MAX_CARGOES) return INVALID_CARGO;
1866 return this->u.cargo_label.cargoes[row];
1869 private:
1871 * Draw a horizontal cargo connection.
1872 * @param left Left-most coordinate to draw.
1873 * @param right Right-most coordinate to draw.
1874 * @param top Top coordinate of the cargo connection.
1875 * @param csp Cargo to draw.
1877 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
1879 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
1880 GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
1881 GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1885 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
1886 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
1888 int CargoesField::small_height; ///< Height of the header row.
1889 int CargoesField::normal_height; ///< Height of the non-header rows.
1890 int CargoesField::industry_width; ///< Width of an industry field.
1891 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; ///< Amount of space between two industries in a column.
1893 const int CargoesField::HOR_CARGO_BORDER_SPACE = 15; ///< Amount of space between the left/right edge of a #CFT_CARGO field, and the left/right most vertical cargo.
1894 const int CargoesField::CARGO_STUB_WIDTH = 10; ///< Width of a cargo not carried in the column (should be less than #HOR_CARGO_BORDER_SPACE).
1895 const int CargoesField::HOR_CARGO_WIDTH = 15; ///< Width of a vertical cargo column (inclusive the border line).
1896 const int CargoesField::HOR_CARGO_SPACE = 5; ///< Amount of horizontal space between two vertical cargoes.
1897 const int CargoesField::VERT_CARGO_EDGE = 4; ///< Amount of vertical space between top/bottom and the top/bottom connected cargo at an industry.
1898 const int CargoesField::VERT_CARGO_SPACE = 4; ///< Amount of vertical space between two connected cargoes at an industry.
1900 const int CargoesField::BLOB_DISTANCE = 5; ///< Distance of the industry legend colour from the edge of the industry box.
1901 const int CargoesField::BLOB_WIDTH = 12; ///< Width of the industry legend colour, including border.
1902 const int CargoesField::BLOB_HEIGHT = 9; ///< Height of the industry legend colour, including border
1904 /** Width of a #CFT_CARGO field. */
1905 const int CargoesField::CARGO_FIELD_WIDTH = HOR_CARGO_BORDER_SPACE * 2 + HOR_CARGO_WIDTH * MAX_CARGOES + HOR_CARGO_SPACE * (MAX_CARGOES - 1);
1907 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; ///< Line colour of the industry type box.
1908 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW; ///< Line colour around the cargo.
1910 /** A single row of #CargoesField. */
1911 struct CargoesRow {
1912 CargoesField columns[5]; ///< One row of fields.
1915 * Connect industry production cargoes to the cargo column after it.
1916 * @param column Column of the industry.
1918 void ConnectIndustryProduced(int column)
1920 CargoesField *ind_fld = this->columns + column;
1921 CargoesField *cargo_fld = this->columns + column + 1;
1922 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
1924 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1926 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1927 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
1928 int other_count = 0;
1930 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
1931 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
1932 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
1933 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
1936 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
1937 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
1938 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
1940 } else {
1941 /* Houses only display what is demanded. */
1942 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
1943 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
1944 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
1950 * Construct a #CFT_CARGO_LABEL field.
1951 * @param column Column to create the new field.
1952 * @param accepting Display accepted cargo (if \c false, display produced cargo).
1954 void MakeCargoLabel(int column, bool accepting)
1956 CargoID cargoes[MAX_CARGOES];
1957 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
1959 CargoesField *label_fld = this->columns + column;
1960 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
1962 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
1963 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
1964 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
1965 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
1967 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
1972 * Connect industry accepted cargoes to the cargo column before it.
1973 * @param column Column of the industry.
1975 void ConnectIndustryAccepted(int column)
1977 CargoesField *ind_fld = this->columns + column;
1978 CargoesField *cargo_fld = this->columns + column - 1;
1979 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
1981 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1983 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1984 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
1985 int other_count = 0;
1987 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
1988 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
1989 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
1990 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
1993 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
1994 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
1995 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
1997 } else {
1998 /* Houses only display what is demanded. */
1999 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2000 for (uint h = 0; h < NUM_HOUSES; h++) {
2001 HouseSpec *hs = HouseSpec::Get(h);
2002 if (!hs->enabled) continue;
2004 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2005 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2006 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2007 goto next_cargo;
2011 next_cargo: ;
2019 * Window displaying the cargo connections around an industry (or cargo).
2021 * The main display is constructed from 'fields', rectangles that contain an industry, piece of the cargo connection, cargo labels, or headers.
2022 * For a nice display, the following should be kept in mind:
2023 * - A #CFT_HEADER is always at the top of an column of #CFT_INDUSTRY fields.
2024 * - A #CFT_CARGO_LABEL field is also always put in a column of #CFT_INDUSTRY fields.
2025 * - The top row contains #CFT_HEADER and #CFT_SMALL_EMPTY fields.
2026 * - Cargo connections have a column of their own (#CFT_CARGO fields).
2027 * - Cargo accepted or produced by an industry, but not carried in a cargo connection, is drawn in the space of a cargo column attached to the industry.
2028 * The information however is part of the industry.
2030 * This results in the following invariants:
2031 * - Width of a #CFT_INDUSTRY column is large enough to hold all industry type labels, all cargo labels, and all header texts.
2032 * - Height of a #CFT_INDUSTRY is large enough to hold a header line, or a industry type line, \c N cargo labels
2033 * (where \c N is the maximum number of cargoes connected between industries), \c N connections of cargo types, and space
2034 * between two industry types (1/2 above it, and 1/2 underneath it).
2035 * - Width of a cargo field (#CFT_CARGO) is large enough to hold \c N vertical columns (one for each type of cargo).
2036 * Also, space is needed between an industry and the leftmost/rightmost column to draw the non-carried cargoes.
2037 * - Height of a #CFT_CARGO field is equally high as the height of the #CFT_INDUSTRY.
2038 * - A field at the top (#CFT_HEADER or #CFT_SMALL_EMPTY) match the width of the fields below them (#CFT_INDUSTRY respectively
2039 * #CFT_CARGO), the height should be sufficient to display the header text.
2041 * When displaying the cargoes around an industry type, five columns are needed (supplying industries, accepted cargoes, the industry,
2042 * produced cargoes, customer industries). Displaying the industries around a cargo needs three columns (supplying industries, the cargo,
2043 * customer industries). The remaining two columns are set to #CFT_EMPTY with a width equal to the average of a cargo and an industry column.
2045 struct IndustryCargoesWindow : public Window {
2046 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2048 typedef SmallVector<CargoesRow, 4> Fields;
2050 Fields fields; ///< Fields to display in the #WID_IC_PANEL.
2051 uint ind_cargo; ///< If less than #NUM_INDUSTRYTYPES, an industry type, else a cargo id + NUM_INDUSTRYTYPES.
2052 Dimension cargo_textsize; ///< Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
2053 Dimension ind_textsize; ///< Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
2054 Scrollbar *vscroll;
2056 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2058 this->OnInit();
2059 this->CreateNestedTree();
2060 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2061 this->FinishInitNested(0);
2062 this->OnInvalidateData(id);
2065 virtual void OnInit()
2067 /* Initialize static CargoesField size variables. */
2068 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2069 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2070 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2071 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2072 CargoesField::small_height = d.height;
2074 /* Decide about the size of the box holding the text of an industry type. */
2075 this->ind_textsize.width = 0;
2076 this->ind_textsize.height = 0;
2077 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2078 const IndustrySpec *indsp = GetIndustrySpec(it);
2079 if (!indsp->enabled) continue;
2080 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2082 d.width = max(d.width, this->ind_textsize.width);
2083 d.height = this->ind_textsize.height;
2084 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2086 /* Compute max size of the cargo texts. */
2087 this->cargo_textsize.width = 0;
2088 this->cargo_textsize.height = 0;
2089 for (uint i = 0; i < NUM_CARGO; i++) {
2090 const CargoSpec *csp = CargoSpec::Get(i);
2091 if (!csp->IsValid()) continue;
2092 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2094 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2095 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2097 d.width += 2 * HOR_TEXT_PADDING;
2098 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2099 uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + MAX_CARGOES * FONT_HEIGHT_NORMAL + (MAX_CARGOES - 1) * CargoesField::VERT_CARGO_SPACE;
2100 d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2102 CargoesField::industry_width = d.width;
2103 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2106 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2108 switch (widget) {
2109 case WID_IC_PANEL:
2110 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::CARGO_FIELD_WIDTH * 2 + WD_FRAMETEXT_RIGHT;
2111 break;
2113 case WID_IC_IND_DROPDOWN:
2114 size->width = max(size->width, this->ind_textsize.width + padding.width);
2115 break;
2117 case WID_IC_CARGO_DROPDOWN:
2118 size->width = max(size->width, this->cargo_textsize.width + padding.width);
2119 break;
2124 CargoesFieldType type; ///< Type of field.
2125 virtual void SetStringParameters (int widget) const
2127 if (widget != WID_IC_CAPTION) return;
2129 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2130 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2131 SetDParam(0, indsp->name);
2132 } else {
2133 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2134 SetDParam(0, csp->name);
2139 * Do the two sets of cargoes have a valid cargo in common?
2140 * @param cargoes1 Base address of the first cargo array.
2141 * @param length1 Number of cargoes in the first cargo array.
2142 * @param cargoes2 Base address of the second cargo array.
2143 * @param length2 Number of cargoes in the second cargo array.
2144 * @return Arrays have at least one valid cargo in common.
2146 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2148 while (length1 > 0) {
2149 if (*cargoes1 != INVALID_CARGO) {
2150 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2152 cargoes1++;
2153 length1--;
2155 return false;
2159 * Can houses be used to supply one of the cargoes?
2160 * @param cargoes Base address of the cargo array.
2161 * @param length Number of cargoes in the array.
2162 * @return Houses can supply at least one of the cargoes.
2164 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2166 for (uint i = 0; i < length; i++) {
2167 if (cargoes[i] == INVALID_CARGO) continue;
2168 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2170 return false;
2174 * Can houses be used as customers of the produced cargoes?
2175 * @param cargoes Base address of the cargo array.
2176 * @param length Number of cargoes in the array.
2177 * @return Houses can accept at least one of the cargoes.
2179 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2181 HouseZones climate_mask;
2182 switch (_settings_game.game_creation.landscape) {
2183 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2184 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2185 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2186 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2187 default: NOT_REACHED();
2189 for (uint i = 0; i < length; i++) {
2190 if (cargoes[i] == INVALID_CARGO) continue;
2192 for (uint h = 0; h < NUM_HOUSES; h++) {
2193 HouseSpec *hs = HouseSpec::Get(h);
2194 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2196 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2197 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2201 return false;
2205 * Count how many industries have accepted cargoes in common with one of the supplied set.
2206 * @param cargoes Cargoes to search.
2207 * @param length Number of cargoes in \a cargoes.
2208 * @return Number of industries that have an accepted cargo in common with the supplied set.
2210 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2212 int count = 0;
2213 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2214 const IndustrySpec *indsp = GetIndustrySpec(it);
2215 if (!indsp->enabled) continue;
2217 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2219 return count;
2223 * Count how many industries have produced cargoes in common with one of the supplied set.
2224 * @param cargoes Cargoes to search.
2225 * @param length Number of cargoes in \a cargoes.
2226 * @return Number of industries that have a produced cargo in common with the supplied set.
2228 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2230 int count = 0;
2231 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2232 const IndustrySpec *indsp = GetIndustrySpec(it);
2233 if (!indsp->enabled) continue;
2235 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2237 return count;
2241 * Shorten the cargo column to just the part between industries.
2242 * @param column Column number of the cargo column.
2243 * @param top Current top row.
2244 * @param bottom Current bottom row.
2246 void ShortenCargoColumn(int column, int top, int bottom)
2248 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2249 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2250 top++;
2252 this->fields[top].columns[column].u.cargo.top_end = true;
2254 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2255 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2256 bottom--;
2258 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2262 * Place an industry in the fields.
2263 * @param row Row of the new industry.
2264 * @param col Column of the new industry.
2265 * @param it Industry to place.
2267 void PlaceIndustry(int row, int col, IndustryType it)
2269 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2270 this->fields[row].columns[col].MakeIndustry(it);
2271 if (col == 0) {
2272 this->fields[row].ConnectIndustryProduced(col);
2273 } else {
2274 this->fields[row].ConnectIndustryAccepted(col);
2279 * Notify smallmap that new displayed industries have been selected (in #_displayed_industries).
2281 void NotifySmallmap()
2283 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2285 /* Only notify the smallmap window if it exists. In particular, do not
2286 * bring it to the front to prevent messing up any nice layout of the user. */
2287 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2291 * Compute what and where to display for industry type \a it.
2292 * @param it Industry type to display.
2294 void ComputeIndustryDisplay(IndustryType it)
2296 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2297 this->ind_cargo = it;
2298 _displayed_industries.reset();
2299 _displayed_industries.set(it);
2301 this->fields.Clear();
2302 CargoesRow *row = this->fields.Append();
2303 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2304 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2305 row->columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2306 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2307 row->columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2309 const IndustrySpec *central_sp = GetIndustrySpec(it);
2310 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2311 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2312 /* Make a field consisting of two cargo columns. */
2313 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2314 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2315 int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
2316 for (int i = 0; i < num_indrows; i++) {
2317 CargoesRow *row = this->fields.Append();
2318 row->columns[0].MakeEmpty(CFT_EMPTY);
2319 row->columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2320 row->columns[2].MakeEmpty(CFT_EMPTY);
2321 row->columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2322 row->columns[4].MakeEmpty(CFT_EMPTY);
2324 /* Add central industry. */
2325 int central_row = 1 + num_indrows / 2;
2326 this->fields[central_row].columns[2].MakeIndustry(it);
2327 this->fields[central_row].ConnectIndustryProduced(2);
2328 this->fields[central_row].ConnectIndustryAccepted(2);
2330 /* Add cargo labels. */
2331 this->fields[central_row - 1].MakeCargoLabel(2, true);
2332 this->fields[central_row + 1].MakeCargoLabel(2, false);
2334 /* Add suppliers and customers of the 'it' industry. */
2335 int supp_count = 0;
2336 int cust_count = 0;
2337 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2338 const IndustrySpec *indsp = GetIndustrySpec(it);
2339 if (!indsp->enabled) continue;
2341 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2342 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2343 _displayed_industries.set(it);
2344 supp_count++;
2346 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2347 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2348 _displayed_industries.set(it);
2349 cust_count++;
2352 if (houses_supply) {
2353 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2354 supp_count++;
2356 if (houses_accept) {
2357 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2358 cust_count++;
2361 this->ShortenCargoColumn(1, 1, num_indrows);
2362 this->ShortenCargoColumn(3, 1, num_indrows);
2363 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2364 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2365 this->SetDirty();
2366 this->NotifySmallmap();
2370 * Compute what and where to display for cargo id \a cid.
2371 * @param cid Cargo id to display.
2373 void ComputeCargoDisplay(CargoID cid)
2375 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2376 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2377 _displayed_industries.reset();
2379 this->fields.Clear();
2380 CargoesRow *row = this->fields.Append();
2381 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2382 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2383 row->columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2384 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2385 row->columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2387 bool houses_supply = HousesCanSupply(&cid, 1);
2388 bool houses_accept = HousesCanAccept(&cid, 1);
2389 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2390 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2391 int num_indrows = max(num_supp, num_cust);
2392 for (int i = 0; i < num_indrows; i++) {
2393 CargoesRow *row = this->fields.Append();
2394 row->columns[0].MakeEmpty(CFT_EMPTY);
2395 row->columns[1].MakeCargo(&cid, 1);
2396 row->columns[2].MakeEmpty(CFT_EMPTY);
2397 row->columns[3].MakeEmpty(CFT_EMPTY);
2398 row->columns[4].MakeEmpty(CFT_EMPTY);
2401 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2403 /* Add suppliers and customers of the cargo. */
2404 int supp_count = 0;
2405 int cust_count = 0;
2406 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2407 const IndustrySpec *indsp = GetIndustrySpec(it);
2408 if (!indsp->enabled) continue;
2410 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2411 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2412 _displayed_industries.set(it);
2413 supp_count++;
2415 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2416 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2417 _displayed_industries.set(it);
2418 cust_count++;
2421 if (houses_supply) {
2422 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2423 supp_count++;
2425 if (houses_accept) {
2426 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2427 cust_count++;
2430 this->ShortenCargoColumn(1, 1, num_indrows);
2431 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2432 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2433 this->SetDirty();
2434 this->NotifySmallmap();
2438 * Some data on this window has become invalid.
2439 * @param data Information about the changed data.
2440 * - data = 0 .. NUM_INDUSTRYTYPES - 1: Display the chain around the given industry.
2441 * - data = NUM_INDUSTRYTYPES: Stop sending updates to the smallmap window.
2442 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2444 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2446 if (!gui_scope) return;
2447 if (data == NUM_INDUSTRYTYPES) {
2448 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2449 this->RaiseWidget(WID_IC_NOTIFY);
2450 this->SetWidgetDirty(WID_IC_NOTIFY);
2452 return;
2455 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2456 this->ComputeIndustryDisplay(data);
2459 virtual void DrawWidget(const Rect &r, int widget) const
2461 if (widget != WID_IC_PANEL) return;
2463 DrawPixelInfo tmp_dpi, *old_dpi;
2464 int width = r.right - r.left + 1;
2465 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2466 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2467 old_dpi = _cur_dpi;
2468 _cur_dpi = &tmp_dpi;
2470 int left_pos = WD_FRAMERECT_LEFT;
2471 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
2472 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2474 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2475 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2476 for (uint i = 0; i < this->fields.Length(); i++) {
2477 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2478 if (vpos + row_height >= 0) {
2479 int xpos = left_pos;
2480 int col, dir;
2481 if (_current_text_dir == TD_RTL) {
2482 col = last_column;
2483 dir = -1;
2484 } else {
2485 col = 0;
2486 dir = 1;
2488 while (col >= 0 && col <= last_column) {
2489 this->fields[i].columns[col].Draw(xpos, vpos);
2490 xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2491 col += dir;
2494 vpos += row_height;
2495 if (vpos >= height) break;
2498 _cur_dpi = old_dpi;
2502 * Calculate in which field was clicked, and within the field, at what position.
2503 * @param pt Clicked position in the #WID_IC_PANEL widget.
2504 * @param fieldxy If \c true is returned, field x/y coordinate of \a pt.
2505 * @param xy If \c true is returned, x/y coordinate with in the field.
2506 * @return Clicked at a valid position.
2508 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2510 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2511 pt.x -= nw->pos_x;
2512 pt.y -= nw->pos_y;
2514 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2515 if (pt.y < vpos) return false;
2517 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2518 if (row + 1 >= (int)this->fields.Length()) return false;
2519 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2520 row++; // rebase row to match index of this->fields.
2522 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
2523 if (pt.x < xpos) return false;
2524 int column;
2525 for (column = 0; column <= 5; column++) {
2526 int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2527 if (pt.x < xpos + width) break;
2528 xpos += width;
2530 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2531 if (column > num_columns) return false;
2532 xpos = pt.x - xpos;
2534 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2535 fieldxy->y = row;
2536 xy->y = vpos;
2537 if (_current_text_dir == TD_RTL) {
2538 fieldxy->x = num_columns - column;
2539 xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
2540 } else {
2541 fieldxy->x = column;
2542 xy->x = xpos;
2544 return true;
2547 virtual void OnClick(Point pt, int widget, int click_count)
2549 switch (widget) {
2550 case WID_IC_PANEL: {
2551 Point fieldxy, xy;
2552 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2554 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2555 switch (fld->type) {
2556 case CFT_INDUSTRY:
2557 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
2558 break;
2560 case CFT_CARGO: {
2561 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2562 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2563 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
2564 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2565 break;
2568 case CFT_CARGO_LABEL: {
2569 CargoID cid = fld->CargoLabelClickedAt(xy);
2570 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2571 break;
2574 default:
2575 break;
2577 break;
2580 case WID_IC_NOTIFY:
2581 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
2582 this->SetWidgetDirty(WID_IC_NOTIFY);
2583 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
2585 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2586 if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
2587 this->NotifySmallmap();
2589 break;
2591 case WID_IC_CARGO_DROPDOWN: {
2592 DropDownList *lst = new DropDownList;
2593 const CargoSpec *cs;
2594 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
2595 *lst->Append() = new DropDownListStringItem(cs->name, cs->Index(), false);
2597 if (lst->Length() == 0) {
2598 delete lst;
2599 break;
2601 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
2602 ShowDropDownList(this, lst, selected, WID_IC_CARGO_DROPDOWN, 0, true);
2603 break;
2606 case WID_IC_IND_DROPDOWN: {
2607 DropDownList *lst = new DropDownList;
2608 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
2609 IndustryType ind = _sorted_industry_types[i];
2610 const IndustrySpec *indsp = GetIndustrySpec(ind);
2611 if (!indsp->enabled) continue;
2612 *lst->Append() = new DropDownListStringItem(indsp->name, ind, false);
2614 if (lst->Length() == 0) {
2615 delete lst;
2616 break;
2618 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
2619 ShowDropDownList(this, lst, selected, WID_IC_IND_DROPDOWN, 0, true);
2620 break;
2625 virtual void OnDropdownSelect(int widget, int index)
2627 if (index < 0) return;
2629 switch (widget) {
2630 case WID_IC_CARGO_DROPDOWN:
2631 this->ComputeCargoDisplay(index);
2632 break;
2634 case WID_IC_IND_DROPDOWN:
2635 this->ComputeIndustryDisplay(index);
2636 break;
2640 virtual void OnHover(Point pt, int widget)
2642 if (widget != WID_IC_PANEL) return;
2644 Point fieldxy, xy;
2645 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2647 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2648 CargoID cid = INVALID_CARGO;
2649 switch (fld->type) {
2650 case CFT_CARGO: {
2651 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2652 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2653 cid = fld->CargoClickedAt(lft, rgt, xy);
2654 break;
2657 case CFT_CARGO_LABEL: {
2658 cid = fld->CargoLabelClickedAt(xy);
2659 break;
2662 case CFT_INDUSTRY:
2663 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
2664 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, TCC_HOVER);
2666 return;
2668 default:
2669 break;
2671 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
2672 const CargoSpec *csp = CargoSpec::Get(cid);
2673 uint64 params[5];
2674 params[0] = csp->name;
2675 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, TCC_HOVER);
2679 virtual void OnResize()
2681 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL);
2685 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5; ///< Horizontal padding around the industry type text.
2686 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; ///< Vertical padding around the industry type text.
2689 * Open the industry and cargoes window.
2690 * @param id Industry type to display, \c NUM_INDUSTRYTYPES selects a default industry type.
2692 static void ShowIndustryCargoesWindow(IndustryType id)
2694 if (id >= NUM_INDUSTRYTYPES) {
2695 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
2696 const IndustrySpec *indsp = GetIndustrySpec(_sorted_industry_types[i]);
2697 if (indsp->enabled) {
2698 id = _sorted_industry_types[i];
2699 break;
2702 if (id >= NUM_INDUSTRYTYPES) return;
2705 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
2706 if (w != NULL) {
2707 w->InvalidateData(id);
2708 return;
2710 new IndustryCargoesWindow(id);
2713 /** Open the industry and cargoes window with an industry. */
2714 void ShowIndustryCargoesWindow()
2716 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);