OpenTTD Source 20261112-master-gbcbec5e63f
framerate_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
12#include "framerate_type.h"
13#include <chrono>
14#include "gfx_func.h"
15#include "newgrf_sound.h"
16#include "window_gui.h"
17#include "window_func.h"
18#include "strings_func.h"
19#include "console_func.h"
20#include "console_type.h"
21#include "company_base.h"
22#include "ai/ai_info.hpp"
23#include "ai/ai_instance.hpp"
24#include "game/game.hpp"
26#include "timer/timer.h"
27#include "timer/timer_window.h"
28#include "zoom_func.h"
29
31
32#include <atomic>
33#include <mutex>
34
35#include "table/strings.h"
36
37#include "safeguards.h"
38
39static std::mutex _sound_perf_lock;
40static std::atomic<bool> _sound_perf_pending;
41static std::vector<TimingMeasurement> _sound_perf_measurements;
42
46namespace {
47
49 const int NUM_FRAMERATE_POINTS = 512;
52
55 static const TimingMeasurement INVALID_DURATION = UINT64_MAX;
56
58 std::array<TimingMeasurement, NUM_FRAMERATE_POINTS> durations{};
60 std::array<TimingMeasurement, NUM_FRAMERATE_POINTS> timestamps{};
62 double expected_rate = 0;
64 int next_index = 0;
66 int prev_index = 0;
68 int num_valid = 0;
69
74
82
88 void Add(TimingMeasurement start_time, TimingMeasurement end_time)
89 {
90 this->durations[this->next_index] = end_time - start_time;
91 this->timestamps[this->next_index] = start_time;
92 this->prev_index = this->next_index;
93 this->next_index += 1;
94 if (this->next_index >= NUM_FRAMERATE_POINTS) this->next_index = 0;
95 this->num_valid = std::min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
96 }
97
103 {
104 this->timestamps[this->next_index] = this->acc_timestamp;
105 this->durations[this->next_index] = this->acc_duration;
106 this->prev_index = this->next_index;
107 this->next_index += 1;
108 if (this->next_index >= NUM_FRAMERATE_POINTS) this->next_index = 0;
109 this->num_valid = std::min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
110
111 this->acc_duration = 0;
112 this->acc_timestamp = start_time;
113 }
114
120 {
121 this->acc_duration += duration;
122 }
123
129 {
130 if (this->durations[this->prev_index] != INVALID_DURATION) {
131 this->timestamps[this->next_index] = start_time;
132 this->durations[this->next_index] = INVALID_DURATION;
133 this->prev_index = this->next_index;
134 this->next_index += 1;
135 if (this->next_index >= NUM_FRAMERATE_POINTS) this->next_index = 0;
136 this->num_valid += 1;
137 }
138 }
139
146 {
147 count = std::min(count, this->num_valid);
148
149 int first_point = this->prev_index - count;
150 if (first_point < 0) first_point += NUM_FRAMERATE_POINTS;
151
152 /* Sum durations, skipping invalid points */
153 double sumtime = 0;
154 const int last_point = first_point + count;
155 for (int i = first_point; i < last_point; i++) {
156 auto d = this->durations[i % NUM_FRAMERATE_POINTS];
157 if (d != INVALID_DURATION) {
158 sumtime += d;
159 } else {
160 /* Don't count the invalid durations */
161 count--;
162 }
163 }
164
165 if (count == 0) return 0; // avoid div by zero
166 return sumtime * 1000 / count / TIMESTAMP_PRECISION;
167 }
168
173 double GetRate()
174 {
175 /* Start at last recorded point, end at latest when reaching the earliest recorded point */
176 int point = this->prev_index;
177 int last_point = this->next_index - this->num_valid;
178 if (last_point < 0) last_point += NUM_FRAMERATE_POINTS;
179
180 /* Number of data points collected */
181 int count = 0;
182 /* Time of previous data point */
183 TimingMeasurement last = this->timestamps[point];
184 /* Total duration covered by collected points */
185 TimingMeasurement total = 0;
186
187 /* We have nothing to compare the first point against */
188 point--;
189 if (point < 0) point = NUM_FRAMERATE_POINTS - 1;
190
191 while (point != last_point) {
192 /* Only record valid data points, but pretend the gaps in measurements aren't there */
193 if (this->durations[point] != INVALID_DURATION) {
194 total += last - this->timestamps[point];
195 count++;
196 }
197 last = this->timestamps[point];
198 if (total >= TIMESTAMP_PRECISION) break; // end after 1 second has been collected
199 point--;
200 if (point < 0) point = NUM_FRAMERATE_POINTS - 1;
201 }
202
203 if (total == 0 || count == 0) return 0;
204 return (double)count * TIMESTAMP_PRECISION / total;
205 }
206 };
207
209 static const double GL_RATE = 1000.0 / MILLISECONDS_PER_TICK;
210
217 PerformanceData(GL_RATE), // PerformanceElement::GameLoop
218 PerformanceData(1), // PerformanceElement::GameLoopEconomy
219 PerformanceData(1), // PerformanceElement::GameLoopTrains
220 PerformanceData(1), // PerformanceElement::GameLoopRoadVehicles
221 PerformanceData(1), // PerformanceElement::GameLoopShips
222 PerformanceData(1), // PerformanceElement::GameLoopAircraft
223 PerformanceData(1), // PerformanceElement::GameLoopLandscape
224 PerformanceData(1), // PerformanceElement::GameLoopLinkGraph
225 PerformanceData(1000.0 / 30), // PerformanceElement::Drawing
226 PerformanceData(1), // PerformanceElement::ViewportDrawing
227 PerformanceData(60.0), // PerformanceElement::Video
228 PerformanceData(1000.0 * 8192 / 44100), // PerformanceElement::Sound
229 PerformanceData(1), // PerformanceElement::AllScripts
230 PerformanceData(1), // PerformanceElement::GameScript
231 PerformanceData(1), // PerformanceElement::AI0 ...
245 PerformanceData(1), // PerformanceElement::AI14
246 };
247
248}
249
250
258{
259 using namespace std::chrono;
260 return (TimingMeasurement)time_point_cast<microseconds>(high_resolution_clock::now()).time_since_epoch().count();
261}
262
263
269{
270 assert(elem < PerformanceElement::End);
271
272 this->elem = elem;
273 this->start_time = GetPerformanceTimer();
274}
275
278{
279 if (this->elem == PerformanceElement::AllScripts) {
280 /* Hack to not record scripts total when no scripts are active */
281 bool any_active = _pf_data[PerformanceElement::GameScript].num_valid > 0;
282 for (PerformanceElement e : EnumRange(PerformanceElement::AI0, PerformanceElement::End)) any_active |= _pf_data[e].num_valid > 0;
283 if (!any_active) {
285 return;
286 }
287 }
288 if (this->elem == PerformanceElement::Sound) {
289 /* PerformanceElement::Sound measurements are made from the mixer thread.
290 * _pf_data cannot be concurrently accessed from the mixer thread
291 * and the main thread, so store the measurement results in a
292 * mutex-protected queue which is drained by the main thread.
293 * See: ProcessPendingPerformanceMeasurements() */
295 std::lock_guard lk(_sound_perf_lock);
296 if (_sound_perf_measurements.size() >= NUM_FRAMERATE_POINTS * 2) return;
297 _sound_perf_measurements.push_back(this->start_time);
298 _sound_perf_measurements.push_back(end);
299 _sound_perf_pending.store(true, std::memory_order_release);
300 return;
301 }
302 _pf_data[this->elem].Add(this->start_time, GetPerformanceTimer());
303}
304
310{
311 _pf_data[this->elem].expected_rate = rate;
312}
313
319{
320 _pf_data[elem].num_valid = 0;
321 _pf_data[elem].next_index = 0;
322 _pf_data[elem].prev_index = 0;
323}
324
330{
332 _pf_data[elem].AddPause(GetPerformanceTimer());
333}
334
335
341{
342 assert(elem < PerformanceElement::End);
343
344 this->elem = elem;
345 this->start_time = GetPerformanceTimer();
346}
347
350{
351 _pf_data[this->elem].AddAccumulate(GetPerformanceTimer() - this->start_time);
352}
353
360{
361 _pf_data[elem].BeginAccumulate(GetPerformanceTimer());
362}
363
364
366
367
400
406static constexpr CompanyID GetAIIndex(PerformanceElement e)
407{
408 return CompanyID(e - PerformanceElement::AI0);
409}
410
416static std::string_view GetAIName(PerformanceElement e)
417{
418 CompanyID c = GetAIIndex(e);
419 if (!Company::IsValidAiID(c)) return {};
420 return Company::Get(c)->ai_info->GetName();
421}
422
424static constexpr std::initializer_list<NWidgetPart> _framerate_window_widgets = {
427 NWidget(WWT_CAPTION, Colours::Grey, WID_FRW_CAPTION),
430 EndContainer(),
433 NWidget(WWT_TEXT, Colours::Invalid, WID_FRW_RATE_GAMELOOP), SetToolTip(STR_FRAMERATE_RATE_GAMELOOP_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
434 NWidget(WWT_TEXT, Colours::Invalid, WID_FRW_RATE_DRAWING), SetToolTip(STR_FRAMERATE_RATE_BLITTER_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
435 NWidget(WWT_TEXT, Colours::Invalid, WID_FRW_RATE_FACTOR), SetToolTip(STR_FRAMERATE_SPEED_FACTOR_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
436 EndContainer(),
437 EndContainer(),
442 NWidget(WWT_EMPTY, Colours::Invalid, WID_FRW_TIMES_NAMES), SetScrollbar(WID_FRW_SCROLLBAR),
443 NWidget(WWT_EMPTY, Colours::Invalid, WID_FRW_TIMES_CURRENT), SetScrollbar(WID_FRW_SCROLLBAR),
444 NWidget(WWT_EMPTY, Colours::Invalid, WID_FRW_TIMES_AVERAGE), SetScrollbar(WID_FRW_SCROLLBAR),
445 NWidget(WWT_EMPTY, Colours::Invalid, WID_FRW_ALLOCSIZE), SetScrollbar(WID_FRW_SCROLLBAR),
446 EndContainer(),
447 NWidget(WWT_TEXT, Colours::Invalid, WID_FRW_INFO_DATA_POINTS), SetFill(1, 0), SetResize(1, 0),
448 EndContainer(),
449 EndContainer(),
451 NWidget(NWID_VSCROLLBAR, Colours::Grey, WID_FRW_SCROLLBAR),
453 EndContainer(),
454 EndContainer(),
455};
456
457struct FramerateWindow : Window {
458 int num_active = 0;
459 int num_displayed = 0;
460
462 StringID strid;
463 uint32_t value;
464
465 inline void SetRate(double value, double target)
466 {
467 const double threshold_good = target * 0.95;
468 const double threshold_bad = target * 2 / 3;
469 this->value = (uint32_t)(value * 100);
470 this->strid = (value > threshold_good) ? STR_FRAMERATE_FPS_GOOD : (value < threshold_bad) ? STR_FRAMERATE_FPS_BAD : STR_FRAMERATE_FPS_WARN;
471 }
472
473 inline void SetTime(double value, double target)
474 {
475 const double threshold_good = target / 3;
476 const double threshold_bad = target;
477 this->value = (uint32_t)(value * 100);
478 this->strid = (value < threshold_good) ? STR_FRAMERATE_MS_GOOD : (value > threshold_bad) ? STR_FRAMERATE_MS_BAD : STR_FRAMERATE_MS_WARN;
479 }
480
481 inline uint32_t GetValue() const { return this->value; }
482 inline uint32_t GetDecimals() const { return 2; }
483 };
484
491
492 static constexpr int MIN_ELEMENTS = 5;
493
494 FramerateWindow(WindowDesc &desc, WindowNumber number) : Window(desc)
495 {
496 this->InitNested(number);
497 this->UpdateData();
498 this->num_displayed = this->num_active;
499
500 /* Window is always initialised to MIN_ELEMENTS height, resize to contain num_displayed */
501 ResizeWindow(this, 0, (std::max(MIN_ELEMENTS, this->num_displayed) - MIN_ELEMENTS) * GetCharacterHeight(FontSize::Normal));
502 }
503
505 const IntervalTimer<TimerWindow> update_interval = {std::chrono::milliseconds(100), [this](auto) {
506 this->UpdateData();
507 this->SetDirty();
508 }};
509
510 void UpdateData()
511 {
512 double gl_rate = _pf_data[PerformanceElement::GameLoop].GetRate();
513 this->rate_gameloop.SetRate(gl_rate, _pf_data[PerformanceElement::GameLoop].expected_rate);
514 this->speed_gameloop.SetRate(gl_rate / _pf_data[PerformanceElement::GameLoop].expected_rate, 1.0);
515 if (this->IsShaded()) return; // in small mode, this is everything needed
516
517 this->rate_drawing.SetRate(_pf_data[PerformanceElement::Drawing].GetRate(), _settings_client.gui.refresh_rate);
518
519 int new_active = 0;
521 this->times_shortterm[e].SetTime(_pf_data[e].GetAverageDurationMilliseconds(8), MILLISECONDS_PER_TICK);
523 if (_pf_data[e].num_valid > 0) {
524 new_active++;
525 }
526 }
527
528 if (new_active != this->num_active) {
529 this->num_active = new_active;
530 Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
531 sb->SetCount(this->num_active);
532 sb->SetCapacity(std::min(this->num_displayed, this->num_active));
533 }
534 }
535
536 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
537 {
538 switch (widget) {
539 case WID_FRW_CAPTION:
540 /* When the window is shaded, the caption shows game loop rate and speed factor */
541 if (!this->IsShaded()) return GetString(STR_FRAMERATE_CAPTION);
542
543 return GetString(STR_FRAMERATE_CAPTION_SMALL, this->rate_gameloop.strid, this->rate_gameloop.GetValue(), this->rate_gameloop.GetDecimals(), this->speed_gameloop.GetValue(), this->speed_gameloop.GetDecimals());
544
545 case WID_FRW_RATE_GAMELOOP:
546 return GetString(STR_FRAMERATE_RATE_GAMELOOP, this->rate_gameloop.strid, this->rate_gameloop.GetValue(), this->rate_gameloop.GetDecimals());
547
548 case WID_FRW_RATE_DRAWING:
549 return GetString(STR_FRAMERATE_RATE_BLITTER, this->rate_drawing.strid, this->rate_drawing.GetValue(), this->rate_drawing.GetDecimals());
550
551 case WID_FRW_RATE_FACTOR:
552 return GetString(STR_FRAMERATE_SPEED_FACTOR, this->speed_gameloop.GetValue(), this->speed_gameloop.GetDecimals());
553
554 case WID_FRW_INFO_DATA_POINTS:
555 return GetString(STR_FRAMERATE_DATA_POINTS, NUM_FRAMERATE_POINTS);
556
557 default:
558 return this->Window::GetWidgetString(widget, stringid);
559 }
560 }
561
562 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
563 {
564 switch (widget) {
565 case WID_FRW_RATE_GAMELOOP:
566 size = GetStringBoundingBox(GetString(STR_FRAMERATE_RATE_GAMELOOP, STR_FRAMERATE_FPS_GOOD, GetParamMaxDigits(6), 2));
567 break;
568 case WID_FRW_RATE_DRAWING:
569 size = GetStringBoundingBox(GetString(STR_FRAMERATE_RATE_BLITTER, STR_FRAMERATE_FPS_GOOD, GetParamMaxDigits(6), 2));
570 break;
571 case WID_FRW_RATE_FACTOR:
572 size = GetStringBoundingBox(GetString(STR_FRAMERATE_SPEED_FACTOR, GetParamMaxDigits(6), 2));
573 break;
574
575 case WID_FRW_TIMES_NAMES: {
576 size.width = 0;
578 resize.width = 0;
579 fill.height = resize.height = GetCharacterHeight(FontSize::Normal);
581 if (_pf_data[e].num_valid == 0) continue;
582 Dimension line_size;
583 if (e < PerformanceElement::AI0) {
584 line_size = GetStringBoundingBox(STR_FRAMERATE_GAMELOOP + to_underlying(e));
585 } else {
586 line_size = GetStringBoundingBox(GetString(STR_FRAMERATE_AI, GetAIIndex(e) + 1, GetAIName(e)));
587 }
588 size.width = std::max(size.width, line_size.width);
589 }
590 break;
591 }
592
593 case WID_FRW_TIMES_CURRENT:
594 case WID_FRW_TIMES_AVERAGE:
595 case WID_FRW_ALLOCSIZE: {
596 size = GetStringBoundingBox(STR_FRAMERATE_CURRENT + (widget - WID_FRW_TIMES_CURRENT));
597 Dimension item_size = GetStringBoundingBox(GetString(STR_FRAMERATE_MS_GOOD, GetParamMaxDigits(6), 2));
598 size.width = std::max(size.width, item_size.width);
600 resize.width = 0;
601 fill.height = resize.height = GetCharacterHeight(FontSize::Normal);
602 break;
603 }
604 }
605 }
606
613 void DrawElementTimesColumn(const Rect &r, StringID heading_str, const CachedDecimalArray &values) const
614 {
615 const Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
616 int32_t skip = sb->GetPosition();
617 int drawable = this->num_displayed;
618 int y = r.top;
619 DrawString(r.left, r.right, y, heading_str, TextColour::FromString, {AlignmentH::Centre, AlignmentV::Middle}, true);
622 if (_pf_data[e].num_valid == 0) continue;
623 if (skip > 0) {
624 skip--;
625 } else {
626 DrawString(r.left, r.right, y, GetString(values[e].strid, values[e].GetValue(), values[e].GetDecimals()), TextColour::FromString, AlignmentH::ForceRight);
628 drawable--;
629 if (drawable == 0) break;
630 }
631 }
632 }
633
634 void DrawElementAllocationsColumn(const Rect &r) const
635 {
636 const Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
637 int32_t skip = sb->GetPosition();
638 int drawable = this->num_displayed;
639 int y = r.top;
640 DrawString(r.left, r.right, y, STR_FRAMERATE_MEMORYUSE, TextColour::FromString, {AlignmentH::Centre, AlignmentV::Middle}, true);
643 if (_pf_data[e].num_valid == 0) continue;
644 if (skip > 0) {
645 skip--;
647 uint64_t value = e == PerformanceElement::GameScript ? Game::GetInstance()->GetAllocatedMemory() : Company::Get(GetAIIndex(e))->ai_instance->GetAllocatedMemory();
648 DrawString(r.left, r.right, y, GetString(STR_FRAMERATE_BYTES_GOOD, value), TextColour::FromString, AlignmentH::ForceRight);
650 drawable--;
651 if (drawable == 0) break;
652 } else if (e == PerformanceElement::Sound) {
653 DrawString(r.left, r.right, y, GetString(STR_FRAMERATE_BYTES_GOOD, GetSoundPoolAllocatedMemory()), TextColour::FromString, AlignmentH::ForceRight);
655 drawable--;
656 if (drawable == 0) break;
657 } else {
658 /* skip non-script */
660 drawable--;
661 if (drawable == 0) break;
662 }
663 }
664 }
665
666 void DrawWidget(const Rect &r, WidgetID widget) const override
667 {
668 switch (widget) {
669 case WID_FRW_TIMES_NAMES: {
670 /* Render a column of titles for performance element names */
671 const Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
672 int32_t skip = sb->GetPosition();
673 int drawable = this->num_displayed;
674 int y = r.top + GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal; // first line contains headings in the value columns
676 if (_pf_data[e].num_valid == 0) continue;
677 if (skip > 0) {
678 skip--;
679 } else {
680 if (e < PerformanceElement::AI0) {
681 DrawString(r.left, r.right, y, STR_FRAMERATE_GAMELOOP + to_underlying(e), TextColour::FromString, AlignmentH::Start);
682 } else {
683 DrawString(r.left, r.right, y, GetString(STR_FRAMERATE_AI, GetAIIndex(e) + 1, GetAIName(e)), TextColour::FromString, AlignmentH::Start);
684 }
686 drawable--;
687 if (drawable == 0) break;
688 }
689 }
690 break;
691 }
692 case WID_FRW_TIMES_CURRENT:
693 /* Render short-term average values */
694 DrawElementTimesColumn(r, STR_FRAMERATE_CURRENT, this->times_shortterm);
695 break;
696 case WID_FRW_TIMES_AVERAGE:
697 /* Render averages of all recorded values */
698 DrawElementTimesColumn(r, STR_FRAMERATE_AVERAGE, this->times_longterm);
699 break;
700 case WID_FRW_ALLOCSIZE:
701 DrawElementAllocationsColumn(r);
702 break;
703 }
704 }
705
706 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
707 {
708 switch (widget) {
709 case WID_FRW_TIMES_NAMES:
710 case WID_FRW_TIMES_CURRENT:
711 case WID_FRW_TIMES_AVERAGE: {
712 /* Open time graph windows when clicking detail measurement lines */
713 const Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
714 int32_t line = sb->GetScrolledRowFromWidget(pt.y, this, widget, WidgetDimensions::scaled.vsep_normal + GetCharacterHeight(FontSize::Normal));
715 if (line != INT32_MAX) {
716 line++;
717 /* Find the visible line that was clicked */
719 if (_pf_data[e].num_valid > 0) line--;
720 if (line == 0) {
722 break;
723 }
724 }
725 }
726 break;
727 }
728 }
729 }
730
731 void OnResize() override
732 {
733 auto *wid = this->GetWidget<NWidgetResizeBase>(WID_FRW_TIMES_NAMES);
734 this->num_displayed = (wid->current_y - wid->min_y - WidgetDimensions::scaled.vsep_normal) / GetCharacterHeight(FontSize::Normal) - 1; // subtract 1 for headings
735 this->GetScrollbar(WID_FRW_SCROLLBAR)->SetCapacity(this->num_displayed);
736 }
737};
738
741 WindowPosition::Automatic, "framerate_display", 0, 0,
742 WindowClass::FramerateDisplay, WindowClass::None,
743 {},
744 _framerate_window_widgets
745);
746
747
749static constexpr std::initializer_list<NWidgetPart> _frametime_graph_window_widgets = {
754 EndContainer(),
757 NWidget(WWT_EMPTY, Colours::Invalid, WID_FGW_GRAPH),
758 EndContainer(),
759 EndContainer(),
760};
761
762struct FrametimeGraphWindow : Window {
765
768
769 FrametimeGraphWindow(WindowDesc &desc, WindowNumber number) : Window(desc), element(static_cast<PerformanceElement>(number))
770 {
771 this->InitNested(number);
772 this->UpdateScale();
773 }
774
775 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
776 {
777 switch (widget) {
778 case WID_FGW_CAPTION:
779 if (this->element < PerformanceElement::AI0) {
780 return GetString(STR_FRAMETIME_CAPTION_GAMELOOP + to_underlying(this->element));
781 }
782 return GetString(STR_FRAMETIME_CAPTION_AI, GetAIIndex(this->element) + 1, GetAIName(this->element));
783
784 default:
785 return this->Window::GetWidgetString(widget, stringid);
786 }
787 }
788
789 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
790 {
791 if (widget == WID_FGW_GRAPH) {
792 Dimension size_ms_label = GetStringBoundingBox(GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, 100));
793 Dimension size_s_label = GetStringBoundingBox(GetString(STR_FRAMERATE_GRAPH_SECONDS, 100));
794
795 /* Size graph in height to fit at least 10 vertical labels with space between, or at least 100 pixels */
796 graph_size.height = std::max<uint>(ScaleGUITrad(100), 10 * (size_ms_label.height + WidgetDimensions::scaled.vsep_normal));
797 /* Always 2:1 graph area */
798 graph_size.width = 2 * graph_size.height;
799 size = graph_size;
800
801 size.width += size_ms_label.width + WidgetDimensions::scaled.hsep_normal;
802 size.height += size_s_label.height + WidgetDimensions::scaled.vsep_normal;
803 }
804 }
805
806 void SelectHorizontalScale(TimingMeasurement range)
807 {
808 /* 60 Hz graphical drawing results in a value of approximately TIMESTAMP_PRECISION,
809 * this lands exactly on the scale = 2 vs scale = 4 boundary.
810 * To avoid excessive switching of the horizontal scale, bias these performance
811 * categories away from this scale boundary. */
812 if (this->element == PerformanceElement::Drawing || this->element == PerformanceElement::ViewportDrawing) range += (range / 2);
813
814 /* Determine horizontal scale based on period covered by 60 points
815 * (slightly less than 2 seconds at full game speed) */
816 struct ScaleDef { TimingMeasurement range; int scale; };
817 static const std::initializer_list<ScaleDef> hscales = {
818 { TIMESTAMP_PRECISION * 120, 60 },
819 { TIMESTAMP_PRECISION * 10, 20 },
820 { TIMESTAMP_PRECISION * 5, 10 },
821 { TIMESTAMP_PRECISION * 3, 4 },
822 { TIMESTAMP_PRECISION * 1, 2 },
823 };
824 for (const auto &sc : hscales) {
825 if (range < sc.range) this->horizontal_scale = sc.scale;
826 }
827 }
828
829 void SelectVerticalScale(TimingMeasurement range)
830 {
831 /* Determine vertical scale based on peak value (within the horizontal scale + a bit) */
832 static const std::initializer_list<TimingMeasurement> vscales = {
842 };
843 for (const auto &sc : vscales) {
844 if (range < sc) this->vertical_scale = (int)sc;
845 }
846 }
847
850 {
851 const auto &durations = _pf_data[this->element].durations;
852 const auto &timestamps = _pf_data[this->element].timestamps;
853 int num_valid = _pf_data[this->element].num_valid;
854 int point = _pf_data[this->element].prev_index;
855
856 TimingMeasurement lastts = timestamps[point];
857 TimingMeasurement time_sum = 0;
858 TimingMeasurement peak_value = 0;
859 int count = 0;
860
861 /* Sensible default for when too few measurements are available */
862 this->horizontal_scale = 4;
863
864 for (int i = 1; i < num_valid; i++) {
865 point--;
866 if (point < 0) point = NUM_FRAMERATE_POINTS - 1;
867
868 TimingMeasurement value = durations[point];
870 /* Skip gaps in data by pretending time is continuous across them */
871 lastts = timestamps[point];
872 continue;
873 }
874 if (value > peak_value) peak_value = value;
875 count++;
876
877 /* Accumulate period of time covered by data */
878 time_sum += lastts - timestamps[point];
879 lastts = timestamps[point];
880
881 /* Enough data to select a range and get decent data density */
882 if (count == 60) this->SelectHorizontalScale(time_sum);
883
884 /* End when enough points have been collected and the horizontal scale has been exceeded */
885 if (count >= 60 && time_sum >= (this->horizontal_scale + 2) * TIMESTAMP_PRECISION / 2) break;
886 }
887
888 this->SelectVerticalScale(peak_value);
889 }
890
892 const IntervalTimer<TimerWindow> update_interval = {std::chrono::milliseconds(500), [this](auto) {
893 this->UpdateScale();
894 }};
895
896 void OnRealtimeTick([[maybe_unused]] uint delta_ms) override
897 {
898 this->SetDirty();
899 }
900
910 template <typename T>
911 static inline T Scinterlate(T dst_min, T dst_max, T src_min, T src_max, T value)
912 {
913 T dst_diff = dst_max - dst_min;
914 T src_diff = src_max - src_min;
915 return (value - src_min) * dst_diff / src_diff + dst_min;
916 }
917
918 void DrawWidget(const Rect &r, WidgetID widget) const override
919 {
920 if (widget == WID_FGW_GRAPH) {
921 const auto &durations = _pf_data[this->element].durations;
922 const auto &timestamps = _pf_data[this->element].timestamps;
923 int point = _pf_data[this->element].prev_index;
924
925 const int x_zero = r.right - (int)this->graph_size.width;
926 const int x_max = r.right;
927 const int y_zero = r.top + (int)this->graph_size.height;
928 const int y_max = r.top;
929 const PixelColour c_grid = PC_DARK_GREY;
930 const PixelColour c_lines = PC_BLACK;
931 const PixelColour c_peak = PC_DARK_RED;
932
933 const TimingMeasurement draw_horz_scale = (TimingMeasurement)this->horizontal_scale * TIMESTAMP_PRECISION / 2;
934 const TimingMeasurement draw_vert_scale = (TimingMeasurement)this->vertical_scale;
935
936 /* Number of \c horizontal_scale units in each horizontal division */
937 const uint horz_div_scl = (this->horizontal_scale <= 20) ? 1 : 10;
938 /* Number of divisions of the horizontal axis */
939 const uint horz_divisions = this->horizontal_scale / horz_div_scl;
940 /* Number of divisions of the vertical axis */
941 const uint vert_divisions = 10;
942
943 /* Draw division lines and labels for the vertical axis */
944 for (uint division = 0; division < vert_divisions; division++) {
945 int y = Scinterlate(y_zero, y_max, 0, (int)vert_divisions, (int)division);
946 GfxDrawLine(x_zero, y, x_max, y, c_grid);
947 if (division % 2 == 0) {
948 if ((TimingMeasurement)this->vertical_scale > TIMESTAMP_PRECISION) {
950 GetString(STR_FRAMERATE_GRAPH_SECONDS, this->vertical_scale * division / 10 / TIMESTAMP_PRECISION),
952 } else {
954 GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, this->vertical_scale * division / 10 * 1000 / TIMESTAMP_PRECISION),
956 }
957 }
958 }
959 /* Draw division lines and labels for the horizontal axis */
960 for (uint division = horz_divisions; division > 0; division--) {
961 int x = Scinterlate(x_zero, x_max, 0, (int)horz_divisions, (int)horz_divisions - (int)division);
962 GfxDrawLine(x, y_max, x, y_zero, c_grid);
963 if (division % 2 == 0) {
964 DrawString(x, x_max, y_zero + WidgetDimensions::scaled.vsep_normal,
965 GetString(STR_FRAMERATE_GRAPH_SECONDS, division * horz_div_scl / 2),
967 }
968 }
969
970 /* Position of last rendered data point */
971 Point lastpoint = {
972 x_max,
973 (int)Scinterlate<int64_t>(y_zero, y_max, 0, this->vertical_scale, durations[point])
974 };
975 /* Timestamp of last rendered data point */
976 TimingMeasurement lastts = timestamps[point];
977
978 TimingMeasurement peak_value = 0;
979 Point peak_point = { 0, 0 };
980 TimingMeasurement value_sum = 0;
981 TimingMeasurement time_sum = 0;
982 int points_drawn = 0;
983
984 for (int i = 1; i < NUM_FRAMERATE_POINTS; i++) {
985 point--;
986 if (point < 0) point = NUM_FRAMERATE_POINTS - 1;
987
988 TimingMeasurement value = durations[point];
990 /* Skip gaps in measurements, pretend the data points on each side are continuous */
991 lastts = timestamps[point];
992 continue;
993 }
994
995 /* Use total time period covered for value along horizontal axis */
996 time_sum += lastts - timestamps[point];
997 lastts = timestamps[point];
998 /* Stop if past the width of the graph */
999 if (time_sum > draw_horz_scale) break;
1000
1001 /* Draw line from previous point to new point */
1002 Point newpoint = {
1003 (int)Scinterlate<int64_t>(x_zero, x_max, 0, (int64_t)draw_horz_scale, (int64_t)draw_horz_scale - (int64_t)time_sum),
1004 (int)Scinterlate<int64_t>(y_zero, y_max, 0, (int64_t)draw_vert_scale, (int64_t)value)
1005 };
1006 if (newpoint.x > lastpoint.x) continue; // don't draw backwards
1007 GfxDrawLine(lastpoint.x, lastpoint.y, newpoint.x, newpoint.y, c_lines);
1008 lastpoint = newpoint;
1009
1010 /* Record peak and average value across graphed data */
1011 value_sum += value;
1012 points_drawn++;
1013 if (value > peak_value) {
1014 peak_value = value;
1015 peak_point = newpoint;
1016 }
1017 }
1018
1019 /* If the peak value is significantly larger than the average, mark and label it */
1020 if (points_drawn > 0 && peak_value > TIMESTAMP_PRECISION / 100 && 2 * peak_value > 3 * value_sum / points_drawn) {
1021 ExtendedTextColour tc_peak{c_peak};
1022 GfxFillRect(peak_point.x - 1, peak_point.y - 1, peak_point.x + 1, peak_point.y + 1, c_peak);
1023 uint64_t value = peak_value * 1000 / TIMESTAMP_PRECISION;
1024 int label_y = std::max(y_max, peak_point.y - GetCharacterHeight(FontSize::Small));
1025 if (peak_point.x - x_zero > (int)this->graph_size.width / 2) {
1026 DrawString(x_zero, peak_point.x - WidgetDimensions::scaled.hsep_normal, label_y, GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, value), tc_peak, AlignmentH::ForceRight, false, FontSize::Small);
1027 } else {
1028 DrawString(peak_point.x + WidgetDimensions::scaled.hsep_normal, x_max, label_y, GetString(STR_FRAMERATE_GRAPH_MILLISECONDS, value), tc_peak, AlignmentH::ForceLeft, false, FontSize::Small);
1029 }
1030 }
1031 }
1032 }
1033};
1034
1037 WindowPosition::Automatic, "frametime_graph", 140, 90,
1038 WindowClass::FrametimeGraph, WindowClass::None,
1039 {},
1040 _frametime_graph_window_widgets
1041);
1042
1043
1044
1050
1060
1063{
1064 const int count1 = NUM_FRAMERATE_POINTS / 8;
1065 const int count2 = NUM_FRAMERATE_POINTS / 4;
1066 const int count3 = NUM_FRAMERATE_POINTS / 1;
1067
1068 IConsolePrint(TextColour::Silver, "Based on num. data points: {} {} {}", count1, count2, count3);
1069
1071 "Game loop",
1072 " GL station ticks",
1073 " GL train ticks",
1074 " GL road vehicle ticks",
1075 " GL ship ticks",
1076 " GL aircraft ticks",
1077 " GL landscape ticks",
1078 " GL link graph delays",
1079 "Drawing",
1080 " Viewport drawing",
1081 "Video output",
1082 "Sound mixing",
1083 "AI/GS scripts total",
1084 "Game script",
1085 };
1086 std::string ai_name_buf;
1087
1088 bool printed_anything = false;
1089
1091 auto &pf = _pf_data[e];
1092 if (pf.num_valid == 0) continue;
1093 IConsolePrint(TextColour::Green, "{} rate: {:.2f}fps (expected: {:.2f}fps)",
1094 MEASUREMENT_NAMES[e],
1095 pf.GetRate(),
1096 pf.expected_rate);
1097 printed_anything = true;
1098 }
1099
1101 auto &pf = _pf_data[e];
1102 if (pf.num_valid == 0) continue;
1103 std::string_view name;
1104 if (e < PerformanceElement::AI0) {
1105 name = MEASUREMENT_NAMES[e];
1106 } else {
1107 ai_name_buf = fmt::format("AI {} {}", GetAIIndex(e) + 1, GetAIName(e));
1108 name = ai_name_buf;
1109 }
1110 IConsolePrint(TextColour::LightBlue, "{} times: {:.2f}ms {:.2f}ms {:.2f}ms",
1111 name,
1112 pf.GetAverageDurationMilliseconds(count1),
1113 pf.GetAverageDurationMilliseconds(count2),
1114 pf.GetAverageDurationMilliseconds(count3));
1115 printed_anything = true;
1116 }
1117
1118 if (!printed_anything) {
1119 IConsolePrint(CC_ERROR, "No performance measurements have been taken yet.");
1120 }
1121}
1122
1131{
1132 if (_sound_perf_pending.load(std::memory_order_acquire)) {
1133 std::lock_guard lk(_sound_perf_lock);
1134 for (size_t i = 0; i < _sound_perf_measurements.size(); i += 2) {
1135 _pf_data[PerformanceElement::Sound].Add(_sound_perf_measurements[i], _sound_perf_measurements[i + 1]);
1136 }
1137 _sound_perf_measurements.clear();
1138 _sound_perf_pending.store(false, std::memory_order_relaxed);
1139 }
1140}
AIInfo keeps track of all information of an AI, like Author, Description, ...
The AIInstance tracks an AI.
Iterate a range of enum values.
static class GameInstance * GetInstance()
Get the current active instance.
Definition game.hpp:108
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
~PerformanceAccumulator()
Finish and add one block of the accumulating value.
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
PerformanceAccumulator(PerformanceElement elem)
Begin measuring one block of the accumulating value.
static void SetInactive(PerformanceElement elem)
Mark a performance element as not currently in use.
static void Paused(PerformanceElement elem)
Indicate that a cycle of "pause" where no processing occurs.
void SetExpectedRate(double rate)
Set the rate of expected cycles per second of a performance element.
PerformanceMeasurer(PerformanceElement elem)
Begin a cycle of a measured element.
~PerformanceMeasurer()
Finish a cycle of a measured element and store the measurement taken.
Scrollbar data structure.
void SetCount(size_t num)
Sets the number of elements in the list.
void SetCapacity(size_t capacity)
Set the capacity of visible elements.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
size_type GetPosition() const
Gets the position of the first visible element in the list.
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:94
Definition of stuff that is very close to a company, like the company struct itself.
void IConsolePrint(ExtendedTextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition console.cpp:91
Console functions used outside of the console code.
Globally used console related types.
static const TextColour CC_ERROR
Colour for error lines.
#define T
Climate temperate.
Definition engines.h:91
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
void ShowFramerateWindow()
Open the general framerate window.
static WindowDesc _framerate_display_desc(WindowPosition::Automatic, "framerate_display", 0, 0, WindowClass::FramerateDisplay, WindowClass::None, {}, _framerate_window_widgets)
Window definition for the frame rate window.
static TimingMeasurement GetPerformanceTimer()
Return a timestamp with TIMESTAMP_PRECISION ticks per second precision.
void ProcessPendingPerformanceMeasurements()
This drains the PerformanceElement::Sound measurement data queue into _pf_data.
void ShowFrametimeGraphWindow(PerformanceElement elem)
Open a graph window for a performance element.
static constexpr CompanyID GetAIIndex(PerformanceElement e)
Get the CompanyID associated with the AI of the given PerformanceElement.
void ConPrintFramerate()
Print performance statistics to game console.
static WindowDesc _frametime_graph_window_desc(WindowPosition::Automatic, "frametime_graph", 140, 90, WindowClass::FrametimeGraph, WindowClass::None, {}, _frametime_graph_window_widgets)
Window definition for the frame rate graph window.
static std::string_view GetAIName(PerformanceElement e)
Get the name of the AI of the given PerformanceElement.
static constexpr EnumIndexArray< PerformanceElement, PerformanceElement, PerformanceElement::End > DISPLAY_ORDER_PFE
Order of the performance elements in the user interface.
Types for recording game performance data.
PerformanceElement
Elements of game performance that can be measured.
@ AI7
AI execution for player slot 8.
@ GameLoopLandscape
Time spent processing other world features.
@ AI0
AI execution for player slot 1.
@ Video
Speed of painting drawn video buffer.
@ GameLoopRoadVehicles
Time spend processing road vehicles.
@ GameLoop
Speed of gameloop processing.
@ GameLoopShips
Time spent processing ships.
@ AI9
AI execution for player slot 10.
@ Drawing
Speed of drawing world and GUI.
@ AllScripts
Sum of all GS/AI scripts.
@ GameLoopAircraft
Time spent processing aircraft.
@ End
End of enum, must be last.
@ AI11
AI execution for player slot 12.
@ GameScript
Game script execution.
@ AI4
AI execution for player slot 5.
@ GameLoopTrains
Time spent processing trains.
@ Sound
Speed of mixing audio samples.
@ AI10
AI execution for player slot 11.
@ AI12
AI execution for player slot 13.
@ GameLoopEconomy
Time spent processing cargo movement.
@ AI3
AI execution for player slot 4.
@ ViewportDrawing
Time spent drawing world viewports in GUI.
@ AI13
AI execution for player slot 14.
@ AI5
AI execution for player slot 6.
@ AI14
AI execution for player slot 15.
@ GameLoopLinkGraph
Time spent waiting for link graph background jobs.
@ AI8
AI execution for player slot 9.
@ AI2
AI execution for player slot 3.
@ AI6
AI execution for player slot 7.
@ AI1
AI execution for player slot 2.
uint64_t TimingMeasurement
Type used to hold a performance timing measurement.
Types related to the framerate windows widgets.
Base functions for all Games.
The GameInstance tracks games.
@ ForceRight
Force align to the right.
@ Start
Align to the start, LTR/RTL aware.
@ ForceLeft
Force align to the left.
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
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:111
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
Functions related to the gfx engine.
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Grey
Grey.
Definition gfx_type.h:299
@ White
White colour.
Definition gfx_type.h:330
@ LightBlue
Light blue colour.
Definition gfx_type.h:331
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Grey
Grey colour.
Definition gfx_type.h:332
@ Green
Green colour.
Definition gfx_type.h:325
@ Silver
Silver colour.
Definition gfx_type.h:319
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:417
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
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 SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart SetTextStyle(TextColour colour, FontSize size=FontSize::Normal)
Widget part function for setting the text style.
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
const TimingMeasurement TIMESTAMP_PRECISION
Units a second is divided into in performance measurements
static const double GL_RATE
Game loop rate, cycles per second
const int NUM_FRAMERATE_POINTS
Number of data points to keep in buffer for each performance measurement.
static EnumIndexArray< PerformanceData, PerformanceElement, PerformanceElement::End > _pf_data
Storage for all performance element measurements.
size_t GetSoundPoolAllocatedMemory()
Get size of memory allocated to sound effects.
Functions related to NewGRF provided sounds.
static constexpr PixelColour PC_DARK_RED
Dark red palette colour.
static constexpr PixelColour PC_DARK_GREY
Dark grey palette colour.
static constexpr PixelColour PC_BLACK
Black palette colour.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Definition of base types and functions in a cross-platform compatible way.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static bool IsValidAiID(auto index)
Is this company a valid company, controlled by the computer (a NoAI program)?
T y
Y coordinate.
T x
X coordinate.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
void OnResize() override
Called after the window got resized.
void DrawElementTimesColumn(const Rect &r, StringID heading_str, const CachedDecimalArray &values) const
Render a column of formatted average durations.
CachedDecimal rate_drawing
cached drawing frame rate
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.
EnumIndexArray< CachedDecimal, PerformanceElement, PerformanceElement::End > CachedDecimalArray
Array of cached decimals.
CachedDecimalArray times_shortterm
cached short term average times
CachedDecimalArray times_longterm
cached long term average times
CachedDecimal speed_gameloop
cached game loop speed factor
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
const IntervalTimer< TimerWindow > update_interval
Update the window on a regular interval.
CachedDecimal rate_gameloop
cached game loop tick rate
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
static constexpr int MIN_ELEMENTS
smallest number of elements to display
int horizontal_scale
number of half-second units horizontally
void OnRealtimeTick(uint delta_ms) override
Called periodically.
void UpdateScale()
Recalculate the graph scaling factors based on current recorded data.
const IntervalTimer< TimerWindow > update_interval
Update the scaling on a regular interval.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Dimension graph_size
size of the main graph area (excluding axis labels)
PerformanceElement element
what element this window renders graph for
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.
static T Scinterlate(T dst_min, T dst_max, T src_min, T src_max, T value)
Scale and interpolate a value from a source range into a destination range.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
int vertical_scale
number of TIMESTAMP_PRECISION units vertically
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Company * Get(auto index)
Specification of a rectangle with absolute coordinates of all edges.
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
TimingMeasurement acc_duration
Current accumulated duration.
int next_index
Next index to write to in durations and timestamps.
std::array< TimingMeasurement, NUM_FRAMERATE_POINTS > durations
Time spent processing each cycle of the performance element, circular buffer.
void AddAccumulate(TimingMeasurement duration)
Accumulate a period onto the current measurement.
TimingMeasurement acc_timestamp
Start time for current accumulation cycle.
double GetAverageDurationMilliseconds(int count)
Get average cycle processing time over a number of data points.
double expected_rate
Expected number of cycles per second when the system is running without slowdowns.
int prev_index
Last index written to in durations and timestamps.
double GetRate()
Get current rate of a performance element, based on approximately the past one second of data.
int num_valid
Number of data points recorded, clamped to NUM_FRAMERATE_POINTS.
void AddPause(TimingMeasurement start_time)
Indicate a pause/expected discontinuity in processing the element.
PerformanceData(double expected_rate)
Initialize a data element with an expected collection rate.
static const TimingMeasurement INVALID_DURATION
Duration value indicating the value is not valid should be considered a gap in measurements.
void BeginAccumulate(TimingMeasurement start_time)
Begin an accumulation of multiple measurements into a single value, from a given start time.
std::array< TimingMeasurement, NUM_FRAMERATE_POINTS > timestamps
Start time of each cycle of the performance element, circular buffer.
void Add(TimingMeasurement start_time, TimingMeasurement end_time)
Collect a complete measurement, given start and ending times for a processing block.
Definition of Interval and OneShot timers.
Definition of the Window system.
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ 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_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:49
void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, bool schedule_resize)
Resize the window.
Definition window.cpp:2146
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:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.