Add standard library header includes to precompiled header. Fix several uses of strin...
[openttd-joker.git] / src / industry_gui.cpp
blob7404fddc9b0c2f111cdbbd745f25242b75390f7d
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"
42 #include "sortlist_type.h"
44 #include "table/strings.h"
46 #include <bitset>
48 #include "safeguards.h"
50 bool _ignore_restrictions;
51 std::bitset<NUM_INDUSTRYTYPES> _displayed_industries; ///< Communication from the industry chain window to the smallmap window about what industries to display.
53 /** Cargo suffix type (for which window is it requested) */
54 enum CargoSuffixType {
55 CST_FUND, ///< Fund-industry window
56 CST_VIEW, ///< View-industry window
57 CST_DIR, ///< Industry-directory window
60 /** Ways of displaying the cargo. */
61 enum CargoSuffixDisplay {
62 CSD_CARGO, ///< Display the cargo without sub-type (cb37 result 401).
63 CSD_CARGO_AMOUNT, ///< Display the cargo and amount (if useful), but no sub-type (cb37 result 400 or fail).
64 CSD_CARGO_TEXT, ///< Display then cargo and supplied string (cb37 result 800-BFF).
65 CSD_CARGO_AMOUNT_TEXT, ///< Display then cargo, amount, and string (cb37 result 000-3FF).
68 /** Transfer storage of cargo suffix information. */
69 struct CargoSuffix {
70 CargoSuffixDisplay display; ///< How to display the cargo and text.
71 char text[512]; ///< Cargo suffix text.
74 static void ShowIndustryCargoesWindow(IndustryType id);
76 /**
77 * Gets the string to display after the cargo name (using callback 37)
78 * @param cargo the cargo for which the suffix is requested
79 * - 00 - first accepted cargo type
80 * - 01 - second accepted cargo type
81 * - 02 - third accepted cargo type
82 * - 03 - first produced cargo type
83 * - 04 - second produced cargo type
84 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
85 * @param ind the industry (NULL if in fund window)
86 * @param ind_type the industry type
87 * @param indspec the industry spec
88 * @param suffix is filled with the string to display
90 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
92 suffix.text[0] = '\0';
93 suffix.display = CSD_CARGO_AMOUNT;
95 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
96 TileIndex t = (cst != CST_FUND) ? ind->location.tile : INVALID_TILE;
97 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, t);
98 if (callback == CALLBACK_FAILED) return;
100 if (indspec->grf_prop.grffile->grf_version < 8) {
101 if (GB(callback, 0, 8) == 0xFF) return;
102 if (callback < 0x400) {
103 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
104 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
105 StopTextRefStackUsage();
106 suffix.display = CSD_CARGO_AMOUNT_TEXT;
107 return;
109 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
110 return;
112 } else { // GRF version 8 or higher.
113 if (callback == 0x400) return;
114 if (callback == 0x401) {
115 suffix.display = CSD_CARGO;
116 return;
118 if (callback < 0x400) {
119 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
120 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
121 StopTextRefStackUsage();
122 suffix.display = CSD_CARGO_AMOUNT_TEXT;
123 return;
125 if (callback >= 0x800 && callback < 0xC00) {
126 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
127 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 - 0x800 + callback), lastof(suffix.text));
128 StopTextRefStackUsage();
129 suffix.display = CSD_CARGO_TEXT;
130 return;
132 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
133 return;
139 * Gets all strings to display after the cargoes of industries (using callback 37)
140 * @param cb_offset The offset for the cargo used in cb37, 0 for accepted cargoes, 3 for produced cargoes
141 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
142 * @param ind the industry (NULL if in fund window)
143 * @param ind_type the industry type
144 * @param indspec the industry spec
145 * @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
146 * @param suffixes is filled with the suffixes
148 template <typename TC, typename TS>
149 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
151 assert_compile(lengthof(cargoes) <= lengthof(suffixes));
152 for (uint j = 0; j < lengthof(cargoes); j++) {
153 if (cargoes[j] != CT_INVALID) {
154 GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j]);
155 } else {
156 suffixes[j].text[0] = '\0';
161 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES]; ///< Industry types sorted by name.
163 /** Sort industry types by their name. */
164 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
166 static char industry_name[2][64];
168 const IndustrySpec *indsp1 = GetIndustrySpec(*a);
169 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
171 const IndustrySpec *indsp2 = GetIndustrySpec(*b);
172 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
174 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
176 /* If the names are equal, sort by industry type. */
177 return (r != 0) ? r : (*a - *b);
181 * Initialize the list of sorted industry types.
183 void SortIndustryTypes()
185 /* Add each industry type to the list. */
186 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
187 _sorted_industry_types[i] = i;
190 /* Sort industry types by name. */
191 QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
195 * Command callback. In case of failure to build an industry, show an error message.
196 * @param result Result of the command.
197 * @param tile Tile where the industry is placed.
198 * @param p1 Additional data of the #CMD_BUILD_INDUSTRY command.
199 * @param p2 Additional data of the #CMD_BUILD_INDUSTRY command.
201 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
203 if (result.Succeeded()) return;
205 uint8 indtype = GB(p1, 0, 8);
206 if (indtype < NUM_INDUSTRYTYPES) {
207 const IndustrySpec *indsp = GetIndustrySpec(indtype);
208 if (indsp->enabled) {
209 SetDParam(0, indsp->name);
210 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
215 static const NWidgetPart _nested_build_industry_widgets[] = {
216 NWidget(NWID_HORIZONTAL),
217 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
218 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
219 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
220 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
221 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
222 EndContainer(),
223 NWidget(NWID_HORIZONTAL),
224 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),
225 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
226 EndContainer(),
227 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
228 EndContainer(),
229 NWidget(NWID_HORIZONTAL),
230 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
231 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
232 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
233 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
234 EndContainer(),
237 /** Window definition of the dynamic place industries gui */
238 static WindowDesc _build_industry_desc(
239 WDP_AUTO, "build_industry", 170, 212,
240 WC_BUILD_INDUSTRY, WC_NONE,
241 WDF_CONSTRUCTION,
242 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
245 /** Build (fund or prospect) a new industry, */
246 class BuildIndustryWindow : public Window {
247 int selected_index; ///< index of the element in the matrix
248 IndustryType selected_type; ///< industry corresponding to the above index
249 uint16 callback_timer; ///< timer counter for callback eventual verification
250 bool timer_enabled; ///< timer can be used
251 uint16 count; ///< How many industries are loaded
252 IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
253 bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
254 Scrollbar *vscroll;
256 /** The offset for the text in the matrix. */
257 static const int MATRIX_TEXT_OFFSET = 17;
259 void SetupArrays()
261 this->count = 0;
263 for (uint i = 0; i < lengthof(this->index); i++) {
264 this->index[i] = INVALID_INDUSTRYTYPE;
265 this->enabled[i] = false;
268 if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
269 this->index[this->count] = INVALID_INDUSTRYTYPE;
270 this->enabled[this->count] = true;
271 this->count++;
272 this->timer_enabled = false;
274 /* Fill the arrays with industries.
275 * The tests performed after the enabled allow to load the industries
276 * In the same way they are inserted by grf (if any)
278 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
279 IndustryType ind = _sorted_industry_types[i];
280 const IndustrySpec *indsp = GetIndustrySpec(ind);
281 if (indsp->enabled) {
282 /* Rule is that editor mode loads all industries.
283 * In game mode, all non raw industries are loaded too
284 * and raw ones are loaded only when setting allows it */
285 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
286 /* Unselect if the industry is no longer in the list */
287 if (this->selected_type == ind) this->selected_index = -1;
288 continue;
290 this->index[this->count] = ind;
291 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
292 /* Keep the selection to the correct line */
293 if (this->selected_type == ind) this->selected_index = this->count;
294 this->count++;
298 /* first industry type is selected if the current selection is invalid.
299 * I'll be damned if there are none available ;) */
300 if (this->selected_index == -1) {
301 this->selected_index = 0;
302 this->selected_type = this->index[0];
305 this->vscroll->SetCount(this->count);
308 /** Update status of the fund and display-chain widgets. */
309 void SetButtons()
311 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
312 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
315 public:
316 BuildIndustryWindow() : Window(&_build_industry_desc)
318 this->timer_enabled = _loaded_newgrf_features.has_newindustries;
320 this->selected_index = -1;
321 this->selected_type = INVALID_INDUSTRYTYPE;
323 this->callback_timer = DAY_TICKS;
325 this->CreateNestedTree();
326 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
327 this->FinishInitNested(0);
329 this->SetButtons();
332 virtual void OnInit()
334 this->SetupArrays();
337 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
339 switch (widget) {
340 case WID_DPI_MATRIX_WIDGET: {
341 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
342 for (byte i = 0; i < this->count; i++) {
343 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
344 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
346 resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
347 d.width += MATRIX_TEXT_OFFSET + padding.width;
348 d.height = 5 * resize->height;
349 *size = maxdim(*size, d);
350 break;
353 case WID_DPI_INFOPANEL: {
354 /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
355 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
356 Dimension d = {0, 0};
357 for (byte i = 0; i < this->count; i++) {
358 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
360 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
362 CargoSuffix cargo_suffix[3];
363 GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
364 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
365 byte p = 0;
366 SetDParam(0, STR_JUST_NOTHING);
367 SetDParamStr(1, "");
368 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
369 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
370 if (p > 0) str++;
371 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
372 SetDParamStr(p++, cargo_suffix[j].text);
374 d = maxdim(d, GetStringBoundingBox(str));
376 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
377 GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
378 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
379 p = 0;
380 SetDParam(0, STR_JUST_NOTHING);
381 SetDParamStr(1, "");
382 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
383 if (indsp->produced_cargo[j] == CT_INVALID) continue;
384 if (p > 0) str++;
385 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
386 SetDParamStr(p++, cargo_suffix[j].text);
388 d = maxdim(d, GetStringBoundingBox(str));
391 /* Set it to something more sane :) */
392 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
393 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
394 break;
397 case WID_DPI_FUND_WIDGET: {
398 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
399 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
400 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
401 d.width += padding.width;
402 d.height += padding.height;
403 *size = maxdim(*size, d);
404 break;
409 virtual void SetStringParameters(int widget) const
411 switch (widget) {
412 case WID_DPI_FUND_WIDGET:
413 /* Raw industries might be prospected. Show this fact by changing the string
414 * In Editor, you just build, while ingame, or you fund or you prospect */
415 if (_game_mode == GM_EDITOR) {
416 /* We've chosen many random industries but no industries have been specified */
417 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
418 } else {
419 const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
420 SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
422 break;
426 virtual void DrawWidget(const Rect &r, int widget) const
428 switch (widget) {
429 case WID_DPI_MATRIX_WIDGET: {
430 uint text_left, text_right, icon_left, icon_right;
431 if (_current_text_dir == TD_RTL) {
432 icon_right = r.right - WD_MATRIX_RIGHT;
433 icon_left = icon_right - 10;
434 text_right = icon_right - BuildIndustryWindow::MATRIX_TEXT_OFFSET;
435 text_left = r.left + WD_MATRIX_LEFT;
436 } else {
437 icon_left = r.left + WD_MATRIX_LEFT;
438 icon_right = icon_left + 10;
439 text_left = icon_left + BuildIndustryWindow::MATRIX_TEXT_OFFSET;
440 text_right = r.right - WD_MATRIX_RIGHT;
443 for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
444 int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
445 bool selected = this->selected_index == i + this->vscroll->GetPosition();
447 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
448 DrawString(text_left, text_right, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
449 continue;
451 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
453 /* Draw the name of the industry in white is selected, otherwise, in orange */
454 DrawString(text_left, text_right, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
455 GfxFillRect(icon_left, y + 1, icon_right, y + 7, selected ? PC_WHITE : PC_BLACK);
456 GfxFillRect(icon_left + 1, y + 2, icon_right - 1, y + 6, indsp->map_colour);
458 break;
461 case WID_DPI_INFOPANEL: {
462 int y = r.top + WD_FRAMERECT_TOP;
463 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
464 int left = r.left + WD_FRAMERECT_LEFT;
465 int right = r.right - WD_FRAMERECT_RIGHT;
467 if (this->selected_type == INVALID_INDUSTRYTYPE) {
468 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
469 break;
472 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
474 if (_game_mode != GM_EDITOR) {
475 SetDParam(0, indsp->GetConstructionCost());
476 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
477 y += FONT_HEIGHT_NORMAL;
480 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
481 CargoSuffix cargo_suffix[3];
482 GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
483 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
484 byte p = 0;
485 SetDParam(0, STR_JUST_NOTHING);
486 SetDParamStr(1, "");
487 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
488 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
489 if (p > 0) str++;
490 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
491 SetDParamStr(p++, cargo_suffix[j].text);
493 DrawString(left, right, y, str);
494 y += FONT_HEIGHT_NORMAL;
496 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
497 GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
498 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
499 p = 0;
500 SetDParam(0, STR_JUST_NOTHING);
501 SetDParamStr(1, "");
502 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
503 if (indsp->produced_cargo[j] == CT_INVALID) continue;
504 if (p > 0) str++;
505 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
506 SetDParamStr(p++, cargo_suffix[j].text);
508 DrawString(left, right, y, str);
509 y += FONT_HEIGHT_NORMAL;
511 /* Get the additional purchase info text, if it has not already been queried. */
512 str = STR_NULL;
513 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
514 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
515 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
516 if (callback_res > 0x400) {
517 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
518 } else {
519 str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
520 if (str != STR_UNDEFINED) {
521 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
522 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
523 StopTextRefStackUsage();
528 break;
533 virtual void OnClick(Point pt, int widget, int click_count)
535 switch (widget) {
536 case WID_DPI_MATRIX_WIDGET: {
537 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
538 if (y < this->count) { // Is it within the boundaries of available data?
539 this->selected_index = y;
540 this->selected_type = this->index[y];
541 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
543 this->SetDirty();
545 if (_thd.GetCallbackWnd() == this &&
546 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
547 this->selected_type == INVALID_INDUSTRYTYPE ||
548 !this->enabled[this->selected_index])) {
549 /* Reset the button state if going to prospecting or "build many industries" */
550 this->RaiseButtons();
551 ResetObjectToPlace();
554 this->SetButtons();
555 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
557 break;
560 case WID_DPI_DISPLAY_WIDGET:
561 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
562 break;
564 case WID_DPI_FUND_WIDGET: {
565 if (this->selected_type == INVALID_INDUSTRYTYPE) {
566 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
568 if (Town::GetNumItems() == 0) {
569 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
570 } else {
571 extern void GenerateIndustries();
572 _generating_world = true;
573 GenerateIndustries();
574 _generating_world = false;
576 } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
577 DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
578 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
579 } else {
580 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
582 break;
587 virtual void OnResize()
589 /* Adjust the number of items in the matrix depending of the resize */
590 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
593 virtual void OnPlaceObject(Point pt, TileIndex tile)
595 bool success = true;
596 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
597 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
598 uint32 seed = InteractiveRandom();
600 if (_game_mode == GM_EDITOR) {
601 /* Show error if no town exists at all */
602 if (Town::GetNumItems() == 0) {
603 SetDParam(0, indsp->name);
604 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
605 return;
608 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
609 _generating_world = true;
610 _ignore_restrictions = true;
612 DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
613 CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
615 cur_company.Restore();
616 _ignore_restrictions = false;
617 _generating_world = false;
618 } else {
619 success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
622 /* If an industry has been built, just reset the cursor and the system */
623 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
626 virtual void OnTick()
628 if (_pause_mode != PM_UNPAUSED) return;
629 if (!this->timer_enabled) return;
630 if (--this->callback_timer == 0) {
631 /* We have just passed another day.
632 * See if we need to update availability of currently selected industry */
633 this->callback_timer = DAY_TICKS; // restart counter
635 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
637 if (indsp->enabled) {
638 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
640 /* Only if result does match the previous state would it require a redraw. */
641 if (call_back_result != this->enabled[this->selected_index]) {
642 this->enabled[this->selected_index] = call_back_result;
643 this->SetButtons();
644 this->SetDirty();
650 virtual void OnTimeout()
652 this->RaiseButtons();
655 virtual void OnPlaceObjectAbort()
657 this->RaiseButtons();
661 * Some data on this window has become invalid.
662 * @param data Information about the changed data.
663 * @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.
665 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
667 if (!gui_scope) return;
668 this->SetupArrays();
670 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
671 if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
672 this->SetButtons();
676 void ShowBuildIndustryWindow()
678 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
679 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
680 new BuildIndustryWindow();
683 static void UpdateIndustryProduction(Industry *i);
685 static inline bool IsProductionAlterable(const Industry *i)
687 const IndustrySpec *is = GetIndustrySpec(i->type);
688 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
689 (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()) &&
690 !_networking);
693 class IndustryViewWindow : public Window
695 /** Modes for changing production */
696 enum Editability {
697 EA_NONE, ///< Not alterable
698 EA_MULTIPLIER, ///< Allow changing the production multiplier
699 EA_RATE, ///< Allow changing the production rates
702 /** Specific lines in the info panel */
703 enum InfoLine {
704 IL_NONE, ///< No line
705 IL_MULTIPLIER, ///< Production multiplier
706 IL_RATE1, ///< Production rate of cargo 1
707 IL_RATE2, ///< Production rate of cargo 2
710 Editability editable; ///< Mode for changing production
711 InfoLine editbox_line; ///< The line clicked to open the edit box
712 InfoLine clicked_line; ///< The line of the button that has been clicked
713 byte clicked_button; ///< The button that has been clicked (to raise)
714 int production_offset_y; ///< The offset of the production texts/buttons
715 int info_height; ///< Height needed for the #WID_IV_INFO panel
717 public:
718 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
720 this->flags |= WF_DISABLE_VP_SCROLL;
721 this->editbox_line = IL_NONE;
722 this->clicked_line = IL_NONE;
723 this->clicked_button = 0;
724 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
726 this->InitNested(window_number);
727 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
728 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
730 this->InvalidateData();
733 virtual void OnPaint()
735 this->DrawWidgets();
737 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
739 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
740 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
741 if (expected > nwi->current_y - 1) {
742 this->info_height = expected + 1;
743 this->ReInit();
744 return;
749 * Draw the text in the #WID_IV_INFO panel.
750 * @param left Left edge of the panel.
751 * @param right Right edge of the panel.
752 * @param top Top edge of the panel.
753 * @return Expected position of the bottom edge of the panel.
755 int DrawInfo(uint left, uint right, uint top)
757 Industry *i = Industry::Get(this->window_number);
758 const IndustrySpec *ind = GetIndustrySpec(i->type);
759 int y = top + WD_FRAMERECT_TOP;
760 bool first = true;
761 bool has_accept = false;
763 if (i->prod_level == PRODLEVEL_CLOSURE) {
764 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
765 y += 2 * FONT_HEIGHT_NORMAL;
768 CargoSuffix cargo_suffix[3];
769 GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
770 bool stockpiling = HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS);
772 uint left_side = left + WD_FRAMERECT_LEFT * 4; // Indent accepted cargoes.
773 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
774 if (i->accepts_cargo[j] == CT_INVALID) continue;
775 has_accept = true;
776 if (first) {
777 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_REQUIRES);
778 y += FONT_HEIGHT_NORMAL;
779 first = false;
781 SetDParam(0, CargoSpec::Get(i->accepts_cargo[j])->name);
782 SetDParam(1, i->accepts_cargo[j]);
783 SetDParam(2, i->incoming_cargo_waiting[j]);
784 SetDParamStr(3, "");
785 StringID str = STR_NULL;
786 switch (cargo_suffix[j].display) {
787 case CSD_CARGO_AMOUNT_TEXT:
788 SetDParamStr(3, cargo_suffix[j].text);
789 FALLTHROUGH;
790 case CSD_CARGO_AMOUNT:
791 str = stockpiling ? STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT : STR_INDUSTRY_VIEW_ACCEPT_CARGO;
792 break;
794 case CSD_CARGO_TEXT:
795 SetDParamStr(3, cargo_suffix[j].text);
796 FALLTHROUGH;
797 case CSD_CARGO:
798 str = STR_INDUSTRY_VIEW_ACCEPT_CARGO;
799 break;
801 default:
802 NOT_REACHED();
804 DrawString(left_side, right - WD_FRAMERECT_RIGHT, y, str);
805 y += FONT_HEIGHT_NORMAL;
808 GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
809 first = true;
810 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
811 if (i->produced_cargo[j] == CT_INVALID) continue;
812 if (first) {
813 if (has_accept) y += WD_PAR_VSEP_WIDE;
814 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
815 y += FONT_HEIGHT_NORMAL;
816 if (this->editable == EA_RATE) this->production_offset_y = y;
817 first = false;
820 SetDParam(0, i->produced_cargo[j]);
821 SetDParam(1, i->last_month_production[j]);
822 SetDParamStr(2, cargo_suffix[j].text);
823 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
824 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
825 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
826 /* Let's put out those buttons.. */
827 if (this->editable == EA_RATE) {
828 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
829 i->production_rate[j] > 0, i->production_rate[j] < 255);
831 y += FONT_HEIGHT_NORMAL;
834 /* Display production multiplier if editable */
835 if (this->editable == EA_MULTIPLIER) {
836 y += WD_PAR_VSEP_WIDE;
837 this->production_offset_y = y;
838 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
839 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
840 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
841 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
842 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
843 y += FONT_HEIGHT_NORMAL;
846 /* Get the extra message for the GUI */
847 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
848 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
849 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
850 if (callback_res > 0x400) {
851 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
852 } else {
853 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
854 if (message != STR_NULL && message != STR_UNDEFINED) {
855 y += WD_PAR_VSEP_WIDE;
857 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
858 /* Use all the available space left from where we stand up to the
859 * end of the window. We ALSO enlarge the window if needed, so we
860 * can 'go' wild with the bottom of the window. */
861 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
862 StopTextRefStackUsage();
867 return y + WD_FRAMERECT_BOTTOM;
870 virtual void SetStringParameters(int widget) const
872 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
875 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
877 if (widget == WID_IV_INFO) size->height = this->info_height;
880 virtual void OnClick(Point pt, int widget, int click_count)
882 switch (widget) {
883 case WID_IV_INFO: {
884 Industry *i = Industry::Get(this->window_number);
885 InfoLine line = IL_NONE;
887 switch (this->editable) {
888 case EA_NONE: break;
890 case EA_MULTIPLIER:
891 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
892 break;
894 case EA_RATE:
895 if (pt.y >= this->production_offset_y) {
896 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
897 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
898 if (i->produced_cargo[j] == CT_INVALID) continue;
899 row--;
900 if (row < 0) {
901 line = (InfoLine)(IL_RATE1 + j);
902 break;
906 break;
908 if (line == IL_NONE) return;
910 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
911 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
912 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
913 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
914 /* Clicked buttons, decrease or increase production */
915 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
916 switch (this->editable) {
917 case EA_MULTIPLIER:
918 if (button == 1) {
919 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
920 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
921 } else {
922 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
923 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
925 break;
927 case EA_RATE:
928 if (button == 1) {
929 if (i->production_rate[line - IL_RATE1] <= 0) return;
930 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
931 } else {
932 if (i->production_rate[line - IL_RATE1] >= 255) return;
933 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
934 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
935 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
937 break;
939 default: NOT_REACHED();
942 UpdateIndustryProduction(i);
943 this->SetDirty();
944 this->SetTimeout();
945 this->clicked_line = line;
946 this->clicked_button = button;
947 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
948 /* clicked the text */
949 this->editbox_line = line;
950 switch (this->editable) {
951 case EA_MULTIPLIER:
952 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
953 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
954 break;
956 case EA_RATE:
957 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
958 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
959 break;
961 default: NOT_REACHED();
964 break;
967 case WID_IV_GOTO: {
968 Industry *i = Industry::Get(this->window_number);
969 if (_ctrl_pressed) {
970 ShowExtraViewPortWindow(i->location.GetCenterTile());
971 } else {
972 ScrollMainWindowToTile(i->location.GetCenterTile());
974 break;
977 case WID_IV_DISPLAY: {
978 Industry *i = Industry::Get(this->window_number);
979 ShowIndustryCargoesWindow(i->type);
980 break;
985 virtual void OnTimeout()
987 this->clicked_line = IL_NONE;
988 this->clicked_button = 0;
989 this->SetDirty();
992 virtual void OnResize()
994 if (this->viewport != NULL) {
995 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
996 nvp->UpdateViewportCoordinates(this);
998 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
1002 virtual void OnQueryTextFinished(char *str)
1004 if (StrEmpty(str)) return;
1006 Industry *i = Industry::Get(this->window_number);
1007 uint value = atoi(str);
1008 switch (this->editbox_line) {
1009 case IL_NONE: NOT_REACHED();
1011 case IL_MULTIPLIER:
1012 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
1013 break;
1015 default:
1016 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
1017 break;
1019 UpdateIndustryProduction(i);
1020 this->SetDirty();
1024 * Some data on this window has become invalid.
1025 * @param data Information about the changed data.
1026 * @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.
1028 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1030 if (!gui_scope) return;
1031 const Industry *i = Industry::Get(this->window_number);
1032 if (IsProductionAlterable(i)) {
1033 const IndustrySpec *ind = GetIndustrySpec(i->type);
1034 this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
1035 } else {
1036 this->editable = EA_NONE;
1040 virtual bool IsNewGRFInspectable() const
1042 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
1045 virtual void ShowNewGRFInspectWindow() const
1047 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
1051 static void UpdateIndustryProduction(Industry *i)
1053 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1054 if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
1056 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1057 if (i->produced_cargo[j] != CT_INVALID) {
1058 i->last_month_production[j] = 8 * i->production_rate[j];
1063 /** Widget definition of the view industry gui */
1064 static const NWidgetPart _nested_industry_view_widgets[] = {
1065 NWidget(NWID_HORIZONTAL),
1066 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1067 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1068 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1069 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1070 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1071 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1072 EndContainer(),
1073 NWidget(WWT_PANEL, COLOUR_CREAM),
1074 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1075 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
1076 EndContainer(),
1077 EndContainer(),
1078 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1079 EndContainer(),
1080 NWidget(NWID_HORIZONTAL),
1081 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1082 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1083 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1084 EndContainer(),
1087 /** Window definition of the view industry gui */
1088 static WindowDesc _industry_view_desc(
1089 WDP_AUTO, "view_industry", 260, 120,
1090 WC_INDUSTRY_VIEW, WC_NONE,
1092 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1095 void ShowIndustryViewWindow(int industry)
1097 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1100 /** Widget definition of the industry directory gui */
1101 static const NWidgetPart _nested_industry_directory_widgets[] = {
1102 NWidget(NWID_HORIZONTAL),
1103 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1104 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1105 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1106 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1107 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1108 EndContainer(),
1109 NWidget(NWID_HORIZONTAL),
1110 NWidget(NWID_VERTICAL),
1111 NWidget(NWID_HORIZONTAL),
1112 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1113 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1114 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_ACC_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_ACCEPTED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1115 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_PROD_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_PRODUCED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1116 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1117 EndContainer(),
1118 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1119 EndContainer(),
1120 NWidget(NWID_VERTICAL),
1121 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1122 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1123 EndContainer(),
1124 EndContainer(),
1127 typedef GUIList<const Industry*, std::pair<CargoID, CargoID>> GUIIndustryList;
1129 /** Special cargo filter criteria */
1130 enum CargoFilterSpecialType {
1131 CF_ANY = CT_NO_REFIT, ///< Show all vehicles independent of carried cargo (i.e. no filtering)
1132 CF_NONE = CT_INVALID, ///< Show only vehicles which do not carry cargo (e.g. train engines)
1135 /** Cargo filter functions */
1136 static bool CDECL CargoFilter(const Industry* const* industry, const std::pair<CargoID, CargoID> cargoes)
1138 auto accepted_cargo = cargoes.first;
1139 auto produced_cargo = cargoes.second;
1141 bool accepted_cargo_matches;
1143 switch (accepted_cargo)
1145 case CF_ANY:
1146 accepted_cargo_matches = true;
1147 break;
1149 case CF_NONE:
1150 accepted_cargo_matches = std::all_of(std::begin((*industry)->accepts_cargo), std::end((*industry)->accepts_cargo), [](CargoID cargo) {
1151 return cargo == CT_INVALID;
1153 break;
1155 default:
1156 accepted_cargo_matches = std::any_of(std::begin((*industry)->accepts_cargo), std::end((*industry)->accepts_cargo), [&](CargoID cargo) {
1157 return cargo == accepted_cargo;
1159 break;
1162 bool produced_cargo_matches;
1164 switch (produced_cargo)
1166 case CF_ANY:
1167 produced_cargo_matches = true;
1168 break;
1170 case CF_NONE:
1171 produced_cargo_matches = std::all_of(std::begin((*industry)->produced_cargo), std::end((*industry)->produced_cargo), [](CargoID cargo) {
1172 return cargo == CT_INVALID;
1174 break;
1176 default:
1177 produced_cargo_matches = std::any_of(std::begin((*industry)->produced_cargo), std::end((*industry)->produced_cargo), [&](CargoID cargo) {
1178 return cargo == produced_cargo;
1180 break;
1183 return accepted_cargo_matches && produced_cargo_matches;
1186 static GUIIndustryList::FilterFunction * const _filter_funcs[] = { &CargoFilter };
1190 * The list of industries.
1192 class IndustryDirectoryWindow : public Window {
1193 protected:
1194 /* Runtime saved values */
1195 static Listing last_sorting;
1196 static const Industry *last_industry;
1198 /* Constants for sorting stations */
1199 static const StringID sorter_names[];
1200 static GUIIndustryList::SortFunction * const sorter_funcs[];
1202 GUIIndustryList industries;
1203 Scrollbar *vscroll;
1205 CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
1206 StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
1207 CargoID produced_cargo_filter_criteria; ///< Selected produced cargo filter
1208 CargoID accepted_cargo_filter_criteria; ///< Selected accepted cargo filter
1210 /** Set cargo filter list item index. */
1211 void SetProducedCargoFilterIndex(int index)
1213 if (this->produced_cargo_filter_criteria != index) {
1214 this->produced_cargo_filter_criteria = index;
1215 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1216 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY ||
1217 this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1219 this->industries.SetFilterState(is_filtering_necessary);
1220 this->industries.SetFilterType(0);
1221 this->industries.ForceRebuild();
1225 /** Set cargo filter list item index. */
1226 void SetAcceptedCargoFilterIndex(int index)
1228 if (this->accepted_cargo_filter_criteria != index) {
1229 this->accepted_cargo_filter_criteria = index;
1230 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1231 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY ||
1232 this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1234 this->industries.SetFilterState(is_filtering_necessary);
1235 this->industries.SetFilterType(0);
1236 this->industries.ForceRebuild();
1240 /** Populate the filter list and set the cargo filter criteria. */
1241 void SetCargoFilterArray()
1243 uint filter_items = 0;
1245 /* Add item for disabling filtering. */
1246 this->cargo_filter[filter_items] = CF_ANY;
1247 this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
1248 this->produced_cargo_filter_criteria = filter_items;
1249 this->accepted_cargo_filter_criteria = filter_items;
1250 filter_items++;
1252 /* Add item for industries not producing anything, e.g. power plants */
1253 this->cargo_filter[filter_items] = CF_NONE;
1254 this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE;
1255 filter_items++;
1257 /* Collect available cargo types for filtering. */
1258 const CargoSpec *cs;
1259 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1260 this->cargo_filter[filter_items] = cs->Index();
1261 this->cargo_filter_texts[filter_items] = cs->name;
1262 filter_items++;
1265 /* Terminate the filter list. */
1266 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
1268 this->industries.SetFilterFuncs(_filter_funcs);
1270 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY ||
1271 this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1273 this->industries.SetFilterState(is_filtering_necessary);
1276 /** (Re)Build industries list */
1277 void BuildSortIndustriesList()
1279 if (this->industries.NeedRebuild()) {
1280 this->industries.Clear();
1282 const Industry *i;
1283 FOR_ALL_INDUSTRIES(i) {
1284 *this->industries.Append() = i;
1287 this->industries.Compact();
1288 this->industries.RebuildDone();
1291 IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
1293 auto filter = std::make_pair(this->cargo_filter[this->accepted_cargo_filter_criteria],
1294 this->cargo_filter[this->produced_cargo_filter_criteria]);
1296 this->industries.Filter(filter);
1297 this->industries.Sort();
1299 this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
1301 this->SetDirty();
1305 * Returns percents of cargo transported if industry produces this cargo, else -1
1307 * @param i industry to check
1308 * @param id cargo slot
1309 * @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
1311 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1313 assert(id < lengthof(i->produced_cargo));
1315 if (i->produced_cargo[id] == CT_INVALID) return 101;
1316 return ToPercent8(i->last_month_pct_transported[id]);
1320 * Returns value representing industry's transported cargo
1321 * percentage for industry sorting
1323 * @param i industry to check
1324 * @return value used for sorting
1326 static int GetCargoTransportedSortValue(const Industry *i)
1328 int p1 = GetCargoTransportedPercentsIfValid(i, 0);
1329 int p2 = GetCargoTransportedPercentsIfValid(i, 1);
1331 if (p1 > p2) Swap(p1, p2); // lower value has higher priority
1333 return (p1 << 8) + p2;
1336 /** Sort industries by name */
1337 static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
1339 static char buf_cache[96];
1340 static char buf[96];
1342 SetDParam(0, (*a)->index);
1343 GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
1345 if (*b != last_industry) {
1346 last_industry = *b;
1347 SetDParam(0, (*b)->index);
1348 GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
1351 return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
1354 /** Sort industries by type and name */
1355 static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
1357 int it_a = 0;
1358 while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
1359 int it_b = 0;
1360 while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
1361 int r = it_a - it_b;
1362 return (r == 0) ? IndustryNameSorter(a, b) : r;
1365 /** Sort industries by production and name */
1366 static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
1368 uint prod_a = 0, prod_b = 0;
1369 for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
1370 if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
1371 if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
1373 int r = prod_a - prod_b;
1375 return (r == 0) ? IndustryTypeSorter(a, b) : r;
1378 /** Sort industries by transported cargo and name */
1379 static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
1381 int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
1382 return (r == 0) ? IndustryNameSorter(a, b) : r;
1386 * Get the StringID to draw and set the appropriate DParams.
1387 * @param i the industry to get the StringID of.
1388 * @return the StringID.
1390 StringID GetIndustryString(const Industry *i) const
1392 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1393 byte p = 0;
1395 /* Industry name */
1396 SetDParam(p++, i->index);
1398 static CargoSuffix cargo_suffix[lengthof(i->produced_cargo)];
1399 GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1401 /* Industry productions */
1402 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1403 if (i->produced_cargo[j] == CT_INVALID) continue;
1404 SetDParam(p++, i->produced_cargo[j]);
1405 SetDParam(p++, i->last_month_production[j]);
1406 SetDParamStr(p++, cargo_suffix[j].text);
1409 /* Transported productions */
1410 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1411 if (i->produced_cargo[j] == CT_INVALID) continue;
1412 SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
1415 /* Drawing the right string */
1416 switch (p) {
1417 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1418 case 5: return STR_INDUSTRY_DIRECTORY_ITEM;
1419 default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
1423 public:
1424 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1426 this->CreateNestedTree();
1427 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1429 this->industries.SetListing(this->last_sorting);
1430 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1431 this->industries.ForceRebuild();
1432 this->BuildSortIndustriesList();
1434 this->FinishInitNested(0);
1437 ~IndustryDirectoryWindow()
1439 this->last_sorting = this->industries.GetListing();
1442 virtual void OnInit() override
1444 this->SetCargoFilterArray();
1447 virtual void SetStringParameters(int widget) const
1449 switch (widget) {
1450 case WID_ID_DROPDOWN_CRITERIA:
1451 SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1452 break;
1454 case WID_ID_FILTER_BY_ACC_CARGO:
1455 SetDParam(0, this->cargo_filter_texts[this->accepted_cargo_filter_criteria]);
1456 break;
1458 case WID_ID_FILTER_BY_PROD_CARGO:
1459 SetDParam(0, this->cargo_filter_texts[this->produced_cargo_filter_criteria]);
1460 break;
1464 virtual void DrawWidget(const Rect &r, int widget) const
1466 switch (widget) {
1467 case WID_ID_DROPDOWN_ORDER:
1468 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1469 break;
1471 case WID_ID_INDUSTRY_LIST: {
1472 int n = 0;
1473 int y = r.top + WD_FRAMERECT_TOP;
1474 if (this->industries.Length() == 0) {
1475 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1476 break;
1478 for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
1479 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
1481 y += this->resize.step_height;
1482 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1484 break;
1489 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1491 switch (widget) {
1492 case WID_ID_DROPDOWN_ORDER: {
1493 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1494 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1495 d.height += padding.height;
1496 *size = maxdim(*size, d);
1497 break;
1500 case WID_ID_DROPDOWN_CRITERIA: {
1501 Dimension d = {0, 0};
1502 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1503 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1505 d.width += padding.width;
1506 d.height += padding.height;
1507 *size = maxdim(*size, d);
1508 break;
1511 case WID_ID_INDUSTRY_LIST: {
1512 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1513 for (uint i = 0; i < this->industries.Length(); i++) {
1514 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1516 resize->height = d.height;
1517 d.height *= 5;
1518 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1519 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1520 *size = maxdim(*size, d);
1521 break;
1527 virtual void OnClick(Point pt, int widget, int click_count)
1529 switch (widget) {
1530 case WID_ID_DROPDOWN_ORDER:
1531 this->industries.ToggleSortOrder();
1532 this->SetDirty();
1533 break;
1535 case WID_ID_DROPDOWN_CRITERIA:
1536 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1537 break;
1539 case WID_ID_FILTER_BY_ACC_CARGO: // Cargo filter dropdown
1540 ShowDropDownMenu(this, this->cargo_filter_texts, this->accepted_cargo_filter_criteria, WID_ID_FILTER_BY_ACC_CARGO, 0, 0);
1541 break;
1543 case WID_ID_FILTER_BY_PROD_CARGO: // Cargo filter dropdown
1544 ShowDropDownMenu(this, this->cargo_filter_texts, this->produced_cargo_filter_criteria, WID_ID_FILTER_BY_PROD_CARGO, 0, 0);
1545 break;
1547 case WID_ID_INDUSTRY_LIST: {
1548 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1549 if (p < this->industries.Length()) {
1550 if (_ctrl_pressed) {
1551 ShowExtraViewPortWindow(this->industries[p]->location.tile);
1552 } else {
1553 ScrollMainWindowToTile(this->industries[p]->location.tile);
1556 break;
1561 virtual void OnDropdownSelect(int widget, int index)
1563 switch (widget) {
1564 case WID_ID_DROPDOWN_CRITERIA: {
1565 if (this->industries.SortType() != index) {
1566 this->industries.SetSortType(index);
1567 this->BuildSortIndustriesList();
1569 break;
1572 case WID_ID_FILTER_BY_ACC_CARGO: {
1573 this->SetAcceptedCargoFilterIndex(index);
1574 this->BuildSortIndustriesList();
1575 break;
1578 case WID_ID_FILTER_BY_PROD_CARGO: {
1579 this->SetProducedCargoFilterIndex(index);
1580 this->BuildSortIndustriesList();
1581 break;
1586 virtual void OnResize()
1588 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1591 virtual void OnPaint()
1593 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1595 this->DrawWidgets();
1598 virtual void OnHundredthTick()
1600 if (_pause_mode == PM_UNPAUSED) {
1601 this->industries.ForceResort();
1602 this->BuildSortIndustriesList();
1607 * Some data on this window has become invalid.
1608 * @param data Information about the changed data.
1609 * @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.
1611 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1613 if (data == 0) {
1614 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1615 this->industries.ForceRebuild();
1616 } else {
1617 this->industries.ForceResort();
1622 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1623 const Industry *IndustryDirectoryWindow::last_industry = NULL;
1625 /* Available station sorting functions. */
1626 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1627 &IndustryNameSorter,
1628 &IndustryTypeSorter,
1629 &IndustryProductionSorter,
1630 &IndustryTransportedCargoSorter
1633 /* Names of the sorting functions */
1634 const StringID IndustryDirectoryWindow::sorter_names[] = {
1635 STR_SORT_BY_NAME,
1636 STR_SORT_BY_TYPE,
1637 STR_SORT_BY_PRODUCTION,
1638 STR_SORT_BY_TRANSPORTED,
1639 INVALID_STRING_ID
1643 /** Window definition of the industry directory gui */
1644 static WindowDesc _industry_directory_desc(
1645 WDP_AUTO, "list_industries", 428, 190,
1646 WC_INDUSTRY_DIRECTORY, WC_NONE,
1648 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1651 void ShowIndustryDirectory()
1653 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1656 /** Widgets of the industry cargoes window. */
1657 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1658 NWidget(NWID_HORIZONTAL),
1659 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1660 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1661 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1662 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1663 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1664 EndContainer(),
1665 NWidget(NWID_HORIZONTAL),
1666 NWidget(NWID_VERTICAL),
1667 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1668 NWidget(NWID_HORIZONTAL),
1669 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1670 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1671 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1672 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1673 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1674 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1675 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1676 EndContainer(),
1677 EndContainer(),
1678 NWidget(NWID_VERTICAL),
1679 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1680 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1681 EndContainer(),
1682 EndContainer(),
1685 /** Window description for the industry cargoes window. */
1686 static WindowDesc _industry_cargoes_desc(
1687 WDP_AUTO, "industry_cargoes", 300, 210,
1688 WC_INDUSTRY_CARGOES, WC_NONE,
1690 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1693 /** Available types of field. */
1694 enum CargoesFieldType {
1695 CFT_EMPTY, ///< Empty field.
1696 CFT_SMALL_EMPTY, ///< Empty small field (for the header).
1697 CFT_INDUSTRY, ///< Display industry.
1698 CFT_CARGO, ///< Display cargo connections.
1699 CFT_CARGO_LABEL, ///< Display cargo labels.
1700 CFT_HEADER, ///< Header text.
1703 static const uint MAX_CARGOES = 3; ///< Maximum number of cargoes carried in a #CFT_CARGO field in #CargoesField.
1705 /** Data about a single field in the #IndustryCargoesWindow panel. */
1706 struct CargoesField {
1707 static const int VERT_INTER_INDUSTRY_SPACE;
1708 static const int HOR_CARGO_BORDER_SPACE;
1709 static const int CARGO_STUB_WIDTH;
1710 static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
1711 static const int CARGO_FIELD_WIDTH;
1712 static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
1713 static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
1715 static const int INDUSTRY_LINE_COLOUR;
1716 static const int CARGO_LINE_COLOUR;
1718 static int small_height, normal_height;
1719 static int industry_width;
1721 CargoesFieldType type; ///< Type of field.
1722 union {
1723 struct {
1724 IndustryType ind_type; ///< Industry type (#NUM_INDUSTRYTYPES means 'houses').
1725 CargoID other_produced[MAX_CARGOES]; ///< Cargoes produced but not used in this figure.
1726 CargoID other_accepted[MAX_CARGOES]; ///< Cargoes accepted but not used in this figure.
1727 } industry; ///< Industry data (for #CFT_INDUSTRY).
1728 struct {
1729 CargoID vertical_cargoes[MAX_CARGOES]; ///< Cargoes running from top to bottom (cargo ID or #INVALID_CARGO).
1730 byte num_cargoes; ///< Number of cargoes.
1731 CargoID supp_cargoes[MAX_CARGOES]; ///< Cargoes entering from the left (index in #vertical_cargoes, or #INVALID_CARGO).
1732 byte top_end; ///< Stop at the top of the vertical cargoes.
1733 CargoID cust_cargoes[MAX_CARGOES]; ///< Cargoes leaving to the right (index in #vertical_cargoes, or #INVALID_CARGO).
1734 byte bottom_end; ///< Stop at the bottom of the vertical cargoes.
1735 } cargo; ///< Cargo data (for #CFT_CARGO).
1736 struct {
1737 CargoID cargoes[MAX_CARGOES]; ///< Cargoes to display (or #INVALID_CARGO).
1738 bool left_align; ///< Align all cargo texts to the left (else align to the right).
1739 } cargo_label; ///< Label data (for #CFT_CARGO_LABEL).
1740 StringID header; ///< Header text (for #CFT_HEADER).
1741 } u; // Data for each type.
1744 * Make one of the empty fields (#CFT_EMPTY or #CFT_SMALL_EMPTY).
1745 * @param type Type of empty field.
1747 void MakeEmpty(CargoesFieldType type)
1749 this->type = type;
1753 * Make an industry type field.
1754 * @param ind_type Industry type (#NUM_INDUSTRYTYPES means 'houses').
1755 * @note #other_accepted and #other_produced should be filled later.
1757 void MakeIndustry(IndustryType ind_type)
1759 this->type = CFT_INDUSTRY;
1760 this->u.industry.ind_type = ind_type;
1761 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1762 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1766 * Connect a cargo from an industry to the #CFT_CARGO column.
1767 * @param cargo Cargo to connect.
1768 * @param produced Cargo is produced (if \c false, cargo is assumed to be accepted).
1769 * @return Horizontal connection index, or \c -1 if not accepted at all.
1771 int ConnectCargo(CargoID cargo, bool producer)
1773 assert(this->type == CFT_CARGO);
1774 if (cargo == INVALID_CARGO) return -1;
1776 /* Find the vertical cargo column carrying the cargo. */
1777 int column = -1;
1778 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1779 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1780 column = i;
1781 break;
1784 if (column < 0) return -1;
1786 if (producer) {
1787 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1788 this->u.cargo.supp_cargoes[column] = column;
1789 } else {
1790 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1791 this->u.cargo.cust_cargoes[column] = column;
1793 return column;
1797 * Does this #CFT_CARGO field have a horizontal connection?
1798 * @return \c true if a horizontal connection exists, \c false otherwise.
1800 bool HasConnection()
1802 assert(this->type == CFT_CARGO);
1804 for (uint i = 0; i < MAX_CARGOES; i++) {
1805 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
1806 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
1808 return false;
1812 * Make a piece of cargo column.
1813 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1814 * @param length Number of cargoes in \a cargoes.
1815 * @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).
1816 * @param top_end This is the first cargo field of this column.
1817 * @param bottom_end This is the last cargo field of this column.
1818 * @note #supp_cargoes and #cust_cargoes should be filled in later.
1820 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
1822 this->type = CFT_CARGO;
1823 uint i;
1824 uint num = 0;
1825 for (i = 0; i < MAX_CARGOES && i < length; i++) {
1826 if (cargoes[i] != INVALID_CARGO) {
1827 this->u.cargo.vertical_cargoes[num] = cargoes[i];
1828 num++;
1831 this->u.cargo.num_cargoes = (count < 0) ? num : count;
1832 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
1833 this->u.cargo.top_end = top_end;
1834 this->u.cargo.bottom_end = bottom_end;
1835 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
1836 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
1840 * Make a field displaying cargo type names.
1841 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1842 * @param length Number of cargoes in \a cargoes.
1843 * @param left_align ALign texts to the left (else to the right).
1845 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
1847 this->type = CFT_CARGO_LABEL;
1848 uint i;
1849 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
1850 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
1851 this->u.cargo_label.left_align = left_align;
1855 * Make a header above an industry column.
1856 * @param textid Text to display.
1858 void MakeHeader(StringID textid)
1860 this->type = CFT_HEADER;
1861 this->u.header = textid;
1865 * For a #CFT_CARGO, compute the left position of the left-most vertical cargo connection.
1866 * @param xpos Left position of the field.
1867 * @return Left position of the left-most vertical cargo column.
1869 int GetCargoBase(int xpos) const
1871 assert(this->type == CFT_CARGO);
1873 switch (this->u.cargo.num_cargoes) {
1874 case 0: return xpos + CARGO_FIELD_WIDTH / 2;
1875 case 1: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH / 2;
1876 case 2: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE / 2;
1877 case 3: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE - HOR_CARGO_WIDTH / 2;
1878 default: NOT_REACHED();
1883 * Draw the field.
1884 * @param xpos Position of the left edge.
1885 * @param vpos Position of the top edge.
1887 void Draw(int xpos, int ypos) const
1889 switch (this->type) {
1890 case CFT_EMPTY:
1891 case CFT_SMALL_EMPTY:
1892 break;
1894 case CFT_HEADER:
1895 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
1896 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
1897 break;
1899 case CFT_INDUSTRY: {
1900 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
1901 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
1902 int xpos2 = xpos + industry_width - 1;
1903 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
1904 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
1905 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1906 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1907 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
1908 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1909 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
1910 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
1912 /* Draw the industry legend. */
1913 int blob_left, blob_right;
1914 if (_current_text_dir == TD_RTL) {
1915 blob_right = xpos2 - BLOB_DISTANCE;
1916 blob_left = blob_right - BLOB_WIDTH;
1917 } else {
1918 blob_left = xpos + BLOB_DISTANCE;
1919 blob_right = blob_left + BLOB_WIDTH;
1921 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
1922 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
1923 } else {
1924 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
1927 /* Draw the other_produced/other_accepted cargoes. */
1928 const CargoID *other_right, *other_left;
1929 if (_current_text_dir == TD_RTL) {
1930 other_right = this->u.industry.other_accepted;
1931 other_left = this->u.industry.other_produced;
1932 } else {
1933 other_right = this->u.industry.other_produced;
1934 other_left = this->u.industry.other_accepted;
1936 ypos1 += VERT_CARGO_EDGE;
1937 for (uint i = 0; i < MAX_CARGOES; i++) {
1938 if (other_right[i] != INVALID_CARGO) {
1939 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
1940 int xp = xpos + industry_width + CARGO_STUB_WIDTH;
1941 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
1942 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1944 if (other_left[i] != INVALID_CARGO) {
1945 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
1946 int xp = xpos - CARGO_STUB_WIDTH;
1947 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
1948 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1950 ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1952 break;
1955 case CFT_CARGO: {
1956 int cargo_base = this->GetCargoBase(xpos);
1957 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
1958 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
1959 int colpos = cargo_base;
1960 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1961 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
1962 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
1963 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1964 colpos++;
1965 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
1966 GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
1967 colpos += HOR_CARGO_WIDTH - 2;
1968 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1969 colpos += 1 + HOR_CARGO_SPACE;
1972 const CargoID *hor_left, *hor_right;
1973 if (_current_text_dir == TD_RTL) {
1974 hor_left = this->u.cargo.cust_cargoes;
1975 hor_right = this->u.cargo.supp_cargoes;
1976 } else {
1977 hor_left = this->u.cargo.supp_cargoes;
1978 hor_right = this->u.cargo.cust_cargoes;
1980 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
1981 for (uint i = 0; i < MAX_CARGOES; i++) {
1982 if (hor_left[i] != INVALID_CARGO) {
1983 int col = hor_left[i];
1984 int dx = 0;
1985 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1986 for (; col > 0; col--) {
1987 int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
1988 DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
1989 dx = 1;
1991 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
1993 if (hor_right[i] != INVALID_CARGO) {
1994 int col = hor_right[i];
1995 int dx = 0;
1996 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1997 for (; col < this->u.cargo.num_cargoes - 1; col++) {
1998 int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
1999 DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
2000 dx = 1;
2002 DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CARGO_FIELD_WIDTH - 1, ypos, csp);
2004 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2006 break;
2009 case CFT_CARGO_LABEL:
2010 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
2011 for (uint i = 0; i < MAX_CARGOES; i++) {
2012 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
2013 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
2014 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
2015 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
2017 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2019 break;
2021 default:
2022 NOT_REACHED();
2027 * Decide which cargo was clicked at in a #CFT_CARGO field.
2028 * @param left Left industry neighbour if available (else \c NULL should be supplied).
2029 * @param right Right industry neighbour if available (else \c NULL should be supplied).
2030 * @param pt Click position in the cargo field.
2031 * @return Cargo clicked at, or #INVALID_CARGO if none.
2033 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
2035 assert(this->type == CFT_CARGO);
2037 /* Vertical matching. */
2038 int cpos = this->GetCargoBase(0);
2039 uint col;
2040 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
2041 if (pt.x < cpos) break;
2042 if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
2043 cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
2045 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
2047 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
2048 uint row;
2049 for (row = 0; row < MAX_CARGOES; row++) {
2050 if (pt.y < vpos) return INVALID_CARGO;
2051 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2052 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2054 if (row == MAX_CARGOES) return INVALID_CARGO;
2056 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
2057 if (col == 0) {
2058 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
2059 if (left != NULL) {
2060 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
2061 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
2063 return INVALID_CARGO;
2065 if (col == this->u.cargo.num_cargoes) {
2066 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
2067 if (right != NULL) {
2068 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
2069 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
2071 return INVALID_CARGO;
2073 if (row >= col) {
2074 /* Clicked somewhere in-between vertical cargo connection.
2075 * Since the horizontal connection is made in the same order as the vertical list, the above condition
2076 * ensures we are left-below the main diagonal, thus at the supplying side.
2078 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
2079 } else {
2080 /* Clicked at a customer connection. */
2081 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
2086 * Decide what cargo the user clicked in the cargo label field.
2087 * @param pt Click position in the cargo label field.
2088 * @return Cargo clicked at, or #INVALID_CARGO if none.
2090 CargoID CargoLabelClickedAt(Point pt) const
2092 assert(this->type == CFT_CARGO_LABEL);
2094 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
2095 uint row;
2096 for (row = 0; row < MAX_CARGOES; row++) {
2097 if (pt.y < vpos) return INVALID_CARGO;
2098 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2099 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2101 if (row == MAX_CARGOES) return INVALID_CARGO;
2102 return this->u.cargo_label.cargoes[row];
2105 private:
2107 * Draw a horizontal cargo connection.
2108 * @param left Left-most coordinate to draw.
2109 * @param right Right-most coordinate to draw.
2110 * @param top Top coordinate of the cargo connection.
2111 * @param csp Cargo to draw.
2113 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
2115 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
2116 GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
2117 GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
2121 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
2122 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
2124 int CargoesField::small_height; ///< Height of the header row.
2125 int CargoesField::normal_height; ///< Height of the non-header rows.
2126 int CargoesField::industry_width; ///< Width of an industry field.
2127 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; ///< Amount of space between two industries in a column.
2129 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.
2130 const int CargoesField::CARGO_STUB_WIDTH = 10; ///< Width of a cargo not carried in the column (should be less than #HOR_CARGO_BORDER_SPACE).
2131 const int CargoesField::HOR_CARGO_WIDTH = 15; ///< Width of a vertical cargo column (inclusive the border line).
2132 const int CargoesField::HOR_CARGO_SPACE = 5; ///< Amount of horizontal space between two vertical cargoes.
2133 const int CargoesField::VERT_CARGO_EDGE = 4; ///< Amount of vertical space between top/bottom and the top/bottom connected cargo at an industry.
2134 const int CargoesField::VERT_CARGO_SPACE = 4; ///< Amount of vertical space between two connected cargoes at an industry.
2136 const int CargoesField::BLOB_DISTANCE = 5; ///< Distance of the industry legend colour from the edge of the industry box.
2137 const int CargoesField::BLOB_WIDTH = 12; ///< Width of the industry legend colour, including border.
2138 const int CargoesField::BLOB_HEIGHT = 9; ///< Height of the industry legend colour, including border
2140 /** Width of a #CFT_CARGO field. */
2141 const int CargoesField::CARGO_FIELD_WIDTH = HOR_CARGO_BORDER_SPACE * 2 + HOR_CARGO_WIDTH * MAX_CARGOES + HOR_CARGO_SPACE * (MAX_CARGOES - 1);
2143 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; ///< Line colour of the industry type box.
2144 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW; ///< Line colour around the cargo.
2146 /** A single row of #CargoesField. */
2147 struct CargoesRow {
2148 CargoesField columns[5]; ///< One row of fields.
2151 * Connect industry production cargoes to the cargo column after it.
2152 * @param column Column of the industry.
2154 void ConnectIndustryProduced(int column)
2156 CargoesField *ind_fld = this->columns + column;
2157 CargoesField *cargo_fld = this->columns + column + 1;
2158 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2160 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
2162 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2163 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
2164 int other_count = 0;
2166 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2167 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
2168 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
2169 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
2172 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2173 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
2174 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
2176 } else {
2177 /* Houses only display what is demanded. */
2178 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2179 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
2180 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
2186 * Construct a #CFT_CARGO_LABEL field.
2187 * @param column Column to create the new field.
2188 * @param accepting Display accepted cargo (if \c false, display produced cargo).
2190 void MakeCargoLabel(int column, bool accepting)
2192 CargoID cargoes[MAX_CARGOES];
2193 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
2195 CargoesField *label_fld = this->columns + column;
2196 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
2198 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
2199 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2200 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
2201 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
2203 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
2208 * Connect industry accepted cargoes to the cargo column before it.
2209 * @param column Column of the industry.
2211 void ConnectIndustryAccepted(int column)
2213 CargoesField *ind_fld = this->columns + column;
2214 CargoesField *cargo_fld = this->columns + column - 1;
2215 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2217 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
2219 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2220 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
2221 int other_count = 0;
2223 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2224 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
2225 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
2226 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
2229 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2230 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
2231 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
2233 } else {
2234 /* Houses only display what is demanded. */
2235 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2236 for (uint h = 0; h < NUM_HOUSES; h++) {
2237 HouseSpec *hs = HouseSpec::Get(h);
2238 if (!hs->enabled) continue;
2240 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2241 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2242 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2243 goto next_cargo;
2247 next_cargo: ;
2255 * Window displaying the cargo connections around an industry (or cargo).
2257 * The main display is constructed from 'fields', rectangles that contain an industry, piece of the cargo connection, cargo labels, or headers.
2258 * For a nice display, the following should be kept in mind:
2259 * - A #CFT_HEADER is always at the top of an column of #CFT_INDUSTRY fields.
2260 * - A #CFT_CARGO_LABEL field is also always put in a column of #CFT_INDUSTRY fields.
2261 * - The top row contains #CFT_HEADER and #CFT_SMALL_EMPTY fields.
2262 * - Cargo connections have a column of their own (#CFT_CARGO fields).
2263 * - 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.
2264 * The information however is part of the industry.
2266 * This results in the following invariants:
2267 * - Width of a #CFT_INDUSTRY column is large enough to hold all industry type labels, all cargo labels, and all header texts.
2268 * - Height of a #CFT_INDUSTRY is large enough to hold a header line, or a industry type line, \c N cargo labels
2269 * (where \c N is the maximum number of cargoes connected between industries), \c N connections of cargo types, and space
2270 * between two industry types (1/2 above it, and 1/2 underneath it).
2271 * - Width of a cargo field (#CFT_CARGO) is large enough to hold \c N vertical columns (one for each type of cargo).
2272 * Also, space is needed between an industry and the leftmost/rightmost column to draw the non-carried cargoes.
2273 * - Height of a #CFT_CARGO field is equally high as the height of the #CFT_INDUSTRY.
2274 * - A field at the top (#CFT_HEADER or #CFT_SMALL_EMPTY) match the width of the fields below them (#CFT_INDUSTRY respectively
2275 * #CFT_CARGO), the height should be sufficient to display the header text.
2277 * When displaying the cargoes around an industry type, five columns are needed (supplying industries, accepted cargoes, the industry,
2278 * produced cargoes, customer industries). Displaying the industries around a cargo needs three columns (supplying industries, the cargo,
2279 * 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.
2281 struct IndustryCargoesWindow : public Window {
2282 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2284 typedef SmallVector<CargoesRow, 4> Fields;
2286 Fields fields; ///< Fields to display in the #WID_IC_PANEL.
2287 uint ind_cargo; ///< If less than #NUM_INDUSTRYTYPES, an industry type, else a cargo id + NUM_INDUSTRYTYPES.
2288 Dimension cargo_textsize; ///< Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
2289 Dimension ind_textsize; ///< Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
2290 Scrollbar *vscroll;
2292 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2294 this->OnInit();
2295 this->CreateNestedTree();
2296 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2297 this->FinishInitNested(0);
2298 this->OnInvalidateData(id);
2301 virtual void OnInit()
2303 /* Initialize static CargoesField size variables. */
2304 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2305 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2306 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2307 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2308 CargoesField::small_height = d.height;
2310 /* Decide about the size of the box holding the text of an industry type. */
2311 this->ind_textsize.width = 0;
2312 this->ind_textsize.height = 0;
2313 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2314 const IndustrySpec *indsp = GetIndustrySpec(it);
2315 if (!indsp->enabled) continue;
2316 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2318 d.width = max(d.width, this->ind_textsize.width);
2319 d.height = this->ind_textsize.height;
2320 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2322 /* Compute max size of the cargo texts. */
2323 this->cargo_textsize.width = 0;
2324 this->cargo_textsize.height = 0;
2325 for (uint i = 0; i < NUM_CARGO; i++) {
2326 const CargoSpec *csp = CargoSpec::Get(i);
2327 if (!csp->IsValid()) continue;
2328 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2330 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2331 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2333 d.width += 2 * HOR_TEXT_PADDING;
2334 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2335 uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + MAX_CARGOES * FONT_HEIGHT_NORMAL + (MAX_CARGOES - 1) * CargoesField::VERT_CARGO_SPACE;
2336 d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2338 CargoesField::industry_width = d.width;
2339 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2342 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2344 switch (widget) {
2345 case WID_IC_PANEL:
2346 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::CARGO_FIELD_WIDTH * 2 + WD_FRAMETEXT_RIGHT;
2347 break;
2349 case WID_IC_IND_DROPDOWN:
2350 size->width = max(size->width, this->ind_textsize.width + padding.width);
2351 break;
2353 case WID_IC_CARGO_DROPDOWN:
2354 size->width = max(size->width, this->cargo_textsize.width + padding.width);
2355 break;
2360 CargoesFieldType type; ///< Type of field.
2361 virtual void SetStringParameters (int widget) const
2363 if (widget != WID_IC_CAPTION) return;
2365 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2366 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2367 SetDParam(0, indsp->name);
2368 } else {
2369 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2370 SetDParam(0, csp->name);
2375 * Do the two sets of cargoes have a valid cargo in common?
2376 * @param cargoes1 Base address of the first cargo array.
2377 * @param length1 Number of cargoes in the first cargo array.
2378 * @param cargoes2 Base address of the second cargo array.
2379 * @param length2 Number of cargoes in the second cargo array.
2380 * @return Arrays have at least one valid cargo in common.
2382 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2384 while (length1 > 0) {
2385 if (*cargoes1 != INVALID_CARGO) {
2386 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2388 cargoes1++;
2389 length1--;
2391 return false;
2395 * Can houses be used to supply one of the cargoes?
2396 * @param cargoes Base address of the cargo array.
2397 * @param length Number of cargoes in the array.
2398 * @return Houses can supply at least one of the cargoes.
2400 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2402 for (uint i = 0; i < length; i++) {
2403 if (cargoes[i] == INVALID_CARGO) continue;
2404 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2406 return false;
2410 * Can houses be used as customers of the produced cargoes?
2411 * @param cargoes Base address of the cargo array.
2412 * @param length Number of cargoes in the array.
2413 * @return Houses can accept at least one of the cargoes.
2415 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2417 HouseZones climate_mask;
2418 switch (_settings_game.game_creation.landscape) {
2419 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2420 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2421 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2422 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2423 default: NOT_REACHED();
2425 for (uint i = 0; i < length; i++) {
2426 if (cargoes[i] == INVALID_CARGO) continue;
2428 for (uint h = 0; h < NUM_HOUSES; h++) {
2429 HouseSpec *hs = HouseSpec::Get(h);
2430 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2432 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2433 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2437 return false;
2441 * Count how many industries have accepted cargoes in common with one of the supplied set.
2442 * @param cargoes Cargoes to search.
2443 * @param length Number of cargoes in \a cargoes.
2444 * @return Number of industries that have an accepted cargo in common with the supplied set.
2446 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2448 int count = 0;
2449 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2450 const IndustrySpec *indsp = GetIndustrySpec(it);
2451 if (!indsp->enabled) continue;
2453 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2455 return count;
2459 * Count how many industries have produced cargoes in common with one of the supplied set.
2460 * @param cargoes Cargoes to search.
2461 * @param length Number of cargoes in \a cargoes.
2462 * @return Number of industries that have a produced cargo in common with the supplied set.
2464 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2466 int count = 0;
2467 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2468 const IndustrySpec *indsp = GetIndustrySpec(it);
2469 if (!indsp->enabled) continue;
2471 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2473 return count;
2477 * Shorten the cargo column to just the part between industries.
2478 * @param column Column number of the cargo column.
2479 * @param top Current top row.
2480 * @param bottom Current bottom row.
2482 void ShortenCargoColumn(int column, int top, int bottom)
2484 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2485 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2486 top++;
2488 this->fields[top].columns[column].u.cargo.top_end = true;
2490 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2491 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2492 bottom--;
2494 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2498 * Place an industry in the fields.
2499 * @param row Row of the new industry.
2500 * @param col Column of the new industry.
2501 * @param it Industry to place.
2503 void PlaceIndustry(int row, int col, IndustryType it)
2505 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2506 this->fields[row].columns[col].MakeIndustry(it);
2507 if (col == 0) {
2508 this->fields[row].ConnectIndustryProduced(col);
2509 } else {
2510 this->fields[row].ConnectIndustryAccepted(col);
2515 * Notify smallmap that new displayed industries have been selected (in #_displayed_industries).
2517 void NotifySmallmap()
2519 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2521 /* Only notify the smallmap window if it exists. In particular, do not
2522 * bring it to the front to prevent messing up any nice layout of the user. */
2523 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2525 /* Notify viewports too. */
2526 Window *w;
2527 FOR_ALL_WINDOWS_FROM_BACK(w) {
2528 if (w->viewport != NULL)
2529 if (w->viewport->zoom >= ZOOM_LVL_DRAW_MAP && w->viewport->map_type == VPMT_INDUSTRY)
2530 w->InvalidateData();
2535 * Compute what and where to display for industry type \a it.
2536 * @param it Industry type to display.
2538 void ComputeIndustryDisplay(IndustryType it)
2540 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2541 this->ind_cargo = it;
2542 _displayed_industries.reset();
2543 _displayed_industries.set(it);
2545 this->fields.Clear();
2546 CargoesRow *row = this->fields.Append();
2547 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2548 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2549 row->columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2550 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2551 row->columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2553 const IndustrySpec *central_sp = GetIndustrySpec(it);
2554 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2555 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2556 /* Make a field consisting of two cargo columns. */
2557 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2558 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2559 int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
2560 for (int i = 0; i < num_indrows; i++) {
2561 CargoesRow *row = this->fields.Append();
2562 row->columns[0].MakeEmpty(CFT_EMPTY);
2563 row->columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2564 row->columns[2].MakeEmpty(CFT_EMPTY);
2565 row->columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2566 row->columns[4].MakeEmpty(CFT_EMPTY);
2568 /* Add central industry. */
2569 int central_row = 1 + num_indrows / 2;
2570 this->fields[central_row].columns[2].MakeIndustry(it);
2571 this->fields[central_row].ConnectIndustryProduced(2);
2572 this->fields[central_row].ConnectIndustryAccepted(2);
2574 /* Add cargo labels. */
2575 this->fields[central_row - 1].MakeCargoLabel(2, true);
2576 this->fields[central_row + 1].MakeCargoLabel(2, false);
2578 /* Add suppliers and customers of the 'it' industry. */
2579 int supp_count = 0;
2580 int cust_count = 0;
2581 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2582 const IndustrySpec *indsp = GetIndustrySpec(it);
2583 if (!indsp->enabled) continue;
2585 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2586 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2587 _displayed_industries.set(it);
2588 supp_count++;
2590 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2591 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2592 _displayed_industries.set(it);
2593 cust_count++;
2596 if (houses_supply) {
2597 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2598 supp_count++;
2600 if (houses_accept) {
2601 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2602 cust_count++;
2605 this->ShortenCargoColumn(1, 1, num_indrows);
2606 this->ShortenCargoColumn(3, 1, num_indrows);
2607 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2608 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2609 this->SetDirty();
2610 this->NotifySmallmap();
2614 * Compute what and where to display for cargo id \a cid.
2615 * @param cid Cargo id to display.
2617 void ComputeCargoDisplay(CargoID cid)
2619 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2620 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2621 _displayed_industries.reset();
2623 this->fields.Clear();
2624 CargoesRow *row = this->fields.Append();
2625 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2626 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2627 row->columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2628 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2629 row->columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2631 bool houses_supply = HousesCanSupply(&cid, 1);
2632 bool houses_accept = HousesCanAccept(&cid, 1);
2633 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2634 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2635 int num_indrows = max(num_supp, num_cust);
2636 for (int i = 0; i < num_indrows; i++) {
2637 CargoesRow *row = this->fields.Append();
2638 row->columns[0].MakeEmpty(CFT_EMPTY);
2639 row->columns[1].MakeCargo(&cid, 1);
2640 row->columns[2].MakeEmpty(CFT_EMPTY);
2641 row->columns[3].MakeEmpty(CFT_EMPTY);
2642 row->columns[4].MakeEmpty(CFT_EMPTY);
2645 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2647 /* Add suppliers and customers of the cargo. */
2648 int supp_count = 0;
2649 int cust_count = 0;
2650 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2651 const IndustrySpec *indsp = GetIndustrySpec(it);
2652 if (!indsp->enabled) continue;
2654 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2655 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2656 _displayed_industries.set(it);
2657 supp_count++;
2659 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2660 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2661 _displayed_industries.set(it);
2662 cust_count++;
2665 if (houses_supply) {
2666 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2667 supp_count++;
2669 if (houses_accept) {
2670 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2671 cust_count++;
2674 this->ShortenCargoColumn(1, 1, num_indrows);
2675 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2676 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2677 this->SetDirty();
2678 this->NotifySmallmap();
2682 * Some data on this window has become invalid.
2683 * @param data Information about the changed data.
2684 * - data = 0 .. NUM_INDUSTRYTYPES - 1: Display the chain around the given industry.
2685 * - data = NUM_INDUSTRYTYPES: Stop sending updates to the smallmap window.
2686 * @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.
2688 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2690 if (!gui_scope) return;
2691 if (data == NUM_INDUSTRYTYPES) {
2692 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2693 this->RaiseWidget(WID_IC_NOTIFY);
2694 this->SetWidgetDirty(WID_IC_NOTIFY);
2696 return;
2699 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2700 this->ComputeIndustryDisplay(data);
2703 virtual void DrawWidget(const Rect &r, int widget) const
2705 if (widget != WID_IC_PANEL) return;
2707 DrawPixelInfo tmp_dpi, *old_dpi;
2708 int width = r.right - r.left + 1;
2709 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2710 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2711 old_dpi = _cur_dpi;
2712 _cur_dpi = &tmp_dpi;
2714 int left_pos = WD_FRAMERECT_LEFT;
2715 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
2716 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2718 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2719 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2720 for (uint i = 0; i < this->fields.Length(); i++) {
2721 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2722 if (vpos + row_height >= 0) {
2723 int xpos = left_pos;
2724 int col, dir;
2725 if (_current_text_dir == TD_RTL) {
2726 col = last_column;
2727 dir = -1;
2728 } else {
2729 col = 0;
2730 dir = 1;
2732 while (col >= 0 && col <= last_column) {
2733 this->fields[i].columns[col].Draw(xpos, vpos);
2734 xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2735 col += dir;
2738 vpos += row_height;
2739 if (vpos >= height) break;
2742 _cur_dpi = old_dpi;
2746 * Calculate in which field was clicked, and within the field, at what position.
2747 * @param pt Clicked position in the #WID_IC_PANEL widget.
2748 * @param fieldxy If \c true is returned, field x/y coordinate of \a pt.
2749 * @param xy If \c true is returned, x/y coordinate with in the field.
2750 * @return Clicked at a valid position.
2752 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2754 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2755 pt.x -= nw->pos_x;
2756 pt.y -= nw->pos_y;
2758 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2759 if (pt.y < vpos) return false;
2761 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2762 if (row + 1 >= (int)this->fields.Length()) return false;
2763 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2764 row++; // rebase row to match index of this->fields.
2766 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
2767 if (pt.x < xpos) return false;
2768 int column;
2769 for (column = 0; column <= 5; column++) {
2770 int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2771 if (pt.x < xpos + width) break;
2772 xpos += width;
2774 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2775 if (column > num_columns) return false;
2776 xpos = pt.x - xpos;
2778 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2779 fieldxy->y = row;
2780 xy->y = vpos;
2781 if (_current_text_dir == TD_RTL) {
2782 fieldxy->x = num_columns - column;
2783 xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
2784 } else {
2785 fieldxy->x = column;
2786 xy->x = xpos;
2788 return true;
2791 virtual void OnClick(Point pt, int widget, int click_count)
2793 switch (widget) {
2794 case WID_IC_PANEL: {
2795 Point fieldxy, xy;
2796 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2798 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2799 switch (fld->type) {
2800 case CFT_INDUSTRY:
2801 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
2802 break;
2804 case CFT_CARGO: {
2805 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2806 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2807 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
2808 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2809 break;
2812 case CFT_CARGO_LABEL: {
2813 CargoID cid = fld->CargoLabelClickedAt(xy);
2814 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2815 break;
2818 default:
2819 break;
2821 break;
2824 case WID_IC_NOTIFY:
2825 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
2826 this->SetWidgetDirty(WID_IC_NOTIFY);
2827 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
2829 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2830 if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
2831 this->NotifySmallmap();
2833 break;
2835 case WID_IC_CARGO_DROPDOWN: {
2836 DropDownList *lst = new DropDownList;
2837 const CargoSpec *cs;
2838 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
2839 *lst->Append() = new DropDownListStringItem(cs->name, cs->Index(), false);
2841 if (lst->Length() == 0) {
2842 delete lst;
2843 break;
2845 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
2846 ShowDropDownList(this, lst, selected, WID_IC_CARGO_DROPDOWN, 0, true);
2847 break;
2850 case WID_IC_IND_DROPDOWN: {
2851 DropDownList *lst = new DropDownList;
2852 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
2853 IndustryType ind = _sorted_industry_types[i];
2854 const IndustrySpec *indsp = GetIndustrySpec(ind);
2855 if (!indsp->enabled) continue;
2856 *lst->Append() = new DropDownListStringItem(indsp->name, ind, false);
2858 if (lst->Length() == 0) {
2859 delete lst;
2860 break;
2862 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
2863 ShowDropDownList(this, lst, selected, WID_IC_IND_DROPDOWN, 0, true);
2864 break;
2869 virtual void OnDropdownSelect(int widget, int index)
2871 if (index < 0) return;
2873 switch (widget) {
2874 case WID_IC_CARGO_DROPDOWN:
2875 this->ComputeCargoDisplay(index);
2876 break;
2878 case WID_IC_IND_DROPDOWN:
2879 this->ComputeIndustryDisplay(index);
2880 break;
2884 virtual void OnToolTip(Point pt, int widget, TooltipCloseCondition close_cond)
2886 if (widget != WID_IC_PANEL) {
2887 this->Window::OnToolTip(pt, widget, close_cond);
2888 return;
2891 Point fieldxy, xy;
2892 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2894 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2895 CargoID cid = INVALID_CARGO;
2896 switch (fld->type) {
2897 case CFT_CARGO: {
2898 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2899 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2900 cid = fld->CargoClickedAt(lft, rgt, xy);
2901 break;
2904 case CFT_CARGO_LABEL: {
2905 cid = fld->CargoLabelClickedAt(xy);
2906 break;
2909 case CFT_INDUSTRY:
2910 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
2911 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, close_cond);
2913 return;
2915 default:
2916 break;
2918 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
2919 const CargoSpec *csp = CargoSpec::Get(cid);
2920 SetDParam(0, csp->name);
2921 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, close_cond);
2925 virtual void OnResize()
2927 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL);
2931 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5; ///< Horizontal padding around the industry type text.
2932 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; ///< Vertical padding around the industry type text.
2935 * Open the industry and cargoes window.
2936 * @param id Industry type to display, \c NUM_INDUSTRYTYPES selects a default industry type.
2938 static void ShowIndustryCargoesWindow(IndustryType id)
2940 if (id >= NUM_INDUSTRYTYPES) {
2941 for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
2942 const IndustrySpec *indsp = GetIndustrySpec(_sorted_industry_types[i]);
2943 if (indsp->enabled) {
2944 id = _sorted_industry_types[i];
2945 break;
2948 if (id >= NUM_INDUSTRYTYPES) return;
2951 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
2952 if (w != NULL) {
2953 w->InvalidateData(id);
2954 return;
2956 new IndustryCargoesWindow(id);
2959 /** Open the industry and cargoes window with an industry. */
2960 void ShowIndustryCargoesWindow()
2962 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);