Foundation
Loading...
Searching...
No Matches
Examples.hpp
Go to the documentation of this file.
1#pragma once
2#include <Core/Paths.hpp>
8#include <Math/Math.hpp>
11#include <argh.h>
12#include <algorithm>
13using namespace Foundation;
14using namespace Core;
15using namespace Math;
16using namespace RenderCore;
17
19 {RHIResourceFormat::R8G8B8A8Unorm, RHIColorSpace::SrgbNonLinear},
20 {RHIResourceFormat::B8G8R8A8Unrom, RHIColorSpace::SrgbNonLinear},
21};
22
24 RHISwapchainPresentMode::Mailbox, RHISwapchainPresentMode::Tearing, RHISwapchainPresentMode::Fifo};
25
26namespace details
27{
28 inline void CreateSwapchain(SDL_Window* window, RHIDevice* device,
30 {
31 int w, h;
32 SDL_GetWindowSizeInPixels(window, &w, &h);
33 LOG(RenderApplication, LogDebug, "Creating swapchain ({}x{})", w, h);
34 device->WaitIdle();
35 if (outSwap)
36 outSwap.Reset();
37 auto format = Ranges::FirstOf(Views::all(kFormatPreferenceList) |
38 Views::filter(Ranges::ContainedBy(device->GetSwapchainSupportedFormats())));
39 auto present = Ranges::FirstOf(Views::all(kPresentModePreferenceList) |
41 CHECK_MSG(format.has_value(), "No supported swapchain format found!");
42 LOG(RenderApplication, LogDebug, "Selected swapchain format: {} with color space: {}", format.value().format, format.value().colorSpace);
43 CHECK_MSG(present.has_value(), "No supported presentation mode found!");
44 LOG(RenderApplication, LogDebug, "Selected swapchain present mode: {}", present.value());
46 .format = format.value().format,
47 .colorSpace = format.value().colorSpace,
48 .extents = RHIExtent3D{w, h, 1},
49 .minBufferCount = 3,
50 .presentMode = present.value(),
51 });
52 }
53}
54// [renderer, app, device, swapchain]
55constexpr int Examples_SDLWindowFlagsVulkan = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_VULKAN;
56// Common command-line options shared by all examples (mirrors Editor::SDLMain):
57// -h, --help Show usage and exit
58// -g, --gpu <id> Select GPU device index
59// -l, --list-gpus List available GPU devices and exit
60inline auto Examples_InitVulkan(SDL_Window* window, int argc, char** argv, RendererDesc const& desc = {})
61{
62 argh::parser cmdl(argc, argv, argh::parser::PREFER_PARAM_FOR_UNREG_OPTION);
63 if (cmdl[{"-h", "--help"}])
64 {
65 fmt::println("Usage: {} [options]", argv[0]);
66 fmt::println("Options:");
67 fmt::println("\t-h, --help\t\tShow this help message");
68 fmt::println("\t-g, --gpu <id>\t\tSpecify GPU device index");
69 fmt::println("\t-l, --list-gpus\t\tList available GPU devices");
70 std::exit(0);
71 }
72 if (cmdl[{"-l", "--list-gpus"}])
73 {
75 for (auto const& d : app->EnumerateDevices())
76 fmt::println("[{}] {}", d.id, d.name);
78 std::exit(0);
79 }
80 int gpuId = 0;
81 cmdl({"-g", "--gpu"}, 0) >> gpuId;
84 auto device = app->CreateDevice({.id = static_cast<uint32_t>(gpuId)}, window);
88 return std::make_tuple(renderer, app, std::move(device), std::move(swap));
89}
90// Polls event, possibly resizing the swapchain, and returns true if the window should close.
92{
93 SDL_Event event{};
94 bool any = SDL_PollEvent(&event);
95 if (outEvent)
96 *outEvent = event;
97 if (!any)
98 return false;
99 if (event.window.windowID != SDL_GetWindowID(window))
100 return false;
101 if (event.type == SDL_EVENT_QUIT || event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) return true;
102 // Resize swapchain if necessary
104 {
106 renderer->SetSwapchain(swap);
107 }
108 return false;
109}
111{
112 renderer->BeginExecute();
113 renderer->ExecuteFrame();
114 renderer->EndExecute();
115}
117{
119 if (device)
120 device->WaitIdle();
121 swapchain.Reset();
122 device.Reset();
125}
126
127inline float Examples_GetTime()
128{
129 return static_cast<float>(SDL_GetTicks() / 1e3);
130}
131
132
134{
135 size_t lastTick{};
136 size_t frames{};
137 float fps{};
138 float Update()
139 {
140 size_t now = SDL_GetTicksNS();
141 size_t delta = now - lastTick;
142 if (delta >= 1e9)
143 {
144 fps = 1e9 * (static_cast<float>(frames) / delta);
145 frames = 0;
146 lastTick = now;
147 }
148 frames++;
149 return fps;
150 }
151};
152
153
155{
156 static constexpr char kControlsText[] = "Mouse Left: Rotate | Mouse Right: Pan | Mouse Wheel: Zoom";
157
159 float radius;
160 float pitch, yaw;
164 {
165 if (event.type == SDL_EVENT_MOUSE_MOTION)
166 {
167 if (event.motion.state & SDL_BUTTON_LMASK)
168 {
169 pitch -= event.motion.xrel * 1e-2f;
170 yaw -= event.motion.yrel * 1e-2f;
171 }
172 if (event.motion.state & SDL_BUTTON_RMASK)
173 {
174 quat rot = angleAxis(yaw, vec3(1, 0, 0)) * angleAxis(pitch, vec3(0, 1, 0));
175 vec3 right = rot * vec3(1, 0, 0);
176 vec3 up = rot * vec3(0, 1, 0);
177 center -= right * (event.motion.xrel * radius * 1e-3f);
178 center += up * (event.motion.yrel * radius * 1e-3f);
179 }
180 }
181 if (event.type == SDL_EVENT_MOUSE_WHEEL)
182 {
183 radius -= event.wheel.y * radius * 1e-1f;
184 radius = radius < 1e-3f ? 1e-3f : radius;
185 }
186 // ---
188 quat rot = angleAxis(yaw, vec3(1, 0, 0)) * angleAxis(pitch, vec3(0, 1, 0));
189 vec3 dir = rot * vec3(0, 0, 1);
192 return viewProj;
193 }
194};
#define GLOBAL_ALLOC
Definition Allocator.hpp:225
constexpr int Examples_SDLWindowFlagsVulkan
Definition Examples.hpp:55
constexpr RHISwapchainPresentMode kPresentModePreferenceList[]
Definition Examples.hpp:23
bool Examples_ShouldClose(SDL_Window *window, Renderer *renderer, RHIDeviceScopedHandle< RHISwapchain > &swap, SDL_Event *outEvent=nullptr)
Definition Examples.hpp:91
float Examples_GetTime()
Definition Examples.hpp:127
constexpr RHISurfaceFormat kFormatPreferenceList[]
Definition Examples.hpp:18
void Examples_NewFrame(Renderer *renderer)
Definition Examples.hpp:110
auto Examples_InitVulkan(SDL_Window *window, int argc, char **argv, RendererDesc const &desc={})
Definition Examples.hpp:60
auto Examples_DestroyVulkan(SDL_Window *window, Renderer *renderer, VulkanApplication *app, RHIApplicationScopedHandle< RHIDevice > &device, RHIDeviceScopedHandle< RHISwapchain > &swapchain)
Definition Examples.hpp:116
#define LOG(TAG, LEVEL, FORMAT,...)
Definition Logging.hpp:55
#define CHECK_MSG(expr, format_str,...)
Definition Logging.hpp:62
@ LogDebug
Definition Logging.hpp:6
Definition Device.hpp:245
virtual Span< RHISwapchainPresentMode const > GetSwapchainSupportedPresentModes() const =0
virtual Span< RHISurfaceFormat const > GetSwapchainSupportedFormats() const =0
virtual void WaitIdle() const =0
virtual RHIDeviceScopedHandle< RHISwapchain > CreateSwapchain(RHISwapchain::SwapchainDesc const &desc)=0
Scoped move-only RAII handle wrapper for RHI Objects.
Definition Details.hpp:86
void Reset()
Destructs the underlying RHIObject, and invalidates the scoped handle.
Definition Details.hpp:127
Definition Application.hpp:9
Renderer implementing a Frame Graph system with automatic resource tracking and synchronization.
Definition Renderer.hpp:89
constexpr Optional< range_value_t< T > > FirstOf(T &&range)
Returns the first element of a range, or an empty Optional if the range is empty.
Definition Container.hpp:231
void Destruct(Allocator *resource, T *obj)
Convenience destructor for objects allocated with Construct or ConstructBase.
Definition Allocator.hpp:160
void PathsInitFromDir(const char *exeDir)
Definition Paths.cpp:13
T * Construct(Allocator *resource, Args &&...args)
Convenience placement new with object of type T using a Foundation::Core::Allocator.
Definition Allocator.hpp:153
vec3 float3
Definition Math.hpp:26
mat4 infinitePerspectiveRHReverseZ(float fovY, float a, float zNear)
Definition ModelViewProjection.hpp:7
mat4 viewMatrixRHReverseZ(vec3 pos, quat rot)
Definition ModelViewProjection.hpp:26
RHISwapchainPresentMode
Definition Swapchain.hpp:11
glm::vec< 3, uint32_t > RHIExtent3D
Definition Common.hpp:11
Definition Allocator.hpp:5
Definition Examples.hpp:27
void CreateSwapchain(SDL_Window *window, RHIDevice *device, RHIDeviceScopedHandle< RHISwapchain > &outSwap)
Definition Examples.hpp:28
Definition Examples.hpp:134
size_t lastTick
Definition Examples.hpp:135
float fps
Definition Examples.hpp:137
float Update()
Definition Examples.hpp:138
size_t frames
Definition Examples.hpp:136
Definition Examples.hpp:155
float3 center
Definition Examples.hpp:158
float radius
Definition Examples.hpp:159
float yaw
Definition Examples.hpp:160
float zNear
Definition Examples.hpp:161
static constexpr char kControlsText[]
Definition Examples.hpp:156
float fovY
Definition Examples.hpp:161
float pitch
Definition Examples.hpp:160
mat4 view
Definition Examples.hpp:162
mat4 Update(SDL_Event const &event)
Definition Examples.hpp:163
mat4 proj
Definition Examples.hpp:162
float aspect
Definition Examples.hpp:161
Range predicate that checks if a value is contained within a given range.
Definition Container.hpp:219
Definition Common.hpp:142
RHIResourceFormat format
Definition Swapchain.hpp:25
Parameters for Renderer creation.
Definition Renderer.hpp:17