OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

industry_gui.cpp
Go to the documentation of this file.
1 /* $Id: industry_gui.cpp 26960 2014-10-05 11:20:02Z peter1138 $ */
2
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 */
9
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
43 #include "table/strings.h"
44
45 #include "safeguards.h"
46
47 bool _ignore_restrictions;
48 uint64 _displayed_industries;
49
50 assert_compile(NUM_INDUSTRYTYPES <= 64); // Make sure all industry types fit in _displayed_industries.
51
53 enum CargoSuffixType {
54 CST_FUND,
55 CST_VIEW,
56 CST_DIR,
57 };
58
59 static void ShowIndustryCargoesWindow(IndustryType id);
60
76 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, char *suffix, const char *suffix_last)
77 {
78 suffix[0] = '\0';
79 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
80 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, (cst != CST_FUND) ? ind->location.tile : INVALID_TILE);
81 if (callback == CALLBACK_FAILED || callback == 0x400) return;
82 if (callback > 0x400) {
83 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
84 } else if (indspec->grf_prop.grffile->grf_version >= 8 || GB(callback, 0, 8) != 0xFF) {
85 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
86 GetString(suffix, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), suffix_last);
87 StopTextRefStackUsage();
88 }
89 }
90 }
91
102 template <typename TC, typename TS>
103 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
104 {
105 assert_compile(lengthof(cargoes) <= lengthof(suffixes));
106 for (uint j = 0; j < lengthof(cargoes); j++) {
107 if (cargoes[j] != CT_INVALID) {
108 GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j], lastof(suffixes[j]));
109 } else {
110 suffixes[j][0] = '\0';
111 }
112 }
113 }
114
115 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES];
116
118 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
119 {
120 static char industry_name[2][64];
121
122 const IndustrySpec *indsp1 = GetIndustrySpec(*a);
123 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
124
125 const IndustrySpec *indsp2 = GetIndustrySpec(*b);
126 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
127
128 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
129
130 /* If the names are equal, sort by industry type. */
131 return (r != 0) ? r : (*a - *b);
132 }
133
137 void SortIndustryTypes()
138 {
139 /* Add each industry type to the list. */
140 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
141 _sorted_industry_types[i] = i;
142 }
143
144 /* Sort industry types by name. */
145 QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
146 }
147
155 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
156 {
157 if (result.Succeeded()) return;
158
159 uint8 indtype = GB(p1, 0, 8);
160 if (indtype < NUM_INDUSTRYTYPES) {
161 const IndustrySpec *indsp = GetIndustrySpec(indtype);
162 if (indsp->enabled) {
163 SetDParam(0, indsp->name);
164 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
165 }
166 }
167 }
168
169 static const NWidgetPart _nested_build_industry_widgets[] = {
170 NWidget(NWID_HORIZONTAL),
171 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
172 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
173 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
174 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
175 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
176 EndContainer(),
177 NWidget(NWID_HORIZONTAL),
178 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_DPI_MATRIX_WIDGET), SetMatrixDataTip(1, 0, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_DPI_SCROLLBAR),
179 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
180 EndContainer(),
181 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
182 EndContainer(),
183 NWidget(NWID_HORIZONTAL),
184 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
185 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
186 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
187 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
188 EndContainer(),
189 };
190
192 static WindowDesc _build_industry_desc(
193 WDP_AUTO, "build_industry", 170, 212,
194 WC_BUILD_INDUSTRY, WC_NONE,
195 WDF_CONSTRUCTION,
196 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
197 );
198
200 class BuildIndustryWindow : public Window {
201 int selected_index;
202 IndustryType selected_type;
203 uint16 callback_timer;
204 bool timer_enabled;
205 uint16 count;
206 IndustryType index[NUM_INDUSTRYTYPES + 1];
207 bool enabled[NUM_INDUSTRYTYPES + 1];
208 Scrollbar *vscroll;
209
211 static const int MATRIX_TEXT_OFFSET = 17;
212
213 void SetupArrays()
214 {
215 this->count = 0;
216
217 for (uint i = 0; i < lengthof(this->index); i++) {
218 this->index[i] = INVALID_INDUSTRYTYPE;
219 this->enabled[i] = false;
220 }
221
222 if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
223 this->index[this->count] = INVALID_INDUSTRYTYPE;
224 this->enabled[this->count] = true;
225 this->count++;
226 this->timer_enabled = false;
227 }
228 /* Fill the arrays with industries.
229 * The tests performed after the enabled allow to load the industries
230 * In the same way they are inserted by grf (if any)
231 */
232 for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
233 IndustryType ind = _sorted_industry_types[i];
234 const IndustrySpec *indsp = GetIndustrySpec(ind);
235 if (indsp->enabled) {
236 /* Rule is that editor mode loads all industries.
237 * In game mode, all non raw industries are loaded too
238 * and raw ones are loaded only when setting allows it */
239 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
240 /* Unselect if the industry is no longer in the list */
241 if (this->selected_type == ind) this->selected_index = -1;
242 continue;
243 }
244 this->index[this->count] = ind;
245 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
246 /* Keep the selection to the correct line */
247 if (this->selected_type == ind) this->selected_index = this->count;
248 this->count++;
249 }
250 }
251
252 /* first industry type is selected if the current selection is invalid.
253 * I'll be damned if there are none available ;) */
254 if (this->selected_index == -1) {
255 this->selected_index = 0;
256 this->selected_type = this->index[0];
257 }
258
259 this->vscroll->SetCount(this->count);
260 }
261
263 void SetButtons()
264 {
265 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
266 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
267 }
268
269 public:
270 BuildIndustryWindow() : Window(&_build_industry_desc)
271 {
272 this->timer_enabled = _loaded_newgrf_features.has_newindustries;
273
274 this->selected_index = -1;
275 this->selected_type = INVALID_INDUSTRYTYPE;
276
277 this->callback_timer = DAY_TICKS;
278
279 this->CreateNestedTree();
280 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
281 this->FinishInitNested(0);
282
283 this->SetButtons();
284 }
285
286 virtual void OnInit()
287 {
288 this->SetupArrays();
289 }
290
291 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
292 {
293 switch (widget) {
294 case WID_DPI_MATRIX_WIDGET: {
295 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
296 for (byte i = 0; i < this->count; i++) {
297 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
298 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
299 }
300 resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
301 d.width += MATRIX_TEXT_OFFSET + padding.width;
302 d.height = 5 * resize->height;
303 *size = maxdim(*size, d);
304 break;
305 }
306
307 case WID_DPI_INFOPANEL: {
308 /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
309 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
310 Dimension d = {0, 0};
311 for (byte i = 0; i < this->count; i++) {
312 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
313
314 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
315
316 char cargo_suffix[3][512];
317 GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
318 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
319 byte p = 0;
320 SetDParam(0, STR_JUST_NOTHING);
321 SetDParamStr(1, "");
322 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
323 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
324 if (p > 0) str++;
325 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
326 SetDParamStr(p++, cargo_suffix[j]);
327 }
328 d = maxdim(d, GetStringBoundingBox(str));
329
330 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
331 GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
332 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
333 p = 0;
334 SetDParam(0, STR_JUST_NOTHING);
335 SetDParamStr(1, "");
336 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
337 if (indsp->produced_cargo[j] == CT_INVALID) continue;
338 if (p > 0) str++;
339 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
340 SetDParamStr(p++, cargo_suffix[j]);
341 }
342 d = maxdim(d, GetStringBoundingBox(str));
343 }
344
345 /* Set it to something more sane :) */
346 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
347 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
348 break;
349 }
350
351 case WID_DPI_FUND_WIDGET: {
352 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
353 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
354 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
355 d.width += padding.width;
356 d.height += padding.height;
357 *size = maxdim(*size, d);
358 break;
359 }
360 }
361 }
362
363 virtual void SetStringParameters(int widget) const
364 {
365 switch (widget) {
366 case WID_DPI_FUND_WIDGET:
367 /* Raw industries might be prospected. Show this fact by changing the string
368 * In Editor, you just build, while ingame, or you fund or you prospect */
369 if (_game_mode == GM_EDITOR) {
370 /* We've chosen many random industries but no industries have been specified */
371 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
372 } else {
373 const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
374 SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
375 }
376 break;
377 }
378 }
379
380 virtual void DrawWidget(const Rect &r, int widget) const
381 {
382 switch (widget) {
383 case WID_DPI_MATRIX_WIDGET: {
384 uint text_left, text_right, icon_left, icon_right;
385 if (_current_text_dir == TD_RTL) {
386 icon_right = r.right - WD_MATRIX_RIGHT;
387 icon_left = icon_right - 10;
388 text_right = icon_right - BuildIndustryWindow::MATRIX_TEXT_OFFSET;
389 text_left = r.left + WD_MATRIX_LEFT;
390 } else {
391 icon_left = r.left + WD_MATRIX_LEFT;
392 icon_right = icon_left + 10;
393 text_left = icon_left + BuildIndustryWindow::MATRIX_TEXT_OFFSET;
394 text_right = r.right - WD_MATRIX_RIGHT;
395 }
396
397 for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
398 int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
399 bool selected = this->selected_index == i + this->vscroll->GetPosition();
400
401 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
402 DrawString(text_left, text_right, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
403 continue;
404 }
405 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
406
407 /* Draw the name of the industry in white is selected, otherwise, in orange */
408 DrawString(text_left, text_right, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
409 GfxFillRect(icon_left, y + 1, icon_right, y + 7, selected ? PC_WHITE : PC_BLACK);
410 GfxFillRect(icon_left + 1, y + 2, icon_right - 1, y + 6, indsp->map_colour);
411 }
412 break;
413 }
414
415 case WID_DPI_INFOPANEL: {
416 int y = r.top + WD_FRAMERECT_TOP;
417 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
418 int left = r.left + WD_FRAMERECT_LEFT;
419 int right = r.right - WD_FRAMERECT_RIGHT;
420
421 if (this->selected_type == INVALID_INDUSTRYTYPE) {
422 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
423 break;
424 }
425
426 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
427
428 if (_game_mode != GM_EDITOR) {
429 SetDParam(0, indsp->GetConstructionCost());
430 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
431 y += FONT_HEIGHT_NORMAL;
432 }
433
434 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
435 char cargo_suffix[3][512];
436 GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
437 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
438 byte p = 0;
439 SetDParam(0, STR_JUST_NOTHING);
440 SetDParamStr(1, "");
441 for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
442 if (indsp->accepts_cargo[j] == CT_INVALID) continue;
443 if (p > 0) str++;
444 SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
445 SetDParamStr(p++, cargo_suffix[j]);
446 }
447 DrawString(left, right, y, str);
448 y += FONT_HEIGHT_NORMAL;
449
450 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
451 GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
452 str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
453 p = 0;
454 SetDParam(0, STR_JUST_NOTHING);
455 SetDParamStr(1, "");
456 for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
457 if (indsp->produced_cargo[j] == CT_INVALID) continue;
458 if (p > 0) str++;
459 SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
460 SetDParamStr(p++, cargo_suffix[j]);
461 }
462 DrawString(left, right, y, str);
463 y += FONT_HEIGHT_NORMAL;
464
465 /* Get the additional purchase info text, if it has not already been queried. */
466 str = STR_NULL;
467 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
468 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
469 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
470 if (callback_res > 0x400) {
471 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
472 } else {
473 str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
474 if (str != STR_UNDEFINED) {
475 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
476 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
477 StopTextRefStackUsage();
478 }
479 }
480 }
481 }
482 break;
483 }
484 }
485 }
486
487 virtual void OnClick(Point pt, int widget, int click_count)
488 {
489 switch (widget) {
490 case WID_DPI_MATRIX_WIDGET: {
491 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
492 if (y < this->count) { // Is it within the boundaries of available data?
493 this->selected_index = y;
494 this->selected_type = this->index[y];
495 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
496
497 this->SetDirty();
498
499 if (_thd.GetCallbackWnd() == this &&
500 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
501 this->selected_type == INVALID_INDUSTRYTYPE ||
502 !this->enabled[this->selected_index])) {
503 /* Reset the button state if going to prospecting or "build many industries" */
504 this->RaiseButtons();
505 ResetObjectToPlace();
506 }
507
508 this->SetButtons();
509 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
510 }
511 break;
512 }
513
514 case WID_DPI_DISPLAY_WIDGET:
515 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
516 break;
517
518 case WID_DPI_FUND_WIDGET: {
519 if (this->selected_type == INVALID_INDUSTRYTYPE) {
520 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
521
522 if (Town::GetNumItems() == 0) {
523 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
524 } else {
525 extern void GenerateIndustries();
526 _generating_world = true;
527 GenerateIndustries();
528 _generating_world = false;
529 }
530 } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
531 DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
532 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
533 } else {
534 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
535 }
536 break;
537 }
538 }
539 }
540
541 virtual void OnResize()
542 {
543 /* Adjust the number of items in the matrix depending of the resize */
544 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
545 }
546
547 virtual void OnPlaceObject(Point pt, TileIndex tile)
548 {
549 bool success = true;
550 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
551 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
552 uint32 seed = InteractiveRandom();
553
554 if (_game_mode == GM_EDITOR) {
555 /* Show error if no town exists at all */
556 if (Town::GetNumItems() == 0) {
557 SetDParam(0, indsp->name);
558 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
559 return;
560 }
561
562 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
563 _generating_world = true;
564 _ignore_restrictions = true;
565
566 DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
567 CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
568
569 cur_company.Restore();
570 _ignore_restrictions = false;
571 _generating_world = false;
572 } else {
573 success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
574 }
575
576 /* If an industry has been built, just reset the cursor and the system */
577 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
578 }
579
580 virtual void OnTick()
581 {
582 if (_pause_mode != PM_UNPAUSED) return;
583 if (!this->timer_enabled) return;
584 if (--this->callback_timer == 0) {
585 /* We have just passed another day.
586 * See if we need to update availability of currently selected industry */
587 this->callback_timer = DAY_TICKS; // restart counter
588
589 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
590
591 if (indsp->enabled) {
592 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
593
594 /* Only if result does match the previous state would it require a redraw. */
595 if (call_back_result != this->enabled[this->selected_index]) {
596 this->enabled[this->selected_index] = call_back_result;
597 this->SetButtons();
598 this->SetDirty();
599 }
600 }
601 }
602 }
603
604 virtual void OnTimeout()
605 {
606 this->RaiseButtons();
607 }
608
609 virtual void OnPlaceObjectAbort()
610 {
611 this->RaiseButtons();
612 }
613
619 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
620 {
621 if (!gui_scope) return;
622 this->SetupArrays();
623
624 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
625 if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
626 this->SetButtons();
627 }
628 };
629
630 void ShowBuildIndustryWindow()
631 {
632 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
633 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
634 new BuildIndustryWindow();
635 }
636
637 static void UpdateIndustryProduction(Industry *i);
638
639 static inline bool IsProductionAlterable(const Industry *i)
640 {
641 const IndustrySpec *is = GetIndustrySpec(i->type);
642 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
643 (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()) &&
644 !_networking);
645 }
646
647 class IndustryViewWindow : public Window
648 {
650 enum Editability {
651 EA_NONE,
652 EA_MULTIPLIER,
653 EA_RATE,
654 };
655
657 enum InfoLine {
658 IL_NONE,
659 IL_MULTIPLIER,
660 IL_RATE1,
661 IL_RATE2,
662 };
663
664 Editability editable;
665 InfoLine editbox_line;
666 InfoLine clicked_line;
667 byte clicked_button;
668 int production_offset_y;
669 int info_height;
670
671 public:
672 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
673 {
674 this->flags |= WF_DISABLE_VP_SCROLL;
675 this->editbox_line = IL_NONE;
676 this->clicked_line = IL_NONE;
677 this->clicked_button = 0;
678 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
679
680 this->InitNested(window_number);
681 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
682 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
683
684 this->InvalidateData();
685 }
686
687 virtual void OnPaint()
688 {
689 this->DrawWidgets();
690
691 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
692
693 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
694 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
695 if (expected > nwi->current_y - 1) {
696 this->info_height = expected + 1;
697 this->ReInit();
698 return;
699 }
700 }
701
709 int DrawInfo(uint left, uint right, uint top)
710 {
711 Industry *i = Industry::Get(this->window_number);
712 const IndustrySpec *ind = GetIndustrySpec(i->type);
713 int y = top + WD_FRAMERECT_TOP;
714 bool first = true;
715 bool has_accept = false;
716 char cargo_suffix[3][512];
717
718 if (i->prod_level == PRODLEVEL_CLOSURE) {
719 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
720 y += 2 * FONT_HEIGHT_NORMAL;
721 }
722
723 if (HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
724 GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
725 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
726 if (i->accepts_cargo[j] == CT_INVALID) continue;
727 has_accept = true;
728 if (first) {
729 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_FOR_PROCESSING);
730 y += FONT_HEIGHT_NORMAL;
731 first = false;
732 }
733 SetDParam(0, i->accepts_cargo[j]);
734 SetDParam(1, i->incoming_cargo_waiting[j]);
735 SetDParamStr(2, cargo_suffix[j]);
736 DrawString(left + WD_FRAMETEXT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_STOCKPILE_CARGO);
737 y += FONT_HEIGHT_NORMAL;
738 }
739 } else {
740 GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
741 StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
742 byte p = 0;
743 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
744 if (i->accepts_cargo[j] == CT_INVALID) continue;
745 has_accept = true;
746 if (p > 0) str++;
747 SetDParam(p++, CargoSpec::Get(i->accepts_cargo[j])->name);
748 SetDParamStr(p++, cargo_suffix[j]);
749 }
750 if (has_accept) {
751 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, str);
752 y += FONT_HEIGHT_NORMAL;
753 }
754 }
755
756 GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
757 first = true;
758 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
759 if (i->produced_cargo[j] == CT_INVALID) continue;
760 if (first) {
761 if (has_accept) y += WD_PAR_VSEP_WIDE;
762 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
763 y += FONT_HEIGHT_NORMAL;
764 if (this->editable == EA_RATE) this->production_offset_y = y;
765 first = false;
766 }
767
768 SetDParam(0, i->produced_cargo[j]);
769 SetDParam(1, i->last_month_production[j]);
770 SetDParamStr(2, cargo_suffix[j]);
771 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
772 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
773 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
774 /* Let's put out those buttons.. */
775 if (this->editable == EA_RATE) {
776 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
777 i->production_rate[j] > 0, i->production_rate[j] < 255);
778 }
779 y += FONT_HEIGHT_NORMAL;
780 }
781
782 /* Display production multiplier if editable */
783 if (this->editable == EA_MULTIPLIER) {
784 y += WD_PAR_VSEP_WIDE;
785 this->production_offset_y = y;
786 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
787 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
788 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
789 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
790 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
791 y += FONT_HEIGHT_NORMAL;
792 }
793
794 /* Get the extra message for the GUI */
795 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
796 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
797 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
798 if (callback_res > 0x400) {
799 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
800 } else {
801 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
802 if (message != STR_NULL && message != STR_UNDEFINED) {
803 y += WD_PAR_VSEP_WIDE;
804
805 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
806 /* Use all the available space left from where we stand up to the
807 * end of the window. We ALSO enlarge the window if needed, so we
808 * can 'go' wild with the bottom of the window. */
809 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
810 StopTextRefStackUsage();
811 }
812 }
813 }
814 }
815 return y + WD_FRAMERECT_BOTTOM;
816 }
817
818 virtual void SetStringParameters(int widget) const
819 {
820 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
821 }
822
823 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
824 {
825 if (widget == WID_IV_INFO) size->height = this->info_height;
826 }
827
828 virtual void OnClick(Point pt, int widget, int click_count)
829 {
830 switch (widget) {
831 case WID_IV_INFO: {
832 Industry *i = Industry::Get(this->window_number);
833 InfoLine line = IL_NONE;
834
835 switch (this->editable) {
836 case EA_NONE: break;
837
838 case EA_MULTIPLIER:
839 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
840 break;
841
842 case EA_RATE:
843 if (pt.y >= this->production_offset_y) {
844 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
845 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
846 if (i->produced_cargo[j] == CT_INVALID) continue;
847 row--;
848 if (row < 0) {
849 line = (InfoLine)(IL_RATE1 + j);
850 break;
851 }
852 }
853 }
854 break;
855 }
856 if (line == IL_NONE) return;
857
858 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
859 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
860 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
861 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
862 /* Clicked buttons, decrease or increase production */
863 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
864 switch (this->editable) {
865 case EA_MULTIPLIER:
866 if (button == 1) {
867 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
868 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
869 } else {
870 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
871 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
872 }
873 break;
874
875 case EA_RATE:
876 if (button == 1) {
877 if (i->production_rate[line - IL_RATE1] <= 0) return;
878 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
879 } else {
880 if (i->production_rate[line - IL_RATE1] >= 255) return;
881 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
882 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
883 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
884 }
885 break;
886
887 default: NOT_REACHED();
888 }
889
890 UpdateIndustryProduction(i);
891 this->SetDirty();
892 this->SetTimeout();
893 this->clicked_line = line;
894 this->clicked_button = button;
895 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
896 /* clicked the text */
897 this->editbox_line = line;
898 switch (this->editable) {
899 case EA_MULTIPLIER:
900 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
901 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
902 break;
903
904 case EA_RATE:
905 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
906 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
907 break;
908
909 default: NOT_REACHED();
910 }
911 }
912 break;
913 }
914
915 case WID_IV_GOTO: {
916 Industry *i = Industry::Get(this->window_number);
917 if (_ctrl_pressed) {
918 ShowExtraViewPortWindow(i->location.GetCenterTile());
919 } else {
920 ScrollMainWindowToTile(i->location.GetCenterTile());
921 }
922 break;
923 }
924
925 case WID_IV_DISPLAY: {
926 Industry *i = Industry::Get(this->window_number);
927 ShowIndustryCargoesWindow(i->type);
928 break;
929 }
930 }
931 }
932
933 virtual void OnTimeout()
934 {
935 this->clicked_line = IL_NONE;
936 this->clicked_button = 0;
937 this->SetDirty();
938 }
939
940 virtual void OnResize()
941 {
942 if (this->viewport != NULL) {
943 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
944 nvp->UpdateViewportCoordinates(this);
945
946 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
947 }
948 }
949
950 virtual void OnQueryTextFinished(char *str)
951 {
952 if (StrEmpty(str)) return;
953
954 Industry *i = Industry::Get(this->window_number);
955 uint value = atoi(str);
956 switch (this->editbox_line) {
957 case IL_NONE: NOT_REACHED();
958
959 case IL_MULTIPLIER:
960 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
961 break;
962
963 default:
964 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
965 break;
966 }
967 UpdateIndustryProduction(i);
968 this->SetDirty();
969 }
970
976 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
977 {
978 if (!gui_scope) return;
979 const Industry *i = Industry::Get(this->window_number);
980 if (IsProductionAlterable(i)) {
981 const IndustrySpec *ind = GetIndustrySpec(i->type);
982 this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
983 } else {
984 this->editable = EA_NONE;
985 }
986 }
987
988 virtual bool IsNewGRFInspectable() const
989 {
990 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
991 }
992
993 virtual void ShowNewGRFInspectWindow() const
994 {
995 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
996 }
997 };
998
999 static void UpdateIndustryProduction(Industry *i)
1000 {
1001 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1002 if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
1003
1004 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1005 if (i->produced_cargo[j] != CT_INVALID) {
1006 i->last_month_production[j] = 8 * i->production_rate[j];
1007 }
1008 }
1009 }
1010
1012 static const NWidgetPart _nested_industry_view_widgets[] = {
1013 NWidget(NWID_HORIZONTAL),
1014 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1015 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1016 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1017 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1018 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1019 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1020 EndContainer(),
1021 NWidget(WWT_PANEL, COLOUR_CREAM),
1022 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1023 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
1024 EndContainer(),
1025 EndContainer(),
1026 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1027 EndContainer(),
1028 NWidget(NWID_HORIZONTAL),
1029 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1030 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1031 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1032 EndContainer(),
1033 };
1034
1036 static WindowDesc _industry_view_desc(
1037 WDP_AUTO, "view_industry", 260, 120,
1038 WC_INDUSTRY_VIEW, WC_NONE,
1039 0,
1040 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1041 );
1042
1043 void ShowIndustryViewWindow(int industry)
1044 {
1045 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1046 }
1047
1049 static const NWidgetPart _nested_industry_directory_widgets[] = {
1050 NWidget(NWID_HORIZONTAL),
1051 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1052 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1053 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1054 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1055 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1056 EndContainer(),
1057 NWidget(NWID_HORIZONTAL),
1058 NWidget(NWID_VERTICAL),
1059 NWidget(NWID_HORIZONTAL),
1060 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1061 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1062 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1063 EndContainer(),
1064 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1065 EndContainer(),
1066 NWidget(NWID_VERTICAL),
1067 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1068 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1069 EndContainer(),
1070 EndContainer(),
1071 };
1072
1073 typedef GUIList<const Industry*> GUIIndustryList;
1074
1075
1079 class IndustryDirectoryWindow : public Window {
1080 protected:
1081 /* Runtime saved values */
1082 static Listing last_sorting;
1083 static const Industry *last_industry;
1084
1085 /* Constants for sorting stations */
1086 static const StringID sorter_names[];
1087 static GUIIndustryList::SortFunction * const sorter_funcs[];
1088
1089 GUIIndustryList industries;
1090 Scrollbar *vscroll;
1091
1093 void BuildSortIndustriesList()
1094 {
1095 if (this->industries.NeedRebuild()) {
1096 this->industries.Clear();
1097
1098 const Industry *i;
1099 FOR_ALL_INDUSTRIES(i) {
1100 *this->industries.Append() = i;
1101 }
1102
1103 this->industries.Compact();
1104 this->industries.RebuildDone();
1105 this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
1106 }
1107
1108 if (!this->industries.Sort()) return;
1109 IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
1110 this->SetWidgetDirty(WID_ID_INDUSTRY_LIST); // Set the modified widget dirty
1111 }
1112
1120 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1121 {
1122 assert(id < lengthof(i->produced_cargo));
1123
1124 if (i->produced_cargo[id] == CT_INVALID) return 101;
1125 return ToPercent8(i->last_month_pct_transported[id]);
1126 }
1127
1135 static int GetCargoTransportedSortValue(const Industry *i)
1136 {
1137 int p1 = GetCargoTransportedPercentsIfValid(i, 0);
1138 int p2 = GetCargoTransportedPercentsIfValid(i, 1);
1139
1140 if (p1 > p2) Swap(p1, p2); // lower value has higher priority
1141
1142 return (p1 << 8) + p2;
1143 }
1144
1146 static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
1147 {
1148 static char buf_cache[96];
1149 static char buf[96];
1150
1151 SetDParam(0, (*a)->index);
1152 GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
1153
1154 if (*b != last_industry) {
1155 last_industry = *b;
1156 SetDParam(0, (*b)->index);
1157 GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
1158 }
1159
1160 return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
1161 }
1162
1164 static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
1165 {
1166 int it_a = 0;
1167 while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
1168 int it_b = 0;
1169 while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
1170 int r = it_a - it_b;
1171 return (r == 0) ? IndustryNameSorter(a, b) : r;
1172 }
1173
1175 static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
1176 {
1177 uint prod_a = 0, prod_b = 0;
1178 for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
1179 if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
1180 if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
1181 }
1182 int r = prod_a - prod_b;
1183
1184 return (r == 0) ? IndustryTypeSorter(a, b) : r;
1185 }
1186
1188 static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
1189 {
1190 int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
1191 return (r == 0) ? IndustryNameSorter(a, b) : r;
1192 }
1193
1199 StringID GetIndustryString(const Industry *i) const
1200 {
1201 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1202 byte p = 0;
1203
1204 /* Industry name */
1205 SetDParam(p++, i->index);
1206
1207 static char cargo_suffix[lengthof(i->produced_cargo)][512];
1208 GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1209
1210 /* Industry productions */
1211 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1212 if (i->produced_cargo[j] == CT_INVALID) continue;
1213 SetDParam(p++, i->produced_cargo[j]);
1214 SetDParam(p++, i->last_month_production[j]);
1215 SetDParamStr(p++, cargo_suffix[j]);
1216 }
1217
1218 /* Transported productions */
1219 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1220 if (i->produced_cargo[j] == CT_INVALID) continue;
1221 SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
1222 }
1223
1224 /* Drawing the right string */
1225 switch (p) {
1226 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1227 case 5: return STR_INDUSTRY_DIRECTORY_ITEM;
1228 default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
1229 }
1230 }
1231
1232 public:
1233 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1234 {
1235 this->CreateNestedTree();
1236 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1237
1238 this->industries.SetListing(this->last_sorting);
1239 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1240 this->industries.ForceRebuild();
1241 this->BuildSortIndustriesList();
1242
1243 this->FinishInitNested(0);
1244 }
1245
1246 ~IndustryDirectoryWindow()
1247 {
1248 this->last_sorting = this->industries.GetListing();
1249 }
1250
1251 virtual void SetStringParameters(int widget) const
1252 {
1253 if (widget == WID_ID_DROPDOWN_CRITERIA) SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1254 }
1255
1256 virtual void DrawWidget(const Rect &r, int widget) const
1257 {
1258 switch (widget) {
1259 case WID_ID_DROPDOWN_ORDER:
1260 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1261 break;
1262
1263 case WID_ID_INDUSTRY_LIST: {
1264 int n = 0;
1265 int y = r.top + WD_FRAMERECT_TOP;
1266 if (this->industries.Length() == 0) {
1267 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1268 break;
1269 }
1270 for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
1271 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
1272
1273 y += this->resize.step_height;
1274 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1275 }
1276 break;
1277 }
1278 }
1279 }
1280
1281 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1282 {
1283 switch (widget) {
1284 case WID_ID_DROPDOWN_ORDER: {
1285 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1286 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1287 d.height += padding.height;
1288 *size = maxdim(*size, d);
1289 break;
1290 }
1291
1292 case WID_ID_DROPDOWN_CRITERIA: {
1293 Dimension d = {0, 0};
1294 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1295 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1296 }
1297 d.width += padding.width;
1298 d.height += padding.height;
1299 *size = maxdim(*size, d);
1300 break;
1301 }
1302
1303 case WID_ID_INDUSTRY_LIST: {
1304 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1305 for (uint i = 0; i < this->industries.Length(); i++) {
1306 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1307 }
1308 resize->height = d.height;
1309 d.height *= 5;
1310 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1311 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1312 *size = maxdim(*size, d);
1313 break;
1314 }
1315 }
1316 }
1317
1318
1319 virtual void OnClick(Point pt, int widget, int click_count)
1320 {
1321 switch (widget) {
1322 case WID_ID_DROPDOWN_ORDER:
1323 this->industries.ToggleSortOrder();
1324 this->SetDirty();
1325 break;
1326
1327 case WID_ID_DROPDOWN_CRITERIA:
1328 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1329 break;
1330
1331 case WID_ID_INDUSTRY_LIST: {
1332 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1333 if (p < this->industries.Length()) {
1334 if (_ctrl_pressed) {
1335 ShowExtraViewPortWindow(this->industries[p]->location.tile);
1336 } else {
1337 ScrollMainWindowToTile(this->industries[p]->location.tile);
1338 }
1339 }
1340 break;
1341 }
1342 }
1343 }
1344
1345 virtual void OnDropdownSelect(int widget, int index)
1346 {
1347 if (this->industries.SortType() != index) {
1348 this->industries.SetSortType(index);
1349 this->BuildSortIndustriesList();
1350 }
1351 }
1352
1353 virtual void OnResize()
1354 {
1355 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1356 }
1357
1358 virtual void OnPaint()
1359 {
1360 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1361 this->DrawWidgets();
1362 }
1363
1364 virtual void OnHundredthTick()
1365 {
1366 this->industries.ForceResort();
1367 this->BuildSortIndustriesList();
1368 }
1369
1375 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1376 {
1377 if (data == 0) {
1378 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1379 this->industries.ForceRebuild();
1380 } else {
1381 this->industries.ForceResort();
1382 }
1383 }
1384 };
1385
1386 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1387 const Industry *IndustryDirectoryWindow::last_industry = NULL;
1388
1389 /* Available station sorting functions. */
1390 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1391 &IndustryNameSorter,
1392 &IndustryTypeSorter,
1393 &IndustryProductionSorter,
1394 &IndustryTransportedCargoSorter
1395 };
1396
1397 /* Names of the sorting functions */
1398 const StringID IndustryDirectoryWindow::sorter_names[] = {
1399 STR_SORT_BY_NAME,
1400 STR_SORT_BY_TYPE,
1401 STR_SORT_BY_PRODUCTION,
1402 STR_SORT_BY_TRANSPORTED,
1403 INVALID_STRING_ID
1404 };
1405
1406
1408 static WindowDesc _industry_directory_desc(
1409 WDP_AUTO, "list_industries", 428, 190,
1410 WC_INDUSTRY_DIRECTORY, WC_NONE,
1411 0,
1412 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1413 );
1414
1415 void ShowIndustryDirectory()
1416 {
1417 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1418 }
1419
1421 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1422 NWidget(NWID_HORIZONTAL),
1423 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1424 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1425 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1426 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1427 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1428 EndContainer(),
1429 NWidget(NWID_HORIZONTAL),
1430 NWidget(NWID_VERTICAL),
1431 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1432 NWidget(NWID_HORIZONTAL),
1433 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1434 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1435 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1436 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1437 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1438 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1439 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1440 EndContainer(),
1441 EndContainer(),
1442 NWidget(NWID_VERTICAL),
1443 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1444 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1445 EndContainer(),
1446 EndContainer(),
1447 };
1448
1450 static WindowDesc _industry_cargoes_desc(
1451 WDP_AUTO, "industry_cargoes", 300, 210,
1452 WC_INDUSTRY_CARGOES, WC_NONE,
1453 0,
1454 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1455 );
1456
1458 enum CargoesFieldType {
1459 CFT_EMPTY,
1460 CFT_SMALL_EMPTY,
1461 CFT_INDUSTRY,
1462 CFT_CARGO,
1463 CFT_CARGO_LABEL,
1464 CFT_HEADER,
1465 };
1466
1467 static const uint MAX_CARGOES = 3;
1468
1470 struct CargoesField {
1471 static const int VERT_INTER_INDUSTRY_SPACE;
1472 static const int HOR_CARGO_BORDER_SPACE;
1473 static const int CARGO_STUB_WIDTH;
1474 static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
1475 static const int CARGO_FIELD_WIDTH;
1476 static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
1477 static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
1478
1479 static const int INDUSTRY_LINE_COLOUR;
1480 static const int CARGO_LINE_COLOUR;
1481
1482 static int small_height, normal_height;
1483 static int industry_width;
1484
1485 CargoesFieldType type;
1486 union {
1487 struct {
1488 IndustryType ind_type;
1489 CargoID other_produced[MAX_CARGOES];
1490 CargoID other_accepted[MAX_CARGOES];
1491 } industry;
1492 struct {
1493 CargoID vertical_cargoes[MAX_CARGOES];
1494 byte num_cargoes;
1495 CargoID supp_cargoes[MAX_CARGOES];
1496 byte top_end;
1497 CargoID cust_cargoes[MAX_CARGOES];
1498 byte bottom_end;
1499 } cargo;
1500 struct {
1501 CargoID cargoes[MAX_CARGOES];
1502 bool left_align;
1503 } cargo_label;
1504 StringID header;
1505 } u; // Data for each type.
1506
1511 void MakeEmpty(CargoesFieldType type)
1512 {
1513 this->type = type;
1514 }
1515
1521 void MakeIndustry(IndustryType ind_type)
1522 {
1523 this->type = CFT_INDUSTRY;
1524 this->u.industry.ind_type = ind_type;
1525 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1526 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1527 }
1528
1535 int ConnectCargo(CargoID cargo, bool producer)
1536 {
1537 assert(this->type == CFT_CARGO);
1538 if (cargo == INVALID_CARGO) return -1;
1539
1540 /* Find the vertical cargo column carrying the cargo. */
1541 int column = -1;
1542 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1543 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1544 column = i;
1545 break;
1546 }
1547 }
1548 if (column < 0) return -1;
1549
1550 if (producer) {
1551 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1552 this->u.cargo.supp_cargoes[column] = column;
1553 } else {
1554 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1555 this->u.cargo.cust_cargoes[column] = column;
1556 }
1557 return column;
1558 }
1559
1564 bool HasConnection()
1565 {
1566 assert(this->type == CFT_CARGO);
1567
1568 for (uint i = 0; i < MAX_CARGOES; i++) {
1569 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
1570 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
1571 }
1572 return false;
1573 }
1574
1584 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
1585 {
1586 this->type = CFT_CARGO;
1587 uint i;
1588 uint num = 0;
1589 for (i = 0; i < MAX_CARGOES && i < length; i++) {
1590 if (cargoes[i] != INVALID_CARGO) {
1591 this->u.cargo.vertical_cargoes[num] = cargoes[i];
1592 num++;
1593 }
1594 }
1595 this->u.cargo.num_cargoes = (count < 0) ? num : count;
1596 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
1597 this->u.cargo.top_end = top_end;
1598 this->u.cargo.bottom_end = bottom_end;
1599 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
1600 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
1601 }
1602
1609 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
1610 {
1611 this->type = CFT_CARGO_LABEL;
1612 uint i;
1613 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
1614 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
1615 this->u.cargo_label.left_align = left_align;
1616 }
1617
1622 void MakeHeader(StringID textid)
1623 {
1624 this->type = CFT_HEADER;
1625 this->u.header = textid;
1626 }
1627
1633 int GetCargoBase(int xpos) const
1634 {
1635 assert(this->type == CFT_CARGO);
1636
1637 switch (this->u.cargo.num_cargoes) {
1638 case 0: return xpos + CARGO_FIELD_WIDTH / 2;
1639 case 1: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH / 2;
1640 case 2: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE / 2;
1641 case 3: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE - HOR_CARGO_WIDTH / 2;
1642 default: NOT_REACHED();
1643 }
1644 }
1645
1651 void Draw(int xpos, int ypos) const
1652 {
1653 switch (this->type) {
1654 case CFT_EMPTY:
1655 case CFT_SMALL_EMPTY:
1656 break;
1657
1658 case CFT_HEADER:
1659 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
1660 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
1661 break;
1662
1663 case CFT_INDUSTRY: {
1664 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
1665 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
1666 int xpos2 = xpos + industry_width - 1;
1667 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
1668 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
1669 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1670 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
1671 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
1672 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1673 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
1674 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
1675
1676 /* Draw the industry legend. */
1677 int blob_left, blob_right;
1678 if (_current_text_dir == TD_RTL) {
1679 blob_right = xpos2 - BLOB_DISTANCE;
1680 blob_left = blob_right - BLOB_WIDTH;
1681 } else {
1682 blob_left = xpos + BLOB_DISTANCE;
1683 blob_right = blob_left + BLOB_WIDTH;
1684 }
1685 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
1686 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
1687 } else {
1688 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
1689 }
1690
1691 /* Draw the other_produced/other_accepted cargoes. */
1692 const CargoID *other_right, *other_left;
1693 if (_current_text_dir == TD_RTL) {
1694 other_right = this->u.industry.other_accepted;
1695 other_left = this->u.industry.other_produced;
1696 } else {
1697 other_right = this->u.industry.other_produced;
1698 other_left = this->u.industry.other_accepted;
1699 }
1700 ypos1 += VERT_CARGO_EDGE;
1701 for (uint i = 0; i < MAX_CARGOES; i++) {
1702 if (other_right[i] != INVALID_CARGO) {
1703 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
1704 int xp = xpos + industry_width + CARGO_STUB_WIDTH;
1705 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
1706 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1707 }
1708 if (other_left[i] != INVALID_CARGO) {
1709 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
1710 int xp = xpos - CARGO_STUB_WIDTH;
1711 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
1712 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1713 }
1714 ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1715 }
1716 break;
1717 }
1718
1719 case CFT_CARGO: {
1720 int cargo_base = this->GetCargoBase(xpos);
1721 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
1722 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
1723 int colpos = cargo_base;
1724 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1725 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
1726 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
1727 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1728 colpos++;
1729 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
1730 GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
1731 colpos += HOR_CARGO_WIDTH - 2;
1732 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
1733 colpos += 1 + HOR_CARGO_SPACE;
1734 }
1735
1736 const CargoID *hor_left, *hor_right;
1737 if (_current_text_dir == TD_RTL) {
1738 hor_left = this->u.cargo.cust_cargoes;
1739 hor_right = this->u.cargo.supp_cargoes;
1740 } else {
1741 hor_left = this->u.cargo.supp_cargoes;
1742 hor_right = this->u.cargo.cust_cargoes;
1743 }
1744 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
1745 for (uint i = 0; i < MAX_CARGOES; i++) {
1746 if (hor_left[i] != INVALID_CARGO) {
1747 int col = hor_left[i];
1748 int dx = 0;
1749 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1750 for (; col > 0; col--) {
1751 int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
1752 DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
1753 dx = 1;
1754 }
1755 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
1756 }
1757 if (hor_right[i] != INVALID_CARGO) {
1758 int col = hor_right[i];
1759 int dx = 0;
1760 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
1761 for (; col < this->u.cargo.num_cargoes - 1; col++) {
1762 int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
1763 DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
1764 dx = 1;
1765 }
1766 DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CARGO_FIELD_WIDTH - 1, ypos, csp);
1767 }
1768 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1769 }
1770 break;
1771 }
1772
1773 case CFT_CARGO_LABEL:
1774 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
1775 for (uint i = 0; i < MAX_CARGOES; i++) {
1776 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
1777 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
1778 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
1779 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
1780 }
1781 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1782 }
1783 break;
1784
1785 default:
1786 NOT_REACHED();
1787 }
1788 }
1789
1797 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
1798 {
1799 assert(this->type == CFT_CARGO);
1800
1801 /* Vertical matching. */
1802 int cpos = this->GetCargoBase(0);
1803 uint col;
1804 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
1805 if (pt.x < cpos) break;
1806 if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
1807 cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
1808 }
1809 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
1810
1811 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
1812 uint row;
1813 for (row = 0; row < MAX_CARGOES; row++) {
1814 if (pt.y < vpos) return INVALID_CARGO;
1815 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
1816 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1817 }
1818 if (row == MAX_CARGOES) return INVALID_CARGO;
1819
1820 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
1821 if (col == 0) {
1822 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
1823 if (left != NULL) {
1824 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
1825 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
1826 }
1827 return INVALID_CARGO;
1828 }
1829 if (col == this->u.cargo.num_cargoes) {
1830 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
1831 if (right != NULL) {
1832 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
1833 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
1834 }
1835 return INVALID_CARGO;
1836 }
1837 if (row >= col) {
1838 /* Clicked somewhere in-between vertical cargo connection.
1839 * Since the horizontal connection is made in the same order as the vertical list, the above condition
1840 * ensures we are left-below the main diagonal, thus at the supplying side.
1841 */
1842 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
1843 } else {
1844 /* Clicked at a customer connection. */
1845 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
1846 }
1847 }
1848
1854 CargoID CargoLabelClickedAt(Point pt) const
1855 {
1856 assert(this->type == CFT_CARGO_LABEL);
1857
1858 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
1859 uint row;
1860 for (row = 0; row < MAX_CARGOES; row++) {
1861 if (pt.y < vpos) return INVALID_CARGO;
1862 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
1863 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
1864 }
1865 if (row == MAX_CARGOES) return INVALID_CARGO;
1866 return this->u.cargo_label.cargoes[row];
1867 }
1868
1869 private:
1877 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
1878 {
1879 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
1880 GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
1881 GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
1882 }
1883 };
1884
1885 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
1886 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
1887
1888 int CargoesField::small_height;
1889 int CargoesField::normal_height;
1890 int CargoesField::industry_width;
1891 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6;
1892
1893 const int CargoesField::HOR_CARGO_BORDER_SPACE = 15;
1894 const int CargoesField::CARGO_STUB_WIDTH = 10;
1895 const int CargoesField::HOR_CARGO_WIDTH = 15;
1896 const int CargoesField::HOR_CARGO_SPACE = 5;
1897 const int CargoesField::VERT_CARGO_EDGE = 4;
1898 const int CargoesField::VERT_CARGO_SPACE = 4;
1899
1900 const int CargoesField::BLOB_DISTANCE = 5;
1901 const int CargoesField::BLOB_WIDTH = 12;
1902 const int CargoesField::BLOB_HEIGHT = 9;
1903
1905 const int CargoesField::CARGO_FIELD_WIDTH = HOR_CARGO_BORDER_SPACE * 2 + HOR_CARGO_WIDTH * MAX_CARGOES + HOR_CARGO_SPACE * (MAX_CARGOES - 1);
1906
1907 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW;
1908 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW;
1909
1911 struct CargoesRow {
1912 CargoesField columns[5];
1913
1918 void ConnectIndustryProduced(int column)
1919 {
1920 CargoesField *ind_fld = this->columns + column;
1921 CargoesField *cargo_fld = this->columns + column + 1;
1922 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
1923
1924 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1925
1926 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1927 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
1928 int other_count = 0;
1929
1930 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
1931 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
1932 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
1933 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
1934 }
1935
1936 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
1937 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
1938 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
1939 }
1940 } else {
1941 /* Houses only display what is demanded. */
1942 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
1943 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
1944 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
1945 }
1946 }
1947 }
1948
1954 void MakeCargoLabel(int column, bool accepting)
1955 {
1956 CargoID cargoes[MAX_CARGOES];
1957 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
1958
1959 CargoesField *label_fld = this->columns + column;
1960 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
1961
1962 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
1963 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
1964 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
1965 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
1966 }
1967 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
1968 }
1969
1970
1975 void ConnectIndustryAccepted(int column)
1976 {
1977 CargoesField *ind_fld = this->columns + column;
1978 CargoesField *cargo_fld = this->columns + column - 1;
1979 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
1980
1981 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1982
1983 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
1984 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
1985 int other_count = 0;
1986
1987 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
1988 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
1989 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
1990 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
1991 }
1992
1993 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
1994 for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
1995 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
1996 }
1997 } else {
1998 /* Houses only display what is demanded. */
1999 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2000 for (uint h = 0; h < NUM_HOUSES; h++) {
2001 HouseSpec *hs = HouseSpec::Get(h);
2002 if (!hs->enabled) continue;
2003
2004 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2005 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2006 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2007 goto next_cargo;
2008 }
2009 }
2010 }
2011 next_cargo: ;
2012 }
2013 }
2014 }
2015 };
2016
2017
2045 struct IndustryCargoesWindow : public Window {
2046 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2047
2048 typedef SmallVector<CargoesRow, 4> Fields;
2049
2050 Fields fields;
2051 uint ind_cargo;
2052 Dimension cargo_textsize;
2053 Dimension ind_textsize;
2054 Scrollbar *vscroll;
2055
2056 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2057 {
2058 this->OnInit();
2059 this->CreateNestedTree();
2060 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2061 this->FinishInitNested(0);
2062 this->OnInvalidateData(id);
2063 }
2064
2065 virtual void OnInit()
2066 {
2067 /* Initialize static CargoesField size variables. */
2068 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2069 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2070 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2071 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2072 CargoesField::small_height = d.height;
2073
2074 /* Decide about the size of the box holding the text of an industry type. */
2075 this->ind_textsize.width = 0;
2076 this->ind_textsize.height = 0;
2077 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2078 const IndustrySpec *indsp = GetIndustrySpec(it);
2079 if (!indsp->enabled) continue;
2080 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2081 }
2082 d.width = max(d.width, this->ind_textsize.width);
2083 d.height = this->ind_textsize.height;
2084 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2085
2086 /* Compute max size of the cargo texts. */
2087 this->cargo_textsize.width = 0;
2088 this->cargo_textsize.height = 0;
2089 for (uint i = 0; i < NUM_CARGO; i++) {
2090 const CargoSpec *csp = CargoSpec::Get(i);
2091 if (!csp->IsValid()) continue;
2092 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2093 }
2094 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2095 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2096
2097 d.width += 2 * HOR_TEXT_PADDING;
2098 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2099 uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + MAX_CARGOES * FONT_HEIGHT_NORMAL + (MAX_CARGOES - 1) * CargoesField::VERT_CARGO_SPACE;
2100 d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2101
2102 CargoesField::industry_width = d.width;
2103 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2104 }
2105
2106 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2107 {
2108 switch (widget) {
2109 case WID_IC_PANEL:
2110 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::CARGO_FIELD_WIDTH * 2 + WD_FRAMETEXT_RIGHT;
2111 break;
2112
2113 case WID_IC_IND_DROPDOWN:
2114 size->width = max(size->width, this->ind_textsize.width + padding.width);
2115 break;
2116
2117 case WID_IC_CARGO_DROPDOWN:
2118 size->width = max(size->width, this->cargo_textsize.width + padding.width);
2119 break;
2120 }
2121 }
2122
2123
2124 CargoesFieldType type;
2125 virtual void SetStringParameters (int widget) const
2126 {
2127 if (widget != WID_IC_CAPTION) return;
2128
2129 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2130 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2131 SetDParam(0, indsp->name);
2132 } else {
2133 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2134 SetDParam(0, csp->name);
2135 }
2136 }
2137
2146 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2147 {
2148 while (length1 > 0) {
2149 if (*cargoes1 != INVALID_CARGO) {
2150 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2151 }
2152 cargoes1++;
2153 length1--;
2154 }
2155 return false;
2156 }
2157
2164 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2165 {
2166 for (uint i = 0; i < length; i++) {
2167 if (cargoes[i] == INVALID_CARGO) continue;
2168 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2169 }
2170 return false;
2171 }
2172
2179 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2180 {
2181 HouseZones climate_mask;
2182 switch (_settings_game.game_creation.landscape) {
2183 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2184 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2185 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2186 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2187 default: NOT_REACHED();
2188 }
2189 for (uint i = 0; i < length; i++) {
2190 if (cargoes[i] == INVALID_CARGO) continue;
2191
2192 for (uint h = 0; h < NUM_HOUSES; h++) {
2193 HouseSpec *hs = HouseSpec::Get(h);
2194 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2195
2196 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2197 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2198 }
2199 }
2200 }
2201 return false;
2202 }
2203
2210 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2211 {
2212 int count = 0;
2213 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2214 const IndustrySpec *indsp = GetIndustrySpec(it);
2215 if (!indsp->enabled) continue;
2216
2217 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2218 }
2219 return count;
2220 }
2221
2228 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2229 {
2230 int count = 0;
2231 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2232 const IndustrySpec *indsp = GetIndustrySpec(it);
2233 if (!indsp->enabled) continue;
2234
2235 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2236 }
2237 return count;
2238 }
2239
2246 void ShortenCargoColumn(int column, int top, int bottom)
2247 {
2248 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2249 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2250 top++;
2251 }
2252 this->fields[top].columns[column].u.cargo.top_end = true;
2253
2254 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2255 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2256 bottom--;
2257 }
2258 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2259 }
2260
2267 void PlaceIndustry(int row, int col, IndustryType it)
2268 {
2269 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2270 this->fields[row].columns[col].MakeIndustry(it);
2271 if (col == 0) {
2272 this->fields[row].ConnectIndustryProduced(col);
2273 } else {
2274 this->fields[row].ConnectIndustryAccepted(col);
2275 }
2276 }
2277
2281 void NotifySmallmap()
2282 {
2283 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2284
2285 /* Only notify the smallmap window if it exists. In particular, do not
2286 * bring it to the front to prevent messing up any nice layout of the user. */
2287 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2288 }
2289
2294 void ComputeIndustryDisplay(IndustryType it)
2295 {
2296 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2297 this->ind_cargo = it;
2298 _displayed_industries = 1ULL << it;
2299
2300 this->fields.Clear();
2301 CargoesRow *row = this->fields.Append();
2302 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2303 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2304 row->columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2305 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2306 row->columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2307
2308 const IndustrySpec *central_sp = GetIndustrySpec(it);
2309 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2310 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2311 /* Make a field consisting of two cargo columns. */
2312 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2313 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2314 int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
2315 for (int i = 0; i < num_indrows; i++) {
2316 CargoesRow *row = this->fields.Append();
2317 row->columns[0].MakeEmpty(CFT_EMPTY);
2318 row->columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2319 row->columns[2].MakeEmpty(CFT_EMPTY);
2320 row->columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2321 row->columns[4].MakeEmpty(CFT_EMPTY);
2322 }
2323 /* Add central industry. */
2324 int central_row = 1 + num_indrows / 2;
2325 this->fields[central_row].columns[2].MakeIndustry(it);
2326 this->fields[central_row].ConnectIndustryProduced(2);
2327 this->fields[central_row].ConnectIndustryAccepted(2);
2328
2329 /* Add cargo labels. */
2330 this->fields[central_row - 1].MakeCargoLabel(2, true);
2331 this->fields[central_row + 1].MakeCargoLabel(2, false);
2332
2333 /* Add suppliers and customers of the 'it' industry. */
2334 int supp_count = 0;
2335 int cust_count = 0;
2336 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2337 const IndustrySpec *indsp = GetIndustrySpec(it);
2338 if (!indsp->enabled) continue;
2339
2340 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2341 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2342 SetBit(_displayed_industries, it);
2343 supp_count++;
2344 }
2345 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2346 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2347 SetBit(_displayed_industries, it);
2348 cust_count++;
2349 }
2350 }
2351 if (houses_supply) {
2352 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2353 supp_count++;
2354 }
2355 if (houses_accept) {
2356 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2357 cust_count++;
2358 }
2359
2360 this->ShortenCargoColumn(1, 1, num_indrows);
2361 this->ShortenCargoColumn(3, 1, num_indrows);
2362 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2363 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2364 this->SetDirty();
2365 this->NotifySmallmap();
2366 }
2367
2372 void ComputeCargoDisplay(CargoID cid)
2373 {
2374 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2375 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2376 _displayed_industries = 0;
2377
2378 this->fields.Clear();
2379 CargoesRow *row = this->fields.Append();
2380 row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2381 row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2382 row->columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2383 row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2384 row->columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2385
2386 bool houses_supply = HousesCanSupply(&cid, 1);
2387 bool houses_accept = HousesCanAccept(&cid, 1);
2388 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2389 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2390 int num_indrows = max(num_supp, num_cust);
2391 for (int i = 0; i < num_indrows; i++) {
2392 CargoesRow *row = this->fields.Append();
2393 row->columns[0].MakeEmpty(CFT_EMPTY);
2394 row->columns[1].MakeCargo(&cid, 1);
2395 row->columns[2].MakeEmpty(CFT_EMPTY);
2396 row->columns[3].MakeEmpty(CFT_EMPTY);
2397 row->columns[4].MakeEmpty(CFT_EMPTY);
2398 }
2399
2400 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2401
2402 /* Add suppliers and customers of the cargo. */
2403 int supp_count = 0;
2404 int cust_count = 0;
2405 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2406 const IndustrySpec *indsp = GetIndustrySpec(it);
2407 if (!indsp->enabled) continue;
2408
2409 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2410 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2411 SetBit(_displayed_industries, it);
2412 supp_count++;
2413 }
2414 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2415 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2416 SetBit(_displayed_industries, it);
2417 cust_count++;
2418 }
2419 }
2420 if (houses_supply) {
2421 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2422 supp_count++;
2423 }
2424 if (houses_accept) {
2425 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2426 cust_count++;
2427 }
2428
2429 this->ShortenCargoColumn(1, 1, num_indrows);
2430 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2431 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2432 this->SetDirty();
2433 this->NotifySmallmap();
2434 }
2435
2443 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2444 {
2445 if (!gui_scope) return;
2446 if (data == NUM_INDUSTRYTYPES) {
2447 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2448 this->RaiseWidget(WID_IC_NOTIFY);
2449 this->SetWidgetDirty(WID_IC_NOTIFY);
2450 }
2451 return;
2452 }
2453
2454 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2455 this->ComputeIndustryDisplay(data);
2456 }
2457
2458 virtual void DrawWidget(const Rect &r, int widget) const
2459 {
2460 if (widget != WID_IC_PANEL) return;
2461
2462 DrawPixelInfo tmp_dpi, *old_dpi;
2463 int width = r.right - r.left + 1;
2464 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2465 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2466 old_dpi = _cur_dpi;
2467 _cur_dpi = &tmp_dpi;
2468
2469 int left_pos = WD_FRAMERECT_LEFT;
2470 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
2471 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2472
2473 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2474 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2475 for (uint i = 0; i < this->fields.Length(); i++) {
2476 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2477 if (vpos + row_height >= 0) {
2478 int xpos = left_pos;
2479 int col, dir;
2480 if (_current_text_dir == TD_RTL) {
2481 col = last_column;
2482 dir = -1;
2483 } else {
2484 col = 0;
2485 dir = 1;
2486 }
2487 while (col >= 0 && col <= last_column) {
2488 this->fields[i].columns[col].Draw(xpos, vpos);
2489 xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2490 col += dir;
2491 }
2492 }
2493 vpos += row_height;
2494 if (vpos >= height) break;
2495 }
2496
2497 _cur_dpi = old_dpi;
2498 }
2499
2507 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2508 {
2509 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2510 pt.x -= nw->pos_x;
2511 pt.y -= nw->pos_y;
2512
2513 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2514 if (pt.y < vpos) return false;
2515
2516 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2517 if (row + 1 >= (int)this->fields.Length()) return false;
2518 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2519 row++; // rebase row to match index of this->fields.
2520
2521 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
2522 if (pt.x < xpos) return false;
2523 int column;
2524 for (column = 0; column <= 5; column++) {
2525 int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
2526 if (pt.x < xpos + width) break;
2527 xpos += width;
2528 }
2529 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2530 if (column > num_columns) return false;
2531 xpos = pt.x - xpos;
2532
2533 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2534 fieldxy->y = row;
2535 xy->y = vpos;
2536 if (_current_text_dir == TD_RTL) {
2537 fieldxy->x = num_columns - column;
2538 xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
2539 } else {
2540 fieldxy->x = column;
2541 xy->x = xpos;
2542 }
2543 return true;
2544 }
2545
2546 virtual void OnClick(Point pt, int widget, int click_count)
2547 {
2548 switch (widget) {
2549 case WID_IC_PANEL: {
2550 Point fieldxy, xy;
2551 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2552
2553 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2554 switch (fld->type) {
2555 case CFT_INDUSTRY:
2556 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
2557 break;
2558
2559 case CFT_CARGO: {
2560 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2561 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2562 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
2563 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2564 break;
2565 }
2566
2567 case CFT_CARGO_LABEL: {
2568 CargoID cid = fld->CargoLabelClickedAt(xy);
2569 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2570 break;
2571 }
2572
2573 default:
2574 break;
2575 }
2576 break;
2577 }
2578
2579 case WID_IC_NOTIFY:
2580 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
2581 this->SetWidgetDirty(WID_IC_NOTIFY);
2582 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
2583
2584 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2585 if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
2586 this->NotifySmallmap();
2587 }
2588 break;
2589
2590 case WID_IC_CARGO_DROPDOWN: {
2591 DropDownList *lst = new DropDownList;
2592 const CargoSpec *cs;
2593 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
2594 *lst->Append() = new DropDownListStringItem(cs->name, cs->Index(), false);
2595 }
2596 if (lst->Length() == 0) {
2597 delete lst;
2598 break;
2599 }
2600 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
2601 ShowDropDownList(this, lst, selected, WID_IC_CARGO_DROPDOWN, 0, true);
2602 break;
2603 }
2604
2605 case WID_IC_IND_DROPDOWN: {
2606 DropDownList *lst = new DropDownList;
2607 for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
2608 IndustryType ind = _sorted_industry_types[i];
2609 const IndustrySpec *indsp = GetIndustrySpec(ind);
2610 if (!indsp->enabled) continue;
2611 *lst->Append() = new DropDownListStringItem(indsp->name, ind, false);
2612 }
2613 if (lst->Length() == 0) {
2614 delete lst;
2615 break;
2616 }
2617 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
2618 ShowDropDownList(this, lst, selected, WID_IC_IND_DROPDOWN, 0, true);
2619 break;
2620 }
2621 }
2622 }
2623
2624 virtual void OnDropdownSelect(int widget, int index)
2625 {
2626 if (index < 0) return;
2627
2628 switch (widget) {
2629 case WID_IC_CARGO_DROPDOWN:
2630 this->ComputeCargoDisplay(index);
2631 break;
2632
2633 case WID_IC_IND_DROPDOWN:
2634 this->ComputeIndustryDisplay(index);
2635 break;
2636 }
2637 }
2638
2639 virtual void OnHover(Point pt, int widget)
2640 {
2641 if (widget != WID_IC_PANEL) return;
2642
2643 Point fieldxy, xy;
2644 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2645
2646 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2647 CargoID cid = INVALID_CARGO;
2648 switch (fld->type) {
2649 case CFT_CARGO: {
2650 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
2651 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
2652 cid = fld->CargoClickedAt(lft, rgt, xy);
2653 break;
2654 }
2655
2656 case CFT_CARGO_LABEL: {
2657 cid = fld->CargoLabelClickedAt(xy);
2658 break;
2659 }
2660
2661 case CFT_INDUSTRY:
2662 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
2663 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, TCC_HOVER);
2664 }
2665 return;
2666
2667 default:
2668 break;
2669 }
2670 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
2671 const CargoSpec *csp = CargoSpec::Get(cid);
2672 uint64 params[5];
2673 params[0] = csp->name;
2674 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, TCC_HOVER);
2675 }
2676 }
2677
2678 virtual void OnResize()
2679 {
2680 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL);
2681 }
2682 };
2683
2684 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5;
2685 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5;
2686
2691 static void ShowIndustryCargoesWindow(IndustryType id)
2692 {
2693 if (id >= NUM_INDUSTRYTYPES) {
2694 for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
2695 const IndustrySpec *indsp = GetIndustrySpec(_sorted_industry_types[i]);
2696 if (indsp->enabled) {
2697 id = _sorted_industry_types[i];
2698 break;
2699 }
2700 }
2701 if (id >= NUM_INDUSTRYTYPES) return;
2702 }
2703
2704 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
2705 if (w != NULL) {
2706 w->InvalidateData(id);
2707 return;
2708 }
2709 new IndustryCargoesWindow(id);
2710 }
2711
2713 void ShowIndustryCargoesWindow()
2714 {
2715 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);
2716 }