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 "Renderer.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/Canvas2D.h"
24 : #include "graphics/CinemaManager.h"
25 : #include "graphics/Color.h"
26 : #include "graphics/FontManager.h"
27 : #include "graphics/GameView.h"
28 : #include "graphics/ModelDef.h"
29 : #include "graphics/ShaderManager.h"
30 : #include "graphics/TerrainTextureManager.h"
31 : #include "graphics/TextureManager.h"
32 : #include "gui/GUIManager.h"
33 : #include "i18n/L10n.h"
34 : #include "lib/alignment.h"
35 : #include "lib/allocators/shared_ptr.h"
36 : #include "lib/code_annotation.h"
37 : #include "lib/debug.h"
38 : #include "lib/file/vfs/vfs.h"
39 : #include "lib/file/vfs/vfs_path.h"
40 : #include "lib/file/vfs/vfs_util.h"
41 : #include "lib/hash.h"
42 : #include "lib/os_path.h"
43 : #include "lib/secure_crt.h"
44 : #include "lib/status.h"
45 : #include "lib/tex/tex.h"
46 : #include "maths/Matrix3D.h"
47 : #include "ps/CConsole.h"
48 : #include "ps/CLogger.h"
49 : #include "ps/CStr.h"
50 : #include "ps/ConfigDB.h"
51 : #include "ps/Filesystem.h"
52 : #include "ps/Game.h"
53 : #include "ps/GameSetup/Config.h"
54 : #include "ps/Globals.h"
55 : #include "ps/memory/LinearAllocator.h"
56 : #include "ps/Hotkey.h"
57 : #include "ps/Profile.h"
58 : #include "ps/ProfileViewer.h"
59 : #include "ps/Profiler2.h"
60 : #include "ps/Util.h"
61 : #include "ps/VideoMode.h"
62 : #include "ps/World.h"
63 : #include "renderer/DebugRenderer.h"
64 : #include "renderer/PostprocManager.h"
65 : #include "renderer/RenderingOptions.h"
66 : #include "renderer/SceneRenderer.h"
67 : #include "renderer/TimeManager.h"
68 : #include "renderer/VertexBufferManager.h"
69 : #include "renderer/backend/Backend.h"
70 : #include "renderer/backend/IDevice.h"
71 : #include "renderer/backend/IDeviceCommandContext.h"
72 : #include "renderer/backend/IFramebuffer.h"
73 : #include "renderer/backend/IShaderProgram.h"
74 : #include "renderer/backend/ISwapChain.h"
75 : #include "tools/atlas/GameInterface/GameLoop.h"
76 : #include "tools/atlas/GameInterface/View.h"
77 :
78 : #include <SDL_events.h>
79 : #include <cstdlib>
80 : #include <string>
81 : #include <unordered_map>
82 : #include <utility>
83 : #include <vector>
84 :
85 : namespace
86 : {
87 :
88 : size_t g_NextScreenShotNumber = 0;
89 :
90 : ///////////////////////////////////////////////////////////////////////////////////
91 : // CRendererStatsTable - Profile display of rendering stats
92 :
93 : /**
94 : * Class CRendererStatsTable: Implementation of AbstractProfileTable to
95 : * display the renderer stats in-game.
96 : *
97 : * Accesses CRenderer::m_Stats by keeping the reference passed to the
98 : * constructor.
99 : */
100 0 : class CRendererStatsTable : public AbstractProfileTable
101 : {
102 : NONCOPYABLE(CRendererStatsTable);
103 : public:
104 : CRendererStatsTable(const CRenderer::Stats& st, const PS::Memory::LinearAllocator& linearAllocator);
105 :
106 : // Implementation of AbstractProfileTable interface
107 : CStr GetName() override;
108 : CStr GetTitle() override;
109 : size_t GetNumberRows() override;
110 : const std::vector<ProfileColumn>& GetColumns() override;
111 : CStr GetCellText(size_t row, size_t col) override;
112 : AbstractProfileTable* GetChild(size_t row) override;
113 :
114 : private:
115 : /// Reference to the renderer singleton's stats
116 : const CRenderer::Stats& Stats;
117 : const PS::Memory::LinearAllocator& m_LinearAllocator;
118 :
119 : /// Column descriptions
120 : std::vector<ProfileColumn> columnDescriptions;
121 :
122 : enum
123 : {
124 : Row_DrawCalls = 0,
125 : Row_TerrainTris,
126 : Row_WaterTris,
127 : Row_ModelTris,
128 : Row_OverlayTris,
129 : Row_BlendSplats,
130 : Row_Particles,
131 : Row_VBReserved,
132 : Row_VBAllocated,
133 : Row_TextureMemory,
134 : Row_ShadersLoaded,
135 : Row_LinearAllocator,
136 :
137 : // Must be last to count number of rows
138 : NumberRows
139 : };
140 : };
141 :
142 : // Construction
143 10 : CRendererStatsTable::CRendererStatsTable(const CRenderer::Stats& st, const PS::Memory::LinearAllocator& linearAllocator)
144 10 : : Stats(st), m_LinearAllocator(linearAllocator)
145 : {
146 10 : columnDescriptions.push_back(ProfileColumn("Name", 230));
147 10 : columnDescriptions.push_back(ProfileColumn("Value", 100));
148 10 : }
149 :
150 : // Implementation of AbstractProfileTable interface
151 0 : CStr CRendererStatsTable::GetName()
152 : {
153 0 : return "renderer";
154 : }
155 :
156 0 : CStr CRendererStatsTable::GetTitle()
157 : {
158 0 : return "Renderer statistics";
159 : }
160 :
161 0 : size_t CRendererStatsTable::GetNumberRows()
162 : {
163 0 : return NumberRows;
164 : }
165 :
166 0 : const std::vector<ProfileColumn>& CRendererStatsTable::GetColumns()
167 : {
168 0 : return columnDescriptions;
169 : }
170 :
171 0 : CStr CRendererStatsTable::GetCellText(size_t row, size_t col)
172 : {
173 0 : char buf[256];
174 :
175 0 : switch(row)
176 : {
177 0 : case Row_DrawCalls:
178 0 : if (col == 0)
179 0 : return "# draw calls";
180 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_DrawCalls);
181 0 : return buf;
182 :
183 0 : case Row_TerrainTris:
184 0 : if (col == 0)
185 0 : return "# terrain tris";
186 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_TerrainTris);
187 0 : return buf;
188 :
189 0 : case Row_WaterTris:
190 0 : if (col == 0)
191 0 : return "# water tris";
192 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_WaterTris);
193 0 : return buf;
194 :
195 0 : case Row_ModelTris:
196 0 : if (col == 0)
197 0 : return "# model tris";
198 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_ModelTris);
199 0 : return buf;
200 :
201 0 : case Row_OverlayTris:
202 0 : if (col == 0)
203 0 : return "# overlay tris";
204 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_OverlayTris);
205 0 : return buf;
206 :
207 0 : case Row_BlendSplats:
208 0 : if (col == 0)
209 0 : return "# blend splats";
210 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_BlendSplats);
211 0 : return buf;
212 :
213 0 : case Row_Particles:
214 0 : if (col == 0)
215 0 : return "# particles";
216 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)Stats.m_Particles);
217 0 : return buf;
218 :
219 0 : case Row_VBReserved:
220 0 : if (col == 0)
221 0 : return "VB reserved";
222 0 : sprintf_s(buf, sizeof(buf), "%lu kB", static_cast<unsigned long>(g_Renderer.GetVertexBufferManager().GetBytesReserved() / 1024));
223 0 : return buf;
224 :
225 0 : case Row_VBAllocated:
226 0 : if (col == 0)
227 0 : return "VB allocated";
228 0 : sprintf_s(buf, sizeof(buf), "%lu kB", static_cast<unsigned long>(g_Renderer.GetVertexBufferManager().GetBytesAllocated() / 1024));
229 0 : return buf;
230 :
231 0 : case Row_TextureMemory:
232 0 : if (col == 0)
233 0 : return "textures uploaded";
234 0 : sprintf_s(buf, sizeof(buf), "%lu kB", (unsigned long)g_Renderer.GetTextureManager().GetBytesUploaded() / 1024);
235 0 : return buf;
236 :
237 0 : case Row_ShadersLoaded:
238 0 : if (col == 0)
239 0 : return "shader effects loaded";
240 0 : sprintf_s(buf, sizeof(buf), "%lu", (unsigned long)g_Renderer.GetShaderManager().GetNumEffectsLoaded());
241 0 : return buf;
242 :
243 0 : case Row_LinearAllocator:
244 0 : if (col == 0)
245 0 : return "linear allocator";
246 0 : sprintf_s(buf, sizeof(buf), "%lu", static_cast<unsigned long>(m_LinearAllocator.GetCapacity()));
247 0 : return buf;
248 :
249 0 : default:
250 0 : return "???";
251 : }
252 : }
253 :
254 0 : AbstractProfileTable* CRendererStatsTable::GetChild(size_t /*row*/)
255 : {
256 0 : return 0;
257 : }
258 :
259 : class CRendererBackendStatsTable : public AbstractProfileTable
260 : {
261 : public:
262 10 : CRendererBackendStatsTable(const Renderer::Backend::IDevice& device)
263 10 : : m_Device(device)
264 : {
265 10 : m_ColumnDescriptions.push_back(ProfileColumn("Name", 230));
266 10 : m_ColumnDescriptions.push_back(ProfileColumn("Value", 100));
267 10 : }
268 :
269 0 : CStr GetName() override { return "renderer.backend"; }
270 0 : CStr GetTitle() override { return "Renderer backend statistics"; }
271 0 : size_t GetNumberRows() override { UpdateIfNeeded(); return m_Statistics.size(); }
272 0 : const std::vector<ProfileColumn>& GetColumns() override { return m_ColumnDescriptions; }
273 0 : AbstractProfileTable* GetChild(size_t) override { return nullptr; }
274 :
275 0 : CStr GetCellText(size_t row, size_t col) override
276 : {
277 0 : UpdateIfNeeded();
278 0 : if (row >= m_Statistics.size() || col > 2)
279 0 : return "";
280 0 : if (col == 0)
281 0 : return CStr(m_Statistics[row].name);
282 0 : return std::visit(
283 0 : []<typename T>(const T& value) -> std::string
284 : {
285 0 : return std::to_string(value);
286 : },
287 0 : m_Statistics[row].value) + " " + CStr{m_Statistics[row].unit};
288 : }
289 :
290 0 : void MakeOutdated() { m_Outdated = true; }
291 :
292 : private:
293 0 : void UpdateIfNeeded()
294 : {
295 0 : if (!m_Outdated)
296 : return;
297 0 : m_Outdated = false;
298 0 : m_Statistics.clear();
299 0 : m_Device.CollectStatistics(m_Statistics);
300 : }
301 :
302 : const Renderer::Backend::IDevice& m_Device;
303 :
304 : std::vector<ProfileColumn> m_ColumnDescriptions;
305 : Renderer::Backend::IDevice::StatisticsVector m_Statistics;
306 :
307 : // We need to recalculate statistics only when a new frame happened.
308 : bool m_Outdated{true};
309 : };
310 :
311 : } // anonymous namespace
312 :
313 : ///////////////////////////////////////////////////////////////////////////////////
314 : // CRenderer implementation
315 :
316 : /**
317 : * Struct CRendererInternals: Truly hide data that is supposed to be hidden
318 : * in this structure so it won't even appear in header files.
319 : */
320 : class CRenderer::Internals
321 : {
322 : NONCOPYABLE(Internals);
323 : public:
324 : Renderer::Backend::IDevice* device;
325 :
326 : std::unique_ptr<Renderer::Backend::IDeviceCommandContext> deviceCommandContext;
327 :
328 : /// true if CRenderer::Open has been called
329 : bool IsOpen;
330 :
331 : /// true if shaders need to be reloaded
332 : bool ShadersDirty;
333 :
334 : /// Table to display renderer stats in-game via profile system
335 : CRendererStatsTable profileTable;
336 : CRendererBackendStatsTable backendProfileTable;
337 :
338 : /// Shader manager
339 : CShaderManager shaderManager;
340 :
341 : /// Texture manager
342 : CTextureManager textureManager;
343 :
344 : CVertexBufferManager vertexBufferManager;
345 :
346 : /// Time manager
347 : CTimeManager timeManager;
348 :
349 : /// Postprocessing effect manager
350 : CPostprocManager postprocManager;
351 :
352 : CSceneRenderer sceneRenderer;
353 :
354 : CDebugRenderer debugRenderer;
355 :
356 : CFontManager fontManager;
357 :
358 : // During rendering we need to collect and sort many objects. To reduce
359 : // the allocation cost and increase cache locality we use the
360 : // LinearAllocator.
361 : // If we need to have more than 16MiB of continious memory then we're doing
362 : // a lot of unnecessary work.
363 : PS::Memory::LinearAllocator linearAllocator{1 * MiB, 16 * MiB};
364 :
365 : struct VertexAttributesHash
366 : {
367 : size_t operator()(const std::vector<Renderer::Backend::SVertexAttributeFormat>& attributes) const;
368 : };
369 :
370 : std::unordered_map<
371 : std::vector<Renderer::Backend::SVertexAttributeFormat>,
372 : std::unique_ptr<Renderer::Backend::IVertexInputLayout>, VertexAttributesHash> vertexInputLayouts;
373 :
374 : ScreenShotType m_ScreenShotType{ScreenShotType::NONE};
375 :
376 : struct InputHandler
377 : {
378 : ScreenShotType& screenshotType;
379 :
380 0 : Input::Reaction operator()(const SDL_Event& ev)
381 : {
382 0 : if (ev.type != SDL_HOTKEYPRESS)
383 : return Input::Reaction::PASS;
384 :
385 0 : std::string_view hotkey{static_cast<const char*>(ev.user.data1)};
386 0 : if (hotkey == "screenshot")
387 : {
388 0 : screenshotType = ScreenShotType::DEFAULT;
389 0 : return Input::Reaction::HANDLED;
390 : }
391 0 : if (hotkey == "bigscreenshot")
392 : {
393 0 : screenshotType = ScreenShotType::BIG;
394 0 : return Input::Reaction::HANDLED;
395 : }
396 : return Input::Reaction::PASS;
397 : }
398 : };
399 :
400 : Input::Handler<InputHandler> m_InputHandler{g_VideoMode.m_InputManager, Input::Slot::SCREENSHOT,
401 : {m_ScreenShotType}};
402 :
403 10 : Internals(Renderer::Backend::IDevice* device) :
404 10 : device(device),
405 10 : deviceCommandContext(device->CreateCommandContext()),
406 10 : IsOpen(false), ShadersDirty(true), profileTable(g_Renderer.m_Stats, linearAllocator),
407 10 : backendProfileTable(*device),
408 20 : shaderManager(device), textureManager(g_VFS, false, device), vertexBufferManager(device),
409 10 : postprocManager(device), sceneRenderer(device), fontManager(device)
410 : {
411 10 : }
412 : };
413 :
414 160 : size_t CRenderer::Internals::VertexAttributesHash::operator()(
415 : const std::vector<Renderer::Backend::SVertexAttributeFormat>& attributes) const
416 : {
417 160 : size_t seed = 0;
418 160 : hash_combine(seed, attributes.size());
419 530 : for (const Renderer::Backend::SVertexAttributeFormat& attribute : attributes)
420 : {
421 370 : hash_combine(seed, attribute.stream);
422 370 : hash_combine(seed, attribute.format);
423 370 : hash_combine(seed, attribute.offset);
424 370 : hash_combine(seed, attribute.stride);
425 370 : hash_combine(seed, attribute.rate);
426 370 : hash_combine(seed, attribute.bindingSlot);
427 : }
428 160 : return seed;
429 : }
430 :
431 10 : CRenderer::CRenderer(Renderer::Backend::IDevice* device)
432 : {
433 10 : PROFILE2("InitRenderer");
434 :
435 10 : m = std::make_unique<Internals>(device);
436 :
437 10 : g_ProfileViewer.AddRootTable(&m->profileTable);
438 10 : g_ProfileViewer.AddRootTable(&m->backendProfileTable);
439 :
440 10 : m_Width = 0;
441 10 : m_Height = 0;
442 :
443 10 : m_Stats.Reset();
444 :
445 : // Create terrain related stuff.
446 10 : new CTerrainTextureManager(device);
447 :
448 10 : Open(g_VideoMode.GetWindowWidth(), g_VideoMode.GetWindowHeight());
449 :
450 : // Setup lighting environment. Since the Renderer accesses the
451 : // lighting environment through a pointer, this has to be done before
452 : // the first Frame.
453 10 : GetSceneRenderer().SetLightEnv(&g_LightEnv);
454 :
455 10 : ModelDefActivateFastImpl();
456 10 : ColorActivateFastImpl();
457 10 : }
458 :
459 10 : CRenderer::~CRenderer()
460 : {
461 10 : PROFILE2("~CRenderer");
462 10 : delete &g_TexMan;
463 :
464 : // We no longer UnloadWaterTextures here -
465 : // that is the responsibility of the module that asked for
466 : // them to be loaded (i.e. CGameView).
467 10 : m.reset();
468 10 : }
469 :
470 0 : void CRenderer::ReloadShaders()
471 : {
472 0 : ENSURE(m->IsOpen);
473 :
474 0 : m->sceneRenderer.ReloadShaders(m->device);
475 0 : m->ShadersDirty = false;
476 0 : }
477 :
478 10 : bool CRenderer::Open(const uint32_t width, const uint32_t height)
479 : {
480 10 : m->IsOpen = true;
481 :
482 : // Dimensions
483 10 : m_Width = width;
484 10 : m_Height = height;
485 :
486 10 : m->debugRenderer.Initialize();
487 :
488 10 : if (m->postprocManager.IsEnabled())
489 0 : m->postprocManager.Initialize(width, height);
490 :
491 10 : m->sceneRenderer.Initialize(width, height);
492 :
493 10 : return true;
494 : }
495 :
496 0 : void CRenderer::CreateViewSizeDependentObjects(const uint32_t width, const uint32_t height)
497 : {
498 0 : m_Width = width;
499 0 : m_Height = height;
500 :
501 0 : m->postprocManager.CreateViewSizeDependentObjects(width, height);
502 :
503 0 : m->sceneRenderer.CreateViewSizeDependentObjects(width, height);
504 0 : }
505 :
506 0 : void CRenderer::DestroyViewSizeDependentObjects()
507 : {
508 0 : m->sceneRenderer.DestroyViewSizeDependentObjects();
509 0 : m->postprocManager.DestroyViewSizeDependentObjects();
510 0 : }
511 :
512 0 : bool CRenderer::ShouldRender() const
513 : {
514 0 : const bool shouldRenderWhenOutOfFocus{
515 0 : g_ConfigDB.Get("renderer.renderwhenoutoffocus", true)};
516 0 : return !g_app_minimized && (g_app_has_focus || shouldRenderWhenOutOfFocus);
517 : }
518 :
519 0 : void CRenderer::RenderFrame(const bool needsPresent)
520 : {
521 : // Do not render if not focused while in fullscreen or minimised,
522 : // as that triggers a difficult-to-reproduce crash on some graphic cards.
523 0 : if (!ShouldRender())
524 : return;
525 :
526 0 : if (m->m_ScreenShotType == ScreenShotType::BIG)
527 : {
528 0 : RenderBigScreenShot(needsPresent);
529 : }
530 0 : else if (m->m_ScreenShotType == ScreenShotType::DEFAULT)
531 : {
532 0 : RenderScreenShot(needsPresent);
533 : }
534 : else
535 : {
536 0 : Renderer::Backend::ISwapChain* swapChain{g_VideoMode.GetOrCreateSwapChain()};
537 0 : if (!swapChain || !swapChain->IsValid())
538 0 : return;
539 :
540 : // In case of no acquired backbuffer we have nothing render to.
541 0 : if (needsPresent && !swapChain->AcquireNextBackbuffer())
542 : return;
543 :
544 0 : if (m_ShouldPreloadResourcesBeforeNextFrame)
545 : {
546 0 : m_ShouldPreloadResourcesBeforeNextFrame = false;
547 : // We don't need to render logger for the preload.
548 0 : RenderFrameImpl(*swapChain, true, false);
549 : }
550 :
551 0 : RenderFrameImpl(*swapChain, true, true);
552 :
553 0 : m->deviceCommandContext->Flush();
554 0 : if (needsPresent)
555 0 : swapChain->Present();
556 : }
557 : }
558 :
559 0 : void CRenderer::RenderFrameImpl(
560 : Renderer::Backend::ISwapChain& swapChain,
561 : const bool renderGUI, const bool renderLogger)
562 : {
563 0 : PROFILE3("render");
564 :
565 0 : g_Profiler2.RecordGPUFrameStart(m->deviceCommandContext.get());
566 :
567 0 : g_TexMan.UploadResourcesIfNeeded(m->deviceCommandContext.get());
568 :
569 0 : m->textureManager.MakeUploadProgress(m->deviceCommandContext.get());
570 :
571 : // prepare before starting the renderer frame
572 0 : if (g_Game && g_Game->IsGameStarted())
573 : {
574 0 : const CGameView& gameView{*g_Game->GetView()};
575 0 : m->sceneRenderer.SetSceneCamera(gameView.GetCamera(), gameView.GetCullCamera());
576 :
577 0 : g_Game->CachePlayerColors();
578 : }
579 :
580 0 : if (g_Game)
581 0 : m->sceneRenderer.SetSimulation(g_Game->GetSimulation2());
582 :
583 : // start new frame
584 0 : BeginFrame();
585 :
586 0 : if (g_Game && g_Game->IsGameStarted())
587 : {
588 0 : CGameView& gameView{*g_Game->GetView()};
589 0 : gameView.EnumerateSceneObjects();
590 :
591 0 : m->sceneRenderer.PrepareSubmissions(m->deviceCommandContext.get());
592 :
593 0 : CPostprocManager& postprocManager{GetPostprocManager()};
594 0 : if (postprocManager.IsEnabled())
595 : {
596 0 : postprocManager.Initialize(m_Width, m_Height);
597 0 : RenderGameWithPostProcessingAndGUI(
598 : swapChain, gameView, postprocManager, renderGUI, renderLogger);
599 : }
600 : else
601 : {
602 0 : RenderGameAndGUI(swapChain, gameView, renderGUI, renderLogger);
603 : }
604 : }
605 : else
606 : {
607 0 : RenderGUIOnly(swapChain, renderGUI, renderLogger);
608 : }
609 :
610 0 : EndFrame();
611 :
612 0 : const Stats& stats = GetStats();
613 0 : PROFILE2_ATTR("draw calls: %zu", stats.m_DrawCalls);
614 0 : PROFILE2_ATTR("terrain tris: %zu", stats.m_TerrainTris);
615 0 : PROFILE2_ATTR("water tris: %zu", stats.m_WaterTris);
616 0 : PROFILE2_ATTR("model tris: %zu", stats.m_ModelTris);
617 0 : PROFILE2_ATTR("overlay tris: %zu", stats.m_OverlayTris);
618 0 : PROFILE2_ATTR("blend splats: %zu", stats.m_BlendSplats);
619 0 : PROFILE2_ATTR("particles: %zu", stats.m_Particles);
620 :
621 0 : g_Profiler2.RecordGPUFrameEnd(m->deviceCommandContext.get());
622 :
623 0 : m->linearAllocator.Release();
624 0 : }
625 :
626 0 : void CRenderer::RenderGameAndGUI(
627 : Renderer::Backend::ISwapChain& swapChain, CGameView& gameView,
628 : const bool renderGUI, const bool renderLogger)
629 : {
630 : // We don't need to clear the color attachment of the framebuffer as the sky
631 : // is going to be rendered anyway.
632 0 : Renderer::Backend::IFramebuffer* framebuffer{
633 0 : swapChain.GetCurrentBackbuffer(
634 : Renderer::Backend::AttachmentLoadOp::DONT_CARE,
635 : Renderer::Backend::AttachmentStoreOp::STORE,
636 : Renderer::Backend::AttachmentLoadOp::CLEAR,
637 : Renderer::Backend::AttachmentStoreOp::DONT_CARE)};
638 :
639 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
640 0 : viewportRect.width = m_Width;
641 0 : viewportRect.height = m_Height;
642 :
643 0 : m->deviceCommandContext->BeginFramebufferPass(framebuffer);
644 0 : m->deviceCommandContext->SetViewports(1, &viewportRect);
645 :
646 0 : m->sceneRenderer.RenderSubmissions(m->deviceCommandContext.get());
647 0 : RenderGameOverlays(gameView);
648 0 : Render2D(renderGUI, renderLogger);
649 :
650 0 : m->deviceCommandContext->EndFramebufferPass();
651 0 : }
652 :
653 0 : void CRenderer::RenderGameWithPostProcessingAndGUI(
654 : Renderer::Backend::ISwapChain& swapChain, CGameView& gameView,
655 : CPostprocManager& postprocManager,
656 : const bool renderGUI, const bool renderLogger)
657 : {
658 0 : ENSURE(postprocManager.IsEnabled());
659 : // We have to update the post process manager with real near/far planes
660 : // that we use for the scene rendering.
661 0 : postprocManager.SetDepthBufferClipPlanes(
662 0 : m->sceneRenderer.GetViewCamera().GetNearPlane(),
663 0 : m->sceneRenderer.GetViewCamera().GetFarPlane()
664 : );
665 :
666 : // In the first pass we render the game scene to a post processing texture
667 : // instead of a backbuffer to be able to apply effects to it.
668 0 : Renderer::Backend::IFramebuffer* framebuffer{postprocManager.PrepareAndGetOutputFramebuffer()};
669 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
670 0 : viewportRect.width = framebuffer->GetWidth();
671 0 : viewportRect.height = framebuffer->GetHeight();
672 :
673 0 : m->deviceCommandContext->BeginFramebufferPass(framebuffer);
674 0 : m->deviceCommandContext->SetViewports(1, &viewportRect);
675 :
676 0 : m->sceneRenderer.RenderSubmissions(m->deviceCommandContext.get());
677 :
678 0 : m->deviceCommandContext->EndFramebufferPass();
679 :
680 0 : if (postprocManager.IsMultisampleEnabled())
681 0 : postprocManager.ResolveMultisampleFramebuffer(m->deviceCommandContext.get());
682 :
683 : // In the second pass we apply our post processing. There might multiple
684 : // ping pong passes to apply different effects.
685 0 : postprocManager.ApplyPostproc(m->deviceCommandContext.get());
686 :
687 : // During the final pass we blit our post processing result to the
688 : // backbuffer and then draw all 2D over it.
689 0 : Renderer::Backend::IFramebuffer* backbuffer{
690 0 : swapChain.GetCurrentBackbuffer(
691 : Renderer::Backend::AttachmentLoadOp::LOAD,
692 : Renderer::Backend::AttachmentStoreOp::STORE,
693 : Renderer::Backend::AttachmentLoadOp::LOAD,
694 : Renderer::Backend::AttachmentStoreOp::DONT_CARE)};
695 0 : postprocManager.BlitOutputFramebuffer(
696 0 : m->deviceCommandContext.get(), backbuffer);
697 :
698 0 : m->deviceCommandContext->BeginFramebufferPass(backbuffer);
699 :
700 0 : viewportRect.width = m_Width;
701 0 : viewportRect.height = m_Height;
702 0 : m->deviceCommandContext->SetViewports(1, &viewportRect);
703 :
704 0 : RenderGameOverlays(gameView);
705 0 : Render2D(renderGUI, renderLogger);
706 :
707 0 : m->deviceCommandContext->EndFramebufferPass();
708 0 : }
709 :
710 0 : void CRenderer::RenderGUIOnly(
711 : Renderer::Backend::ISwapChain& swapChain,
712 : const bool renderGUI, const bool renderLogger)
713 : {
714 : // We have a fullscreen background in our UI so we don't need
715 : // to clear the color attachment.
716 : // We don't need a depth test to render so we don't care about the
717 : // depth-stencil attachment content.
718 : // In case of Atlas we don't have g_Game, so we still need to clear depth.
719 0 : const Renderer::Backend::AttachmentLoadOp depthStencilLoadOp =
720 0 : g_AtlasGameLoop && g_AtlasGameLoop->view
721 0 : ? Renderer::Backend::AttachmentLoadOp::CLEAR
722 : : Renderer::Backend::AttachmentLoadOp::DONT_CARE;
723 0 : Renderer::Backend::IFramebuffer* backbuffer =
724 0 : swapChain.GetCurrentBackbuffer(
725 : Renderer::Backend::AttachmentLoadOp::DONT_CARE,
726 : Renderer::Backend::AttachmentStoreOp::STORE,
727 : depthStencilLoadOp,
728 : Renderer::Backend::AttachmentStoreOp::DONT_CARE);
729 0 : m->deviceCommandContext->BeginFramebufferPass(backbuffer);
730 :
731 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
732 0 : viewportRect.width = m_Width;
733 0 : viewportRect.height = m_Height;
734 0 : m->deviceCommandContext->SetViewports(1, &viewportRect);
735 :
736 0 : Render2D(renderGUI, renderLogger);
737 :
738 0 : m->deviceCommandContext->EndFramebufferPass();
739 0 : }
740 :
741 0 : void CRenderer::RenderGameOverlays(CGameView& gameView)
742 : {
743 0 : m->sceneRenderer.RenderSceneOverlays(m->deviceCommandContext.get());
744 :
745 0 : gameView.GetCinema()->Render(*m->deviceCommandContext);
746 :
747 : // If we're in Atlas game view, render special tools
748 0 : if (g_AtlasGameLoop && g_AtlasGameLoop->view)
749 : {
750 0 : g_AtlasGameLoop->view->DrawCinemaPathTool(*m->deviceCommandContext);
751 : }
752 0 : }
753 :
754 0 : void CRenderer::Render2D(const bool renderGUI, const bool renderLogger)
755 : {
756 0 : CCanvas2D canvas(g_VideoMode.GetWindowWidth(), g_VideoMode.GetWindowHeight(), g_VideoMode.GetScale(), m->deviceCommandContext.get());
757 :
758 0 : m->sceneRenderer.RenderTextOverlays(canvas);
759 :
760 0 : if (renderGUI)
761 : {
762 0 : GPU_SCOPED_LABEL(m->deviceCommandContext.get(), "Render GUI");
763 : // All GUI elements are drawn in Z order to render semi-transparent
764 : // objects correctly.
765 0 : g_GUI->Draw(canvas);
766 0 : }
767 :
768 : // If we're in Atlas game view, render special overlays (e.g. editor bandbox).
769 0 : if (g_AtlasGameLoop && g_AtlasGameLoop->view)
770 : {
771 0 : g_AtlasGameLoop->view->DrawOverlays(canvas);
772 : }
773 :
774 0 : {
775 0 : GPU_SCOPED_LABEL(m->deviceCommandContext.get(), "Render console");
776 0 : g_Console->Render(canvas);
777 0 : }
778 :
779 0 : if (renderLogger)
780 : {
781 0 : GPU_SCOPED_LABEL(m->deviceCommandContext.get(), "Render logger");
782 0 : g_Logger->Render(canvas);
783 0 : }
784 :
785 0 : {
786 0 : GPU_SCOPED_LABEL(m->deviceCommandContext.get(), "Render profiler");
787 : // Profile information
788 0 : g_ProfileViewer.RenderProfile(canvas);
789 0 : }
790 :
791 0 : GetFontManager().UploadAtlasTexturesToGPU(m->deviceCommandContext.get());
792 0 : }
793 :
794 0 : void CRenderer::RenderScreenShot(const bool needsPresent)
795 : {
796 0 : m->m_ScreenShotType = ScreenShotType::NONE;
797 :
798 : // get next available numbered filename
799 : // note: %04d -> always 4 digits, so sorting by filename works correctly.
800 0 : const VfsPath filenameFormat(L"screenshots/screenshot%04d.png");
801 0 : VfsPath filename;
802 0 : vfs::NextNumberedFilename(g_VFS, filenameFormat, g_NextScreenShotNumber, filename);
803 :
804 0 : const size_t width = static_cast<size_t>(g_VideoMode.GetWindowWidth()), height = static_cast<size_t>(g_VideoMode.GetWindowHeight());
805 0 : const size_t bpp = 24;
806 :
807 0 : const size_t img_size = width * height * bpp / 8;
808 0 : const size_t hdr_size = tex_hdr_size(filename);
809 0 : std::shared_ptr<std::uint8_t> buf;
810 0 : AllocateAligned(buf, hdr_size + img_size, maxSectorSize);
811 0 : void* img = buf.get() + hdr_size;
812 0 : Tex t;
813 0 : if (t.wrap(width, height, bpp, TEX_BOTTOM_UP, buf, hdr_size) < 0)
814 : return;
815 :
816 0 : Renderer::Backend::ISwapChain* swapChain{g_VideoMode.GetOrCreateSwapChain()};
817 0 : if (!swapChain || !swapChain->IsValid())
818 0 : return;
819 :
820 0 : if (needsPresent && !swapChain->AcquireNextBackbuffer())
821 : return;
822 :
823 : // Hide log messages and re-render
824 0 : RenderFrameImpl(*swapChain, false, false);
825 :
826 0 : m->deviceCommandContext->ReadbackFramebufferSync(*swapChain, 0, 0, width, height, img);
827 0 : m->deviceCommandContext->Flush();
828 0 : if (needsPresent)
829 0 : swapChain->Present();
830 :
831 0 : if (tex_write(&t, filename) == INFO::OK)
832 : {
833 0 : OsPath realPath;
834 0 : g_VFS->GetRealPath(filename, realPath);
835 :
836 0 : LOGMESSAGERENDER("Screenshot written to '{}'", realPath.string8());
837 :
838 0 : debug_printf(
839 0 : CStr(g_L10n.Translate("Screenshot written to '%s'") + "\n").c_str(),
840 0 : realPath.string8().c_str());
841 0 : }
842 : else
843 0 : LOGERROR("Error writing screenshot to '{}'", filename.string8());
844 0 : }
845 :
846 0 : void CRenderer::RenderBigScreenShot(const bool needsPresent)
847 : {
848 0 : m->m_ScreenShotType = ScreenShotType::NONE;
849 :
850 : // If the game hasn't started yet then use WriteScreenshot to generate the image.
851 0 : if (!g_Game)
852 0 : return RenderScreenShot(needsPresent);
853 :
854 0 : const int tiles{g_ConfigDB.Get("screenshot.tiles", 4)};
855 0 : const int tileWidth{g_ConfigDB.Get("screenshot.tilewidth", 256)};
856 0 : const int tileHeight{g_ConfigDB.Get("screenshot.tileheight", 256)};
857 0 : if (tiles <= 0 || tileWidth <= 0 || tileHeight <= 0 || tileWidth * tiles % 4 != 0 || tileHeight * tiles % 4 != 0)
858 : {
859 0 : LOGWARNING("Invalid big screenshot size: tiles={} tileWidth={} tileHeight={}", tiles,
860 : tileWidth, tileHeight);
861 0 : return;
862 : }
863 :
864 0 : if (g_VideoMode.GetWindowWidth() < tileWidth && g_VideoMode.GetWindowHeight() < tileHeight)
865 : {
866 0 : LOGWARNING(
867 : "The window size is too small for a big screenshot, increase the"
868 : " window size {}x{} or decrease the tile size {}x{}",
869 : g_VideoMode.GetWindowWidth(), g_VideoMode.GetWindowHeight(), tileWidth, tileHeight);
870 0 : return;
871 : }
872 :
873 : // get next available numbered filename
874 : // note: %04d -> always 4 digits, so sorting by filename works correctly.
875 0 : const VfsPath filenameFormat(L"screenshots/screenshot%04d.bmp");
876 0 : VfsPath filename;
877 0 : vfs::NextNumberedFilename(g_VFS, filenameFormat, g_NextScreenShotNumber, filename);
878 :
879 0 : const int imageWidth = tileWidth * tiles, imageHeight = tileHeight * tiles;
880 0 : const int bpp = 24;
881 :
882 0 : const size_t imageSize = imageWidth * imageHeight * bpp / 8;
883 0 : const size_t tileSize = tileWidth * tileHeight * bpp / 8;
884 0 : const size_t headerSize = tex_hdr_size(filename);
885 0 : void* tileData = malloc(tileSize);
886 0 : if (!tileData)
887 : {
888 0 : WARN_IF_ERR(ERR::NO_MEM);
889 0 : return;
890 : }
891 0 : std::shared_ptr<std::uint8_t> imageBuffer;
892 0 : AllocateAligned(imageBuffer, headerSize + imageSize, maxSectorSize);
893 :
894 0 : Tex t;
895 0 : void* img = imageBuffer.get() + headerSize;
896 0 : if (t.wrap(imageWidth, imageHeight, bpp, TEX_BOTTOM_UP, imageBuffer, headerSize) < 0)
897 : {
898 0 : free(tileData);
899 0 : return;
900 : }
901 :
902 0 : const CCamera oldCamera{g_Game->GetView()->GetCamera()};
903 :
904 : // Resize various things so that the sizes and aspect ratios are correct
905 0 : {
906 0 : DestroyViewSizeDependentObjects();
907 0 : m->device->WaitUntilIdle();
908 0 : CreateViewSizeDependentObjects(tileWidth, tileHeight);
909 :
910 0 : SViewPort vp = { 0, 0, tileWidth, tileHeight };
911 0 : g_Game->GetView()->SetViewport(vp);
912 : }
913 :
914 : // Render each tile
915 0 : CMatrix3D projection;
916 0 : projection.SetIdentity();
917 0 : const float aspectRatio = 1.0f * tileWidth / tileHeight;
918 0 : for (int tileY = 0; tileY < tiles; ++tileY)
919 : {
920 0 : for (int tileX = 0; tileX < tiles; ++tileX)
921 : {
922 : // Adjust the camera to render the appropriate region
923 0 : if (oldCamera.GetProjectionType() == CCamera::ProjectionType::PERSPECTIVE)
924 : {
925 0 : projection.SetPerspectiveTile(
926 : oldCamera.GetFOV(), aspectRatio, oldCamera.GetNearPlane(), oldCamera.GetFarPlane(),
927 : tiles, tileX, tileY);
928 : }
929 0 : CCamera camera{g_Game->GetView()->GetCamera()};
930 0 : camera.SetProjection(projection);
931 0 : g_Game->GetView()->SetCamera(camera);
932 :
933 0 : Renderer::Backend::ISwapChain* swapChain{g_VideoMode.GetOrCreateSwapChain()};
934 0 : if (!swapChain || !swapChain->IsValid())
935 0 : continue;
936 :
937 0 : if (!needsPresent || swapChain->AcquireNextBackbuffer())
938 : {
939 0 : RenderFrameImpl(*swapChain, false, false);
940 :
941 0 : m->deviceCommandContext->ReadbackFramebufferSync(*swapChain, 0, 0, tileWidth, tileHeight, tileData);
942 0 : m->deviceCommandContext->Flush();
943 :
944 0 : if (needsPresent)
945 0 : swapChain->Present();
946 : }
947 :
948 : // Copy the tile pixels into the main image
949 0 : for (int y = 0; y < tileHeight; ++y)
950 : {
951 0 : void* dest = static_cast<char*>(img) + ((tileY * tileHeight + y) * imageWidth + (tileX * tileWidth)) * bpp / 8;
952 0 : void* src = static_cast<char*>(tileData) + y * tileWidth * bpp / 8;
953 0 : memcpy(dest, src, tileWidth * bpp / 8);
954 : }
955 0 : }
956 : }
957 :
958 : // Restore the viewport settings
959 0 : {
960 0 : DestroyViewSizeDependentObjects();
961 0 : m->device->WaitUntilIdle();
962 :
963 0 : SViewPort vp = { 0, 0, g_VideoMode.GetWindowWidth(), g_VideoMode.GetWindowHeight() };
964 0 : CreateViewSizeDependentObjects(vp.m_Width, vp.m_Height);
965 :
966 0 : g_Game->GetView()->SetViewport(vp);
967 0 : g_Game->GetView()->SetCamera(oldCamera);
968 : }
969 :
970 0 : if (tex_write(&t, filename) == INFO::OK)
971 : {
972 0 : OsPath realPath;
973 0 : g_VFS->GetRealPath(filename, realPath);
974 :
975 0 : LOGMESSAGERENDER("Screenshot written to '{}'", realPath.string8());
976 :
977 0 : debug_printf(
978 0 : CStr(g_L10n.Translate("Screenshot written to '%s'") + "\n").c_str(),
979 0 : realPath.string8().c_str());
980 0 : }
981 : else
982 0 : LOGERROR("Error writing screenshot to '{}'", filename.string8());
983 :
984 0 : free(tileData);
985 0 : }
986 :
987 0 : void CRenderer::BeginFrame()
988 : {
989 0 : PROFILE("begin frame");
990 :
991 : // Zero out all the per-frame stats.
992 0 : m_Stats.Reset();
993 :
994 0 : if (m->ShadersDirty)
995 0 : ReloadShaders();
996 :
997 0 : m->sceneRenderer.BeginFrame();
998 0 : }
999 :
1000 0 : void CRenderer::EndFrame()
1001 : {
1002 0 : PROFILE3("end frame");
1003 :
1004 0 : m->sceneRenderer.EndFrame();
1005 :
1006 0 : m->linearAllocator.Release();
1007 :
1008 0 : m->backendProfileTable.MakeOutdated();
1009 0 : }
1010 :
1011 0 : void CRenderer::MakeShadersDirty()
1012 : {
1013 0 : m->ShadersDirty = true;
1014 0 : m->sceneRenderer.MakeShadersDirty();
1015 0 : }
1016 :
1017 5 : CTextureManager& CRenderer::GetTextureManager()
1018 : {
1019 0 : return m->textureManager;
1020 : }
1021 :
1022 20 : CVertexBufferManager& CRenderer::GetVertexBufferManager()
1023 : {
1024 0 : return m->vertexBufferManager;
1025 : }
1026 :
1027 110 : CShaderManager& CRenderer::GetShaderManager()
1028 : {
1029 0 : return m->shaderManager;
1030 : }
1031 :
1032 0 : CTimeManager& CRenderer::GetTimeManager()
1033 : {
1034 0 : return m->timeManager;
1035 : }
1036 :
1037 20 : CPostprocManager& CRenderer::GetPostprocManager()
1038 : {
1039 0 : return m->postprocManager;
1040 : }
1041 :
1042 11 : CSceneRenderer& CRenderer::GetSceneRenderer()
1043 : {
1044 10 : return m->sceneRenderer;
1045 : }
1046 :
1047 0 : CDebugRenderer& CRenderer::GetDebugRenderer()
1048 : {
1049 0 : return m->debugRenderer;
1050 : }
1051 :
1052 2642 : CFontManager& CRenderer::GetFontManager()
1053 : {
1054 0 : return m->fontManager;
1055 : }
1056 :
1057 0 : void CRenderer::PreloadResourcesBeforeNextFrame()
1058 : {
1059 0 : m_ShouldPreloadResourcesBeforeNextFrame = true;
1060 0 : }
1061 :
1062 0 : void CRenderer::MakeScreenShotOnNextFrame(ScreenShotType screenShotType)
1063 : {
1064 0 : m->m_ScreenShotType = screenShotType;
1065 0 : }
1066 :
1067 10 : Renderer::Backend::IDeviceCommandContext* CRenderer::GetDeviceCommandContext()
1068 : {
1069 10 : return m->deviceCommandContext.get();
1070 : }
1071 :
1072 160 : Renderer::Backend::IVertexInputLayout* CRenderer::GetVertexInputLayout(
1073 : const std::span<const Renderer::Backend::SVertexAttributeFormat> attributes)
1074 : {
1075 320 : const auto [it, inserted] = m->vertexInputLayouts.emplace(
1076 320 : std::vector<Renderer::Backend::SVertexAttributeFormat>{attributes.begin(), attributes.end()}, nullptr);
1077 160 : if (inserted)
1078 130 : it->second = m->device->CreateVertexInputLayout(attributes);
1079 160 : return it->second.get();
1080 : }
1081 :
1082 0 : PS::Memory::LinearAllocator& CRenderer::GetLinearAllocator()
1083 : {
1084 0 : return m->linearAllocator;
1085 : }
1086 :
1087 0 : const Renderer::Backend::IDevice::Capabilities& CRenderer::GetCapabilities() const
1088 : {
1089 0 : return m->device->GetCapabilities();
1090 : }
|