OpenTTD Source 20260512-master-g20b387b91f
linkgraph_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11#include "../window_gui.h"
12#include "../window_func.h"
13#include "../company_base.h"
14#include "../company_gui.h"
17#include "../viewport_func.h"
18#include "../zoom_func.h"
19#include "../smallmap_gui.h"
22#include "../strings_func.h"
23#include "linkgraph_gui.h"
24
25#include "table/strings.h"
26
27#include "../safeguards.h"
28
34{
35 PixelColour{0x0f}, PixelColour{0xd1}, PixelColour{0xd0}, PixelColour{0x57},
36 PixelColour{0x55}, PixelColour{0x53}, PixelColour{0xbf}, PixelColour{0xbd},
37 PixelColour{0xba}, PixelColour{0xb9}, PixelColour{0xb7}, PixelColour{0xb5}
38},
39{
40 PixelColour{0x0f}, PixelColour{0xd1}, PixelColour{0xd0}, PixelColour{0x57},
41 PixelColour{0x55}, PixelColour{0x53}, PixelColour{0x96}, PixelColour{0x95},
42 PixelColour{0x94}, PixelColour{0x93}, PixelColour{0x92}, PixelColour{0x91}
43},
44{
45 PixelColour{0x0f}, PixelColour{0x0b}, PixelColour{0x09}, PixelColour{0x07},
46 PixelColour{0x05}, PixelColour{0x03}, PixelColour{0xbf}, PixelColour{0xbd},
47 PixelColour{0xba}, PixelColour{0xb9}, PixelColour{0xb7}, PixelColour{0xb5}
48},
49{
50 PixelColour{0x0f}, PixelColour{0x0b}, PixelColour{0x0a}, PixelColour{0x09},
51 PixelColour{0x08}, PixelColour{0x07}, PixelColour{0x06}, PixelColour{0x05},
52 PixelColour{0x04}, PixelColour{0x03}, PixelColour{0x02}, PixelColour{0x01}
53}
54};
55
61{
62 const NWidgetBase *wi = this->window->GetWidget<NWidgetBase>(this->widget_id);
63 dpi->left = dpi->top = 0;
64 dpi->width = wi->current_x;
65 dpi->height = wi->current_y;
66}
67
72{
73 this->cached_links.clear();
74 this->cached_stations.clear();
75 if (this->company_mask.None()) return;
76
77 DrawPixelInfo dpi;
78 this->GetWidgetDpi(&dpi);
79
80 for (const Station *sta : Station::Iterate()) {
81 if (sta->rect.IsEmpty()) continue;
82
83 Point pta = this->GetStationMiddle(sta);
84
85 StationID from = sta->index;
86 StationLinkMap &seen_links = this->cached_links[from];
87
88 uint supply = 0;
89 for (CargoType cargo : this->cargo_mask) {
90 if (!CargoSpec::Get(cargo)->IsValid()) continue;
91 if (!LinkGraph::IsValidID(sta->goods[cargo].link_graph)) continue;
92 const LinkGraph &lg = *LinkGraph::Get(sta->goods[cargo].link_graph);
93
94 ConstNode &from_node = lg[sta->goods[cargo].node];
95 supply += lg.Monthly(from_node.supply);
96 for (const Edge &edge : from_node.edges) {
97 StationID to = lg[edge.dest_node].station;
98 assert(from != to);
99 if (!Station::IsValidID(to) || seen_links.find(to) != seen_links.end()) {
100 continue;
101 }
102 const Station *stb = Station::Get(to);
103 assert(sta != stb);
104
105 /* Show links between stations of selected companies or "neutral" ones like oilrigs. */
106 if (stb->owner != OWNER_NONE && sta->owner != OWNER_NONE && !this->company_mask.Test(stb->owner)) continue;
107 if (stb->rect.IsEmpty()) continue;
108
109 if (!this->IsLinkVisible(pta, this->GetStationMiddle(stb), &dpi)) continue;
110
111 this->AddLinks(sta, stb);
112 seen_links[to]; // make sure it is created and marked as seen
113 }
114 }
115 if (this->IsPointVisible(pta, &dpi)) {
116 this->cached_stations.emplace_back(from, supply);
117 }
118 }
119}
120
128inline bool LinkGraphOverlay::IsPointVisible(Point pt, const DrawPixelInfo *dpi, int padding) const
129{
130 return pt.x > dpi->left - padding && pt.y > dpi->top - padding &&
131 pt.x < dpi->left + dpi->width + padding &&
132 pt.y < dpi->top + dpi->height + padding;
133}
134
143inline bool LinkGraphOverlay::IsLinkVisible(Point pta, Point ptb, const DrawPixelInfo *dpi, int padding) const
144{
145 const int left = dpi->left - padding;
146 const int right = dpi->left + dpi->width + padding;
147 const int top = dpi->top - padding;
148 const int bottom = dpi->top + dpi->height + padding;
149
150 /*
151 * This method is an implementation of the Cohen-Sutherland line-clipping algorithm.
152 * See: https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm
153 */
154
155 const uint8_t INSIDE = 0; // 0000
156 const uint8_t LEFT = 1; // 0001
157 const uint8_t RIGHT = 2; // 0010
158 const uint8_t BOTTOM = 4; // 0100
159 const uint8_t TOP = 8; // 1000
160
161 int x0 = pta.x;
162 int y0 = pta.y;
163 int x1 = ptb.x;
164 int y1 = ptb.y;
165
166 auto out_code = [&](int x, int y) -> uint8_t {
167 uint8_t out = INSIDE;
168 if (x < left) {
169 out |= LEFT;
170 } else if (x > right) {
171 out |= RIGHT;
172 }
173 if (y < top) {
174 out |= TOP;
175 } else if (y > bottom) {
176 out |= BOTTOM;
177 }
178 return out;
179 };
180
181 uint8_t c0 = out_code(x0, y0);
182 uint8_t c1 = out_code(x1, y1);
183
184 while (true) {
185 if (c0 == 0 || c1 == 0) return true;
186 if ((c0 & c1) != 0) return false;
187
188 if (c0 & TOP) { // point 0 is above the clip window
189 x0 = x0 + (int)(((int64_t) (x1 - x0)) * ((int64_t) (top - y0)) / ((int64_t) (y1 - y0)));
190 y0 = top;
191 } else if (c0 & BOTTOM) { // point 0 is below the clip window
192 x0 = x0 + (int)(((int64_t) (x1 - x0)) * ((int64_t) (bottom - y0)) / ((int64_t) (y1 - y0)));
193 y0 = bottom;
194 } else if (c0 & RIGHT) { // point 0 is to the right of clip window
195 y0 = y0 + (int)(((int64_t) (y1 - y0)) * ((int64_t) (right - x0)) / ((int64_t) (x1 - x0)));
196 x0 = right;
197 } else if (c0 & LEFT) { // point 0 is to the left of clip window
198 y0 = y0 + (int)(((int64_t) (y1 - y0)) * ((int64_t) (left - x0)) / ((int64_t) (x1 - x0)));
199 x0 = left;
200 }
201
202 c0 = out_code(x0, y0);
203 }
204
205 NOT_REACHED();
206}
207
213void LinkGraphOverlay::AddLinks(const Station *from, const Station *to)
214{
215 for (CargoType cargo : this->cargo_mask) {
216 if (!CargoSpec::Get(cargo)->IsValid()) continue;
217 const GoodsEntry &ge = from->goods[cargo];
219 ge.link_graph != to->goods[cargo].link_graph) {
220 continue;
221 }
222 const LinkGraph &lg = *LinkGraph::Get(ge.link_graph);
223 if (lg[ge.node].HasEdgeTo(to->goods[cargo].node)) {
224 ConstEdge &edge = lg[ge.node][to->goods[cargo].node];
225 this->AddStats(cargo, lg.Monthly(edge.capacity), lg.Monthly(edge.usage),
226 ge.HasData() ? ge.GetData().flows.GetFlowVia(to->index) : 0,
228 from->owner == OWNER_NONE || to->owner == OWNER_NONE,
229 this->cached_links[from->index][to->index]);
230 }
231 }
232}
233
246/* static */ void LinkGraphOverlay::AddStats(CargoType new_cargo, uint new_cap, uint new_usg, uint new_plan, uint32_t time, bool new_shared, LinkProperties &cargo)
247{
248 /* multiply the numbers by 32 in order to avoid comparing to 0 too often. */
249 if (cargo.capacity == 0 ||
250 cargo.Usage() * 32 / (cargo.capacity + 1) < std::max(new_usg, new_plan) * 32 / (new_cap + 1)) {
251 cargo.cargo = new_cargo;
252 cargo.capacity = new_cap;
253 cargo.usage = new_usg;
254 cargo.planned = new_plan;
255 cargo.time = time;
256 }
257 if (new_shared) cargo.shared = true;
258}
259
265{
266 if (this->dirty) {
267 this->RebuildCache();
268 this->dirty = false;
269 }
270 this->DrawLinks(dpi);
271 this->DrawStationDots(dpi);
272}
273
279{
280 int width = ScaleGUITrad(this->scale);
281 for (const auto &i : this->cached_links) {
282 if (!Station::IsValidID(i.first)) continue;
283 Point pta = this->GetStationMiddle(Station::Get(i.first));
284 for (const auto &j : i.second) {
285 if (!Station::IsValidID(j.first)) continue;
286 Point ptb = this->GetStationMiddle(Station::Get(j.first));
287 if (!this->IsLinkVisible(pta, ptb, dpi, width + 2)) continue;
288 this->DrawContent(pta, ptb, j.second);
289 }
290 }
291}
292
299void LinkGraphOverlay::DrawContent(Point pta, Point ptb, const LinkProperties &cargo) const
300{
301 uint usage_or_plan = std::min(cargo.capacity * 2 + 1, cargo.Usage());
302 PixelColour colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][usage_or_plan * lengthof(LinkGraphOverlay::LINK_COLOURS[0]) / (cargo.capacity * 2 + 2)];
303 int width = ScaleGUITrad(this->scale);
304 int dash = cargo.shared ? width * 4 : 0;
305
306 /* Move line a bit 90° against its dominant direction to prevent it from
307 * being hidden below the grey line. */
308 int side = _settings_game.vehicle.road_side ? 1 : -1;
309 if (abs(pta.x - ptb.x) < abs(pta.y - ptb.y)) {
310 int offset_x = (pta.y > ptb.y ? 1 : -1) * side * width;
311 GfxDrawLine(pta.x + offset_x, pta.y, ptb.x + offset_x, ptb.y, colour, width, dash);
312 } else {
313 int offset_y = (pta.x < ptb.x ? 1 : -1) * side * width;
314 GfxDrawLine(pta.x, pta.y + offset_y, ptb.x, ptb.y + offset_y, colour, width, dash);
315 }
316
317 GfxDrawLine(pta.x, pta.y, ptb.x, ptb.y, GetColourGradient(Colours::Grey, Shade::Darkest), width);
318}
319
326{
327 int width = ScaleGUITrad(this->scale);
328 for (const auto &i : this->cached_stations) {
329 const Station *st = Station::GetIfValid(i.first);
330 if (st == nullptr) continue;
331 Point pt = this->GetStationMiddle(st);
332 if (!this->IsPointVisible(pt, dpi, 3 * width)) continue;
333
334 uint r = width * 2 + width * 2 * std::min(200U, i.second) / 200;
335
340 }
341}
342
351/* static */ void LinkGraphOverlay::DrawVertex(int x, int y, int size, PixelColour colour, PixelColour border_colour)
352{
353 size--;
354 int w1 = size / 2;
355 int w2 = size / 2 + size % 2;
356 int borderwidth = ScaleGUITrad(1);
357
358 GfxFillRect(x - w1 - borderwidth, y - w1 - borderwidth, x + w2 + borderwidth, y + w2 + borderwidth, border_colour);
359 GfxFillRect(x - w1, y - w1, x + w2, y + w2, colour);
360}
361
362bool LinkGraphOverlay::ShowTooltip(Point pt, TooltipCloseCondition close_cond)
363{
364 for (auto i(this->cached_links.crbegin()); i != this->cached_links.crend(); ++i) {
365 if (!Station::IsValidID(i->first)) continue;
366 Point pta = this->GetStationMiddle(Station::Get(i->first));
367 for (auto j(i->second.crbegin()); j != i->second.crend(); ++j) {
368 if (!Station::IsValidID(j->first)) continue;
369 if (i->first == j->first) continue;
370
371 /* Check the distance from the cursor to the line defined by the two stations. */
372 Point ptb = this->GetStationMiddle(Station::Get(j->first));
373 float dist = std::abs((int64_t)(ptb.x - pta.x) * (int64_t)(pta.y - pt.y) - (int64_t)(pta.x - pt.x) * (int64_t)(ptb.y - pta.y)) /
374 std::sqrt((int64_t)(ptb.x - pta.x) * (int64_t)(ptb.x - pta.x) + (int64_t)(ptb.y - pta.y) * (int64_t)(ptb.y - pta.y));
375 const auto &link = j->second;
376 if (dist <= 4 && link.Usage() > 0 &&
377 pt.x + 2 >= std::min(pta.x, ptb.x) &&
378 pt.x - 2 <= std::max(pta.x, ptb.x) &&
379 pt.y + 2 >= std::min(pta.y, ptb.y) &&
380 pt.y - 2 <= std::max(pta.y, ptb.y)) {
381 static std::string tooltip_extension;
382 tooltip_extension.clear();
383 /* Fill buf with more information if this is a bidirectional link. */
384 uint32_t back_time = 0;
385 auto k = this->cached_links[j->first].find(i->first);
386 if (k != this->cached_links[j->first].end()) {
387 const auto &back = k->second;
388 back_time = back.time;
389 if (back.Usage() > 0) {
390 tooltip_extension = GetString(STR_LINKGRAPH_STATS_TOOLTIP_RETURN_EXTENSION,
391 back.cargo, back.Usage(), back.Usage() * 100 / (back.capacity + 1));
392 }
393 }
394 /* Add information about the travel time if known. */
395 const auto time = link.time ? back_time ? ((link.time + back_time) / 2) : link.time : back_time;
396 if (time > 0) {
397 auto params = MakeParameters(time);
398 AppendStringWithArgsInPlace(tooltip_extension, STR_LINKGRAPH_STATS_TOOLTIP_TIME_EXTENSION, params);
399 }
401 GetEncodedString(TimerGameEconomy::UsingWallclockUnits() ? STR_LINKGRAPH_STATS_TOOLTIP_MINUTE : STR_LINKGRAPH_STATS_TOOLTIP_MONTH,
402 link.cargo, link.Usage(), i->first, j->first, link.Usage() * 100 / (link.capacity + 1), tooltip_extension),
403 close_cond);
404 return true;
405 }
406 }
407 }
408 GuiShowTooltips(this->window, {}, close_cond);
409 return false;
410}
411
418{
419 if (this->window->viewport != nullptr) {
420 return GetViewportStationMiddle(*this->window->viewport, st);
421 } else {
422 /* assume this is a smallmap */
423 return GetSmallMapStationMiddle(this->window, st);
424 }
425}
426
432{
433 this->cargo_mask = cargo_mask;
434 this->RebuildCache();
435 this->window->GetWidget<NWidgetBase>(this->widget_id)->SetDirty(this->window);
436}
437
443{
444 this->company_mask = company_mask;
445 this->RebuildCache();
446 this->window->GetWidget<NWidgetBase>(this->widget_id)->SetDirty(this->window);
447}
448
450std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsLinkGraphGUI()
451{
452 return MakeCompanyButtonRows(WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST, Colours::Grey, 3, STR_NULL);
453}
454
455std::unique_ptr<NWidgetBase> MakeSaturationLegendLinkGraphGUI()
456{
457 auto panel = std::make_unique<NWidgetVertical>(NWidContainerFlag::EqualSize);
458 for (uint i = 0; i < lengthof(LinkGraphOverlay::LINK_COLOURS[0]); ++i) {
459 auto wid = std::make_unique<NWidgetBackground>(WWT_PANEL, Colours::DarkGreen, i + WID_LGL_SATURATION_FIRST);
460 wid->SetMinimalSize(50, 0);
461 wid->SetMinimalTextLines(1, 0, FontSize::Small);
462 wid->SetFill(1, 1);
463 wid->SetResize(0, 0);
464 panel->Add(std::move(wid));
465 }
466 return panel;
467}
468
469std::unique_ptr<NWidgetBase> MakeCargoesLegendLinkGraphGUI()
470{
471 uint num_cargo = static_cast<uint>(_sorted_cargo_specs.size());
472 static const uint ENTRIES_PER_COL = 5;
473 auto panel = std::make_unique<NWidgetHorizontal>(NWidContainerFlag::EqualSize);
474 std::unique_ptr<NWidgetVertical> col = nullptr;
475
476 for (uint i = 0; i < num_cargo; ++i) {
477 if (i % ENTRIES_PER_COL == 0) {
478 if (col != nullptr) panel->Add(std::move(col));
479 col = std::make_unique<NWidgetVertical>(NWidContainerFlag::EqualSize);
480 }
481 auto wid = std::make_unique<NWidgetBackground>(WWT_PANEL, Colours::Grey, i + WID_LGL_CARGO_FIRST);
482 wid->SetMinimalSize(25, 0);
483 wid->SetMinimalTextLines(1, 0, FontSize::Small);
484 wid->SetFill(1, 1);
485 wid->SetResize(0, 0);
486 col->Add(std::move(wid));
487 }
488 /* Fill up last row */
489 for (uint i = num_cargo; i < Ceil(num_cargo, ENTRIES_PER_COL); ++i) {
490 auto spc = std::make_unique<NWidgetSpacer>(25, 0);
491 spc->SetMinimalTextLines(1, 0, FontSize::Small);
492 spc->SetFill(1, 1);
493 spc->SetResize(0, 0);
494 col->Add(std::move(spc));
495 }
496 /* If there are no cargo specs defined, then col won't have been created so don't add it. */
497 if (col != nullptr) panel->Add(std::move(col));
498 return panel;
499}
500
501
502static constexpr std::initializer_list<NWidgetPart> _nested_linkgraph_legend_widgets = {
505 NWidget(WWT_CAPTION, Colours::DarkGreen, WID_LGL_CAPTION), SetStringTip(STR_LINKGRAPH_LEGEND_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
508 EndContainer(),
512 NWidgetFunction(MakeSaturationLegendLinkGraphGUI),
513 EndContainer(),
517 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_LGL_COMPANIES_ALL), SetStringTip(STR_LINKGRAPH_LEGEND_ALL),
518 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_LGL_COMPANIES_NONE), SetStringTip(STR_LINKGRAPH_LEGEND_NONE),
519 EndContainer(),
520 EndContainer(),
523 NWidgetFunction(MakeCargoesLegendLinkGraphGUI),
524 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_LGL_CARGOES_ALL), SetStringTip(STR_LINKGRAPH_LEGEND_ALL),
525 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_LGL_CARGOES_NONE), SetStringTip(STR_LINKGRAPH_LEGEND_NONE),
526 EndContainer(),
527 EndContainer(),
528 EndContainer(),
530};
531
532static_assert(WID_LGL_SATURATION_LAST - WID_LGL_SATURATION_FIRST ==
534
537 WindowPosition::Automatic, "toolbar_linkgraph", 0, 0,
539 {},
540 _nested_linkgraph_legend_widgets
541);
542
550
551LinkGraphLegendWindow::LinkGraphLegendWindow(WindowDesc &desc, int window_number) : Window(desc), num_cargo(_sorted_cargo_specs.size())
552{
553 this->InitNested(window_number);
554 this->InvalidateData(0);
555 this->SetOverlay(GetMainWindow()->viewport->overlay);
556}
557
562void LinkGraphLegendWindow::SetOverlay(std::shared_ptr<LinkGraphOverlay> overlay)
563{
564 this->overlay = std::move(overlay);
565 CompanyMask companies = this->overlay->GetCompanyMask();
566 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
567 if (!this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) {
568 this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, companies.Test(c));
569 }
570 }
571 CargoTypes cargoes = this->overlay->GetCargoMask();
572 for (uint c = 0; c < this->num_cargo; c++) {
573 this->SetWidgetLoweredState(WID_LGL_CARGO_FIRST + c, cargoes.Test(_sorted_cargo_specs[c]->Index()));
574 }
575}
576
577void LinkGraphLegendWindow::UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize)
578{
579 if (IsInsideMM(widget, WID_LGL_SATURATION_FIRST, WID_LGL_SATURATION_LAST + 1)) {
580 StringID str = STR_NULL;
581 if (widget == WID_LGL_SATURATION_FIRST) {
582 str = STR_LINKGRAPH_LEGEND_UNUSED;
583 } else if (widget == WID_LGL_SATURATION_LAST) {
584 str = STR_LINKGRAPH_LEGEND_OVERLOADED;
585 } else if (widget == (WID_LGL_SATURATION_LAST + WID_LGL_SATURATION_FIRST) / 2) {
586 str = STR_LINKGRAPH_LEGEND_SATURATED;
587 }
588 if (str != STR_NULL) {
590 dim.width += padding.width;
591 dim.height += padding.height;
592 size = maxdim(size, dim);
593 }
594 }
595 if (IsInsideMM(widget, WID_LGL_CARGO_FIRST, WID_LGL_CARGO_LAST + 1)) {
596 const CargoSpec *cargo = _sorted_cargo_specs[widget - WID_LGL_CARGO_FIRST];
598 dim.width += padding.width;
599 dim.height += padding.height;
600 size = maxdim(size, dim);
601 }
602}
603
605{
607 if (IsInsideMM(widget, WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST + 1)) {
608 if (this->IsWidgetDisabled(widget)) return;
609 CompanyID cid = (CompanyID)(widget - WID_LGL_COMPANY_FIRST);
610 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
611 DrawCompanyIcon(cid, CentreBounds(br.left, br.right, sprite_size.width), CentreBounds(br.top, br.bottom, sprite_size.height));
612 }
613 if (IsInsideMM(widget, WID_LGL_SATURATION_FIRST, WID_LGL_SATURATION_LAST + 1)) {
614 PixelColour colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][widget - WID_LGL_SATURATION_FIRST];
615 GfxFillRect(br, colour);
616 StringID str = STR_NULL;
617 if (widget == WID_LGL_SATURATION_FIRST) {
618 str = STR_LINKGRAPH_LEGEND_UNUSED;
619 } else if (widget == WID_LGL_SATURATION_LAST) {
620 str = STR_LINKGRAPH_LEGEND_OVERLOADED;
621 } else if (widget == (WID_LGL_SATURATION_LAST + WID_LGL_SATURATION_FIRST) / 2) {
622 str = STR_LINKGRAPH_LEGEND_SATURATED;
623 }
624 if (str != STR_NULL) {
625 DrawString(br.left, br.right, CentreBounds(br.top, br.bottom, GetCharacterHeight(FontSize::Small)), str, GetContrastColour(colour) | TC_FORCED, SA_HOR_CENTER, false, FontSize::Small);
626 }
627 }
628 if (IsInsideMM(widget, WID_LGL_CARGO_FIRST, WID_LGL_CARGO_LAST + 1)) {
629 const CargoSpec *cargo = _sorted_cargo_specs[widget - WID_LGL_CARGO_FIRST];
630 GfxFillRect(br, cargo->legend_colour);
631 DrawString(br.left, br.right, CentreBounds(br.top, br.bottom, GetCharacterHeight(FontSize::Small)), cargo->abbrev, GetContrastColour(cargo->legend_colour, 73), SA_HOR_CENTER, false, FontSize::Small);
632 }
633}
634
635bool LinkGraphLegendWindow::OnTooltip([[maybe_unused]] Point, WidgetID widget, TooltipCloseCondition close_cond)
636{
637 if (IsInsideMM(widget, WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST + 1)) {
638 if (this->IsWidgetDisabled(widget)) {
639 GuiShowTooltips(this, GetEncodedString(STR_LINKGRAPH_LEGEND_SELECT_COMPANIES), close_cond);
640 } else {
641 GuiShowTooltips(this,
642 GetEncodedString(STR_LINKGRAPH_LEGEND_COMPANY_TOOLTIP,
643 STR_LINKGRAPH_LEGEND_SELECT_COMPANIES,
644 widget - WID_LGL_COMPANY_FIRST),
645 close_cond);
646 }
647 return true;
648 }
649 if (IsInsideMM(widget, WID_LGL_CARGO_FIRST, WID_LGL_CARGO_LAST + 1)) {
650 const CargoSpec *cargo = _sorted_cargo_specs[widget - WID_LGL_CARGO_FIRST];
651 GuiShowTooltips(this, GetEncodedString(cargo->name), close_cond);
652 return true;
653 }
654 return false;
655}
656
661{
662 CompanyMask mask;
663 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
664 if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue;
665 if (!this->IsWidgetLowered(WID_LGL_COMPANY_FIRST + c)) continue;
666 mask.Set(c);
667 }
668 this->overlay->SetCompanyMask(mask);
669}
670
675{
676 CargoTypes mask{};
677 for (uint c = 0; c < num_cargo; c++) {
678 if (!this->IsWidgetLowered(WID_LGL_CARGO_FIRST + c)) continue;
679 mask.Set(_sorted_cargo_specs[c]->Index());
680 }
681 this->overlay->SetCargoMask(mask);
682}
683
684void LinkGraphLegendWindow::OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count)
685{
686 /* Check which button is clicked */
687 if (IsInsideMM(widget, WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST + 1)) {
688 if (!this->IsWidgetDisabled(widget)) {
689 this->ToggleWidgetLoweredState(widget);
691 }
692 } else if (widget == WID_LGL_COMPANIES_ALL || widget == WID_LGL_COMPANIES_NONE) {
693 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
694 if (this->IsWidgetDisabled(WID_LGL_COMPANY_FIRST + c)) continue;
695 this->SetWidgetLoweredState(WID_LGL_COMPANY_FIRST + c, widget == WID_LGL_COMPANIES_ALL);
696 }
698 this->SetDirty();
699 } else if (IsInsideMM(widget, WID_LGL_CARGO_FIRST, WID_LGL_CARGO_LAST + 1)) {
700 this->ToggleWidgetLoweredState(widget);
701 this->UpdateOverlayCargoes();
702 } else if (widget == WID_LGL_CARGOES_ALL || widget == WID_LGL_CARGOES_NONE) {
703 for (uint c = 0; c < this->num_cargo; c++) {
704 this->SetWidgetLoweredState(WID_LGL_CARGO_FIRST + c, widget == WID_LGL_CARGOES_ALL);
705 }
706 this->UpdateOverlayCargoes();
707 }
708 this->SetDirty();
709}
710
716void LinkGraphLegendWindow::OnInvalidateData([[maybe_unused]] int data, [[maybe_unused]] bool gui_scope)
717{
718 if (this->num_cargo != _sorted_cargo_specs.size()) {
719 this->Close();
720 return;
721 }
722
723 /* Disable the companies who are not active */
724 for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) {
725 this->SetWidgetDisabledState(WID_LGL_COMPANY_FIRST + i, !Company::IsValidID(i));
726 }
727}
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
bool IsPointVisible(Point pt, const DrawPixelInfo *dpi, int padding=0) const
Determine if a certain point is inside the given DPI, with some lee way.
void SetCargoMask(CargoTypes cargo_mask)
Set a new cargo mask and rebuild the cache.
CargoTypes cargo_mask
Bitmask of cargos to be displayed.
Window * window
Window to be drawn into.
void DrawLinks(const DrawPixelInfo *dpi) const
Draw the cached links or part of them into the given area.
static void DrawVertex(int x, int y, int size, PixelColour colour, PixelColour border_colour)
Draw a square symbolizing a producer of cargo.
void SetCompanyMask(CompanyMask company_mask)
Set a new company mask and rebuild the cache.
static const PixelColour LINK_COLOURS[][12]
Colours for the various "load" states of links.
static void AddStats(CargoType new_cargo, uint new_cap, uint new_usg, uint new_flow, uint32_t time, bool new_shared, LinkProperties &cargo)
Add information from a given pair of link stat and flow stat to the given link properties.
StationSupplyList cached_stations
Cache for stations to be drawn.
LinkMap cached_links
Cache for links to reduce recalculation.
bool IsLinkVisible(Point pta, Point ptb, const DrawPixelInfo *dpi, int padding=0) const
Determine if a certain link crosses through the area given by the dpi with some lee way.
Point GetStationMiddle(const Station *st) const
Determine the middle of a station in the current window.
void Draw(const DrawPixelInfo *dpi)
Draw the linkgraph overlay or some part of it, in the area given.
bool dirty
Set if overlay should be rebuilt.
const WidgetID widget_id
ID of Widget in Window to be drawn to.
void DrawContent(Point pta, Point ptb, const LinkProperties &cargo) const
Draw one specific link.
CompanyMask company_mask
Bitmask of companies to be displayed.
uint scale
Width of link lines.
void GetWidgetDpi(DrawPixelInfo *dpi) const
Get a DPI for the widget we will be drawing to.
void AddLinks(const Station *sta, const Station *stb)
Add all "interesting" links between the given stations to the cache.
void DrawStationDots(const DrawPixelInfo *dpi) const
Draw dots for stations into the smallmap.
void SetDirty()
Mark the linkgraph dirty to be rebuilt next time Draw() is called.
void RebuildCache()
Rebuild the cache and recalculate which links and stations to be shown.
A connected component of a link graph.
Definition linkgraph.h:37
uint Monthly(uint base) const
Scale a value to its monthly equivalent, based on last compression.
Definition linkgraph.h:253
Baseclass for nested widgets.
uint current_x
Current horizontal size (after resizing).
uint current_y
Current vertical size (after resizing).
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:93
Definition of stuff that is very close to a company, like the company struct itself.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
GUI Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:972
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:900
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:669
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:116
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ SA_HOR_CENTER
Horizontally center the text.
Definition gfx_type.h:389
@ Grey
Grey.
Definition gfx_type.h:299
@ DarkGreen
Dark green.
Definition gfx_type.h:292
@ TC_FORCED
Ignore colour changes from strings.
Definition gfx_type.h:332
constexpr NWidgetPart NWidgetFunction(NWidgetFunctionType *func_ptr)
Obtain a nested widget (sub)tree from an external source.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:980
std::unique_ptr< NWidgetBase > MakeCompanyButtonRowsLinkGraphGUI()
Make a number of rows with buttons for each company for the linkgraph legend window.
static WindowDesc _linkgraph_legend_desc(WindowPosition::Automatic, "toolbar_linkgraph", 0, 0, WC_LINKGRAPH_LEGEND, WC_NONE, {}, _nested_linkgraph_legend_widgets)
Window definition for the linkgraph toolbar.
void ShowLinkGraphLegend()
Open a link graph legend window.
Declaration of linkgraph overlay GUI.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr uint Ceil(uint a, uint b)
Computes ceil(a / b) * b for non-negative a and b.
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition misc_gui.cpp:690
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
TextColour GetContrastColour(PixelColour background, uint8_t threshold)
Determine a contrasty text colour for a coloured background.
Definition palette.cpp:366
@ Light
Light colour shade.
@ Darkest
Darkest colour shade.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Point GetSmallMapStationMiddle(const Window *w, const Station *st)
Determine the middle of a station in the smallmap window.
Smallmap GUI functions.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
Functions related to OTTD's strings.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Owner owner
The owner of this station.
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Specification of a cargo type.
Definition cargotype.h:75
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:139
StringID abbrev
Two letter abbreviation for this cargo type.
Definition cargotype.h:96
StringID name
Name of this type of cargo.
Definition cargotype.h:92
T y
Y coordinate.
T x
X coordinate.
Dimensions (a width and height) of a rectangle in 2D.
Data about how and where to blit pixels.
Definition gfx_type.h:157
FlowStatMap flows
Planned flows through this station.
Stores station stats for a single cargo.
NodeID node
ID of node in link graph referring to this goods entry.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
LinkGraphID link_graph
Link graph this station belongs to.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Invalidate the data of this window if the cargoes or companies have changed.
void SetOverlay(std::shared_ptr< LinkGraphOverlay > overlay)
Set the overlay belonging to this menu and import its company/cargo settings.
void UpdateOverlayCompanies()
Update the overlay with the new company selection.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
Event to display a custom tooltip.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void UpdateOverlayCargoes()
Update the overlay with the new cargo selection.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
uint32_t TravelTime() const
Get edge's average travel time.
Definition linkgraph.h:56
NodeID dest_node
Destination of the edge.
Definition linkgraph.h:48
uint usage
Usage of the link.
Definition linkgraph.h:44
uint capacity
Capacity of the link.
Definition linkgraph.h:43
std::vector< BaseEdge > edges
Sorted list of outgoing edges from this node.
Definition linkgraph.h:101
uint supply
Supply at the station.
Definition linkgraph.h:95
Monthly statistics for a link between two stations.
uint usage
Actual usage of the link.
bool shared
If this is a shared link to be drawn dashed.
CargoType cargo
Cargo type of the link.
uint planned
Planned usage of the link.
uint Usage() const
Return the usage of the link to display.
uint capacity
Capacity of the link.
uint32_t time
Travel time of the link.
Colour for pixel/line drawing.
Definition gfx_type.h:414
static LinkGraph * Get(auto index)
Specification of a rectangle with absolute coordinates of all edges.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Station * GetIfValid(auto index)
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
High level window description.
Definition window_gui.h:168
Data structure for an opened window.
Definition window_gui.h:274
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1117
ResizeInfo resize
Resize information.
Definition window_gui.h:315
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:492
bool IsWidgetDisabled(WidgetID widget_index) const
Gets the enabled/disabled status of a widget.
Definition window_gui.h:411
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:442
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:382
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
Definition window_gui.h:451
Definition of the game-calendar-timer.
Definition of the tick-based game-timer.
Functions related to (drawing on) viewports.
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
std::unique_ptr< NWidgetBase > MakeCompanyButtonRows(WidgetID widget_first, WidgetID widget_last, Colours button_colour, int max_length, StringID button_tooltip, bool resizable)
Make a number of rows with button-like graphics, for enabling/disabling each company.
Definition widget.cpp:3476
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ EqualSize
Containers should keep all their (resizing) children equally large.
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1195
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:144
int WidgetID
Widget ID.
Definition window_type.h:21
@ WC_LINKGRAPH_LEGEND
Linkgraph legend; Window numbers:
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
Definition window_type.h:51
Functions related to zooming.