Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ProfileViewer.h"
21 :
22 : #include "lib/code_annotation.h"
23 : #include "graphics/Canvas2D.h"
24 : #include "graphics/Color.h"
25 : #include "graphics/FontMetrics.h"
26 : #include "graphics/TextRenderer.h"
27 : #include "lib/external_libraries/libsdl.h"
28 : #include "lib/os_path.h"
29 : #include "lib/path.h"
30 : #include "maths/Rect.h"
31 : #include "maths/Size2D.h"
32 : #include "maths/Vector2D.h"
33 : #include "ps/CLogger.h"
34 : #include "ps/CStrIntern.h"
35 : #include "ps/Hotkey.h"
36 : #include "ps/Profile.h"
37 : #include "ps/Pyrogenesis.h"
38 : #include "ps/VideoMode.h"
39 : #include "scriptinterface/Object.h"
40 : #include "scriptinterface/Request.h"
41 :
42 : #include <SDL_events.h>
43 : #include <SDL_keycode.h>
44 : #include <algorithm>
45 : #include <ctime>
46 : #include <fmt/ostream.h>
47 : #include <fstream>
48 : #include <js/RootingAPI.h>
49 : #include <js/TypeDecls.h>
50 : #include <js/Value.h>
51 : #include <string>
52 :
53 : namespace Script { class Interface; }
54 :
55 : struct CProfileViewerInternals
56 : {
57 : NONCOPYABLE(CProfileViewerInternals); // because of the ofstream
58 : public:
59 11 : CProfileViewerInternals() {}
60 :
61 : /// Whether the profiling display is currently visible
62 : bool profileVisible;
63 :
64 : /// List of root tables
65 : std::vector<AbstractProfileTable*> rootTables;
66 :
67 : /// Path from a root table (path[0]) to the currently visible table (path[size-1])
68 : std::vector<AbstractProfileTable*> path;
69 :
70 : /// Helper functions
71 : void TableIsDeleted(AbstractProfileTable* table);
72 : void NavigateTree(int id);
73 :
74 : void SaveToFile();
75 :
76 : /// File for saved profile output (reset when the game is restarted)
77 : std::ofstream outputStream;
78 :
79 : /**
80 : * Input: Filter and handle any input events that the profile display is
81 : * interested in.
82 : *
83 : * In particular, this function handles enable/disable of the profile
84 : * display as well as navigating the information tree.
85 : */
86 : struct InputHandler
87 : {
88 : CProfileViewerInternals& profileViewer;
89 : Input::Reaction operator()(const SDL_Event& ev);
90 : };
91 : Input::Handler<InputHandler> inputHandler{g_VideoMode.m_InputManager, Input::Slot::PROFILE_VIEWER,
92 : {*this}};
93 : };
94 :
95 :
96 : ///////////////////////////////////////////////////////////////////////////////////////////////
97 : // AbstractProfileTable implementation
98 :
99 46 : AbstractProfileTable::~AbstractProfileTable()
100 : {
101 46 : if (CProfileViewer::IsInitialised())
102 : {
103 46 : g_ProfileViewer.m->TableIsDeleted(this);
104 : }
105 46 : }
106 :
107 :
108 : ///////////////////////////////////////////////////////////////////////////////////////////////
109 : // CProfileViewer implementation
110 :
111 :
112 : // AbstractProfileTable got deleted, make sure we have no dangling pointers
113 46 : void CProfileViewerInternals::TableIsDeleted(AbstractProfileTable* table)
114 : {
115 102 : for(int idx = (int)rootTables.size()-1; idx >= 0; --idx)
116 : {
117 56 : if (rootTables[idx] == table)
118 21 : rootTables.erase(rootTables.begin() + idx);
119 : }
120 :
121 46 : for(size_t idx = 0; idx < path.size(); ++idx)
122 : {
123 0 : if (path[idx] != table)
124 0 : continue;
125 :
126 0 : path.erase(path.begin() + idx, path.end());
127 0 : if (path.size() == 0)
128 0 : profileVisible = false;
129 : }
130 46 : }
131 :
132 :
133 : // Move into child tables or return to parent tables based on the given number
134 0 : void CProfileViewerInternals::NavigateTree(int id)
135 : {
136 0 : if (id == 0)
137 : {
138 0 : if (path.size() > 1)
139 0 : path.pop_back();
140 : }
141 : else
142 : {
143 0 : AbstractProfileTable* table = path[path.size() - 1];
144 0 : size_t numrows = table->GetNumberRows();
145 :
146 0 : for(size_t row = 0; row < numrows; ++row)
147 : {
148 0 : AbstractProfileTable* child = table->GetChild(row);
149 :
150 0 : if (!child)
151 0 : continue;
152 :
153 0 : --id;
154 0 : if (id == 0)
155 : {
156 0 : path.push_back(child);
157 0 : break;
158 : }
159 : }
160 : }
161 0 : }
162 :
163 :
164 : // Construction/Destruction
165 11 : CProfileViewer::CProfileViewer()
166 : {
167 11 : m = new CProfileViewerInternals;
168 11 : m->profileVisible = false;
169 11 : }
170 :
171 11 : CProfileViewer::~CProfileViewer()
172 : {
173 11 : delete m;
174 11 : }
175 :
176 :
177 : // Render
178 0 : void CProfileViewer::RenderProfile(CCanvas2D& canvas)
179 : {
180 0 : if (!m->profileVisible)
181 0 : return;
182 :
183 0 : if (m->path.empty())
184 : {
185 0 : m->profileVisible = false;
186 0 : return;
187 : }
188 :
189 0 : PROFILE3("profile viewer");
190 :
191 0 : AbstractProfileTable* table = m->path[m->path.size() - 1];
192 0 : const std::vector<ProfileColumn>& columns = table->GetColumns();
193 0 : size_t numrows = table->GetNumberRows();
194 :
195 0 : CStrIntern font_name("mono-stroke-10");
196 0 : CFontMetrics font(font_name);
197 0 : int height = font.GetHeight();
198 :
199 : // Render background.
200 0 : float estimateWidth = 50.0f;
201 0 : for (const ProfileColumn& column : columns)
202 0 : estimateWidth += static_cast<float>(column.width);
203 :
204 0 : float estimateHeight = 3 + static_cast<float>(numrows);
205 0 : if (m->path.size() > 1)
206 0 : estimateHeight += 2;
207 0 : estimateHeight *= height;
208 :
209 0 : canvas.DrawRect(CRect(CSize2D(estimateWidth, estimateHeight)), CColor(0.0f, 0.0f, 0.0f, 0.5f));
210 :
211 : // Draw row backgrounds.
212 0 : for (size_t row = 0; row < numrows; ++row)
213 : {
214 0 : canvas.DrawRect(
215 0 : CRect(CVector2D(0.0f, height * (2.0f + row) + 2.0f), CSize2D(estimateWidth, height)),
216 0 : row % 2 ? CColor(1.0f, 1.0f, 1.0f, 0.1f): CColor(0.0f, 0.0f, 0.0f, 0.1f));
217 : }
218 :
219 : // Print table and column titles.
220 0 : CTextRenderer textRenderer;
221 0 : textRenderer.SetCurrentFont(font_name, CStrIntern{});
222 0 : textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
223 0 : textRenderer.PrintfAt(2.0f, height, L"%hs", table->GetTitle().c_str());
224 0 : textRenderer.Translate(22.0f, height*2.0f);
225 :
226 : float colX = 0.0f;
227 0 : for (size_t col = 0; col < columns.size(); ++col)
228 : {
229 0 : CStrW text = columns[col].title.FromUTF8();
230 0 : float w, h;
231 0 : font.CalculateStringSize(text.c_str(), w, h);
232 :
233 0 : float x = colX;
234 0 : if (col > 0) // right-align all but the first column
235 0 : x += columns[col].width - w;
236 0 : textRenderer.Put(x, 0.0f, text.c_str());
237 :
238 0 : colX += columns[col].width;
239 0 : }
240 :
241 0 : textRenderer.Translate(0.0f, height);
242 :
243 : // Print rows
244 : int currentExpandId = 1;
245 :
246 0 : for (size_t row = 0; row < numrows; ++row)
247 : {
248 0 : if (table->IsHighlightRow(row))
249 0 : textRenderer.SetCurrentColor(CColor(1.0f, 0.5f, 0.5f, 1.0f));
250 : else
251 0 : textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
252 :
253 0 : if (table->GetChild(row))
254 : {
255 0 : textRenderer.PrintfAt(-15.0f, 0.0f, L"%d", currentExpandId);
256 0 : currentExpandId++;
257 : }
258 :
259 0 : float rowColX = 0.0f;
260 0 : for (size_t col = 0; col < columns.size(); ++col)
261 : {
262 0 : const CStrW text{table->GetCellText(row, col).FromUTF8()};
263 0 : if (!text.empty())
264 : {
265 0 : float w, h;
266 0 : font.CalculateStringSize(text.c_str(), w, h);
267 :
268 0 : float x = rowColX;
269 0 : if (col > 0) // right-align all but the first column
270 0 : x += columns[col].width - w;
271 0 : textRenderer.Put(x, 0.0f, text.c_str());
272 : }
273 0 : rowColX += columns[col].width;
274 0 : }
275 :
276 0 : textRenderer.Translate(0.0f, height);
277 : }
278 :
279 0 : textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
280 :
281 0 : if (m->path.size() > 1)
282 : {
283 0 : textRenderer.Translate(0.0f, height);
284 0 : textRenderer.Put(-15.0f, 0.0f, L"0");
285 0 : textRenderer.Put(0.0f, 0.0f, L"back to parent");
286 : }
287 :
288 0 : canvas.DrawText(textRenderer);
289 0 : }
290 :
291 :
292 : // Handle input
293 0 : Input::Reaction CProfileViewerInternals::InputHandler::operator()(const SDL_Event& ev)
294 : {
295 0 : switch(ev.type)
296 : {
297 0 : case SDL_KEYDOWN:
298 0 : {
299 0 : if (!profileViewer.profileVisible)
300 : break;
301 :
302 0 : int k = ev.key.keysym.sym;
303 0 : if (k >= SDLK_0 && k <= SDLK_9)
304 : {
305 0 : profileViewer.NavigateTree(k - SDLK_0);
306 0 : return Input::Reaction::HANDLED;
307 : }
308 : break;
309 : }
310 0 : case SDL_HOTKEYPRESS:
311 0 : std::string_view hotkey = static_cast<const char*>(ev.user.data1);
312 :
313 0 : if (hotkey == "profile.toggle")
314 : {
315 0 : if (!profileViewer.profileVisible)
316 : {
317 0 : if (profileViewer.rootTables.size())
318 : {
319 0 : profileViewer.profileVisible = true;
320 0 : profileViewer.path.push_back(profileViewer.rootTables[0]);
321 : }
322 : }
323 : else
324 : {
325 : size_t i;
326 :
327 0 : for(i = 0; i < profileViewer.rootTables.size(); ++i)
328 : {
329 0 : if (profileViewer.rootTables[i] == profileViewer.path[0])
330 : break;
331 : }
332 0 : i++;
333 :
334 0 : profileViewer.path.clear();
335 0 : if (i < profileViewer.rootTables.size())
336 : {
337 0 : profileViewer.path.push_back(profileViewer.rootTables[i]);
338 : }
339 : else
340 : {
341 0 : profileViewer.profileVisible = false;
342 : }
343 : }
344 0 : return Input::Reaction::HANDLED;
345 : }
346 0 : else if( hotkey == "profile.save" )
347 : {
348 0 : profileViewer.SaveToFile();
349 0 : return Input::Reaction::HANDLED;
350 : }
351 : break;
352 : }
353 : return Input::Reaction::PASS;
354 : }
355 :
356 : // Add a table to the list of roots
357 21 : void CProfileViewer::AddRootTable(AbstractProfileTable* table, bool front)
358 : {
359 21 : if (front)
360 1 : m->rootTables.insert(m->rootTables.begin(), table);
361 : else
362 20 : m->rootTables.push_back(table);
363 21 : }
364 :
365 : namespace
366 : {
367 : class WriteTable
368 : {
369 : public:
370 0 : WriteTable(std::ofstream& outputStream) : m_OutputStream(outputStream) {}
371 : WriteTable(const WriteTable& writeTable) = default;
372 :
373 0 : void operator() (AbstractProfileTable* table)
374 : {
375 0 : std::vector<CStr> data; // 2d array of (rows+head)*columns elements
376 :
377 0 : const std::vector<ProfileColumn>& columns = table->GetColumns();
378 :
379 : // Add column headers to 'data'
380 0 : for (std::vector<ProfileColumn>::const_iterator col_it = columns.begin();
381 0 : col_it != columns.end(); ++col_it)
382 0 : data.push_back(col_it->title);
383 :
384 : // Recursively add all profile data to 'data'
385 0 : WriteRows(1, table, data);
386 :
387 : // Calculate the width of each column ( = the maximum width of
388 : // any value in that column)
389 0 : std::vector<size_t> columnWidths;
390 0 : size_t cols = columns.size();
391 0 : for (size_t c = 0; c < cols; ++c)
392 : {
393 0 : size_t max = 0;
394 0 : for (size_t i = c; i < data.size(); i += cols)
395 0 : max = std::max(max, data[i].length());
396 0 : columnWidths.push_back(max);
397 : }
398 :
399 : // Output data as a formatted table:
400 :
401 0 : m_OutputStream << "\n\n" << table->GetTitle() << "\n";
402 :
403 0 : if (cols == 0) // avoid divide-by-zero
404 0 : return;
405 :
406 0 : for (size_t r = 0; r < data.size()/cols; ++r)
407 : {
408 0 : for (size_t c = 0; c < cols; ++c)
409 0 : fmt::print(m_OutputStream, "{}{:<{}}", c ? " | " : "\n", data[r * cols + c],
410 0 : columnWidths[c]);
411 :
412 : // Add dividers under some rows. (Currently only the first, since
413 : // that contains the column headers.)
414 0 : if (r == 0)
415 0 : for (size_t c = 0; c < cols; ++c)
416 0 : m_OutputStream << (c ? "-|-" : "\n")
417 0 : << CStr::Repeat("-", columnWidths[c]);
418 : }
419 0 : }
420 :
421 0 : void WriteRows(int indent, AbstractProfileTable* table, std::vector<CStr>& data)
422 : {
423 0 : const std::vector<ProfileColumn>& columns = table->GetColumns();
424 :
425 0 : for (size_t r = 0; r < table->GetNumberRows(); ++r)
426 : {
427 : // Do pretty tree-structure indenting
428 0 : CStr indentation = CStr::Repeat("| ", indent-1);
429 0 : if (r+1 == table->GetNumberRows())
430 0 : indentation += "'-";
431 : else
432 0 : indentation += "|-";
433 :
434 0 : for (size_t c = 0; c < columns.size(); ++c)
435 0 : if (c == 0)
436 0 : data.push_back(indentation + table->GetCellText(r, c));
437 : else
438 0 : data.push_back(table->GetCellText(r, c));
439 :
440 0 : if (table->GetChild(r))
441 0 : WriteRows(indent+1, table->GetChild(r), data);
442 0 : }
443 0 : }
444 :
445 : private:
446 : std::ofstream& m_OutputStream;
447 : const WriteTable& operator=(const WriteTable&);
448 : };
449 :
450 : struct DumpTable
451 : {
452 : const Script::Interface& m_ScriptInterface;
453 : JS::PersistentRooted<JS::Value> m_Root;
454 : DumpTable(const Script::Interface& scriptInterface, JS::HandleValue root) :
455 : m_ScriptInterface(scriptInterface)
456 : {
457 : Script::Request rq(scriptInterface);
458 : m_Root.init(rq.cx, root);
459 : }
460 :
461 : // std::for_each requires a move constructor and the use of JS::PersistentRooted<T> apparently breaks a requirement for an
462 : // automatic move constructor
463 : DumpTable(DumpTable && original) :
464 : m_ScriptInterface(original.m_ScriptInterface)
465 : {
466 : Script::Request rq(m_ScriptInterface);
467 : m_Root.init(rq.cx, original.m_Root.get());
468 : }
469 :
470 : void operator() (AbstractProfileTable* table)
471 : {
472 : Script::Request rq(m_ScriptInterface);
473 :
474 : JS::RootedValue t(rq.cx);
475 : Script::CreateObject(
476 : rq,
477 : &t,
478 : "cols", DumpCols(table),
479 : "data", DumpRows(table));
480 :
481 : Script::SetProperty(rq, m_Root, table->GetTitle().c_str(), t);
482 : }
483 :
484 : std::vector<std::string> DumpCols(AbstractProfileTable* table)
485 : {
486 : std::vector<std::string> titles;
487 :
488 : const std::vector<ProfileColumn>& columns = table->GetColumns();
489 :
490 : for (size_t c = 0; c < columns.size(); ++c)
491 : titles.push_back(columns[c].title);
492 :
493 : return titles;
494 : }
495 :
496 : JS::Value DumpRows(AbstractProfileTable* table)
497 : {
498 : Script::Request rq(m_ScriptInterface);
499 :
500 : JS::RootedValue data(rq.cx);
501 : Script::CreateObject(rq, &data);
502 :
503 : const std::vector<ProfileColumn>& columns = table->GetColumns();
504 :
505 : for (size_t r = 0; r < table->GetNumberRows(); ++r)
506 : {
507 : JS::RootedValueVector row{rq.cx};
508 : if (!row.resize(columns.size() + 1))
509 : throw std::runtime_error{"Resize failed"};
510 :
511 : Script::SetProperty(rq, data, table->GetCellText(r, 0).c_str(), row);
512 :
513 : if (table->GetChild(r))
514 : {
515 : JS::RootedValue childRows(rq.cx, DumpRows(table->GetChild(r)));
516 : row[0].set(childRows);
517 : }
518 :
519 : for (size_t c = 1; c < columns.size(); ++c)
520 : {
521 : row[c].set(JS::StringValue(
522 : JS_NewStringCopyZ(rq.cx, table->GetCellText(r, c).c_str())));
523 : }
524 : }
525 :
526 : return data;
527 : }
528 :
529 : private:
530 : const DumpTable& operator=(const DumpTable&);
531 : };
532 :
533 0 : bool SortByName(AbstractProfileTable* a, AbstractProfileTable* b)
534 : {
535 0 : return (a->GetName() < b->GetName());
536 : }
537 : }
538 :
539 0 : void CProfileViewer::SaveToFile()
540 : {
541 0 : m->SaveToFile();
542 0 : }
543 :
544 0 : void CProfileViewerInternals::SaveToFile()
545 : {
546 : // Open the file, if necessary. If this method is called several times,
547 : // the profile results will be appended to the previous ones from the same
548 : // run.
549 0 : if (!outputStream.is_open())
550 : {
551 : // Open the file. (It will be closed when the CProfileViewer
552 : // destructor is called.)
553 0 : const OsPath filePath{psLogDir()/"profile.txt"};
554 0 : outputStream.open(OsString(filePath), std::ofstream::out | std::ofstream::trunc);
555 :
556 0 : if (outputStream.fail())
557 : {
558 0 : LOGERROR("Failed to open profile log file");
559 0 : return;
560 : }
561 : else
562 : {
563 0 : LOGMESSAGERENDER("Profiler snapshot saved to '{}'", filePath.string8());
564 : }
565 0 : }
566 :
567 0 : time_t t;
568 0 : time(&t);
569 0 : outputStream << "================================================================\n\n";
570 0 : outputStream << "PS profiler snapshot - " << asctime(localtime(&t));
571 :
572 0 : std::vector<AbstractProfileTable*> tables = rootTables;
573 0 : sort(tables.begin(), tables.end(), SortByName);
574 0 : for_each(tables.begin(), tables.end(), WriteTable(outputStream));
575 :
576 0 : outputStream << "\n\n================================================================\n";
577 0 : outputStream.flush();
578 0 : }
579 :
580 0 : void CProfileViewer::ShowTable(const CStr& table)
581 : {
582 0 : m->path.clear();
583 :
584 0 : if (table.length() > 0)
585 : {
586 0 : for (size_t i = 0; i < m->rootTables.size(); ++i)
587 : {
588 0 : if (m->rootTables[i]->GetName() == table)
589 : {
590 0 : m->path.push_back(m->rootTables[i]);
591 0 : m->profileVisible = true;
592 0 : return;
593 : }
594 : }
595 : }
596 :
597 : // No matching table found, so don't display anything
598 0 : m->profileVisible = false;
599 : }
|