metaforce/aurora/lib/gpu.cpp

409 lines
14 KiB
C++
Raw Normal View History

2022-02-19 05:33:56 +00:00
#include "gpu.hpp"
2022-03-08 23:35:40 +00:00
#include <aurora/aurora.hpp>
#include <SDL.h>
2022-02-19 05:33:56 +00:00
#include <dawn/native/DawnNative.h>
#include <dawn/webgpu_cpp.h>
#include <logvisor/logvisor.hpp>
#include <magic_enum.hpp>
#include <memory>
#include "dawn/BackendBinding.hpp"
2022-03-08 23:35:40 +00:00
// FIXME hack to avoid crash on Windows
namespace aurora {
extern WindowSize g_windowSize;
} // namespace aurora
2022-02-19 05:33:56 +00:00
namespace aurora::gpu {
static logvisor::Module Log("aurora::gpu");
wgpu::Device g_device;
wgpu::Queue g_queue;
wgpu::SwapChain g_swapChain;
wgpu::BackendType g_backendType;
GraphicsConfig g_graphicsConfig;
TextureWithSampler g_frameBuffer;
TextureWithSampler g_frameBufferResolved;
TextureWithSampler g_depthBuffer;
2022-05-09 21:13:38 +00:00
// EFB -> XFB copy pipeline
static wgpu::BindGroupLayout g_CopyBindGroupLayout;
wgpu::RenderPipeline g_CopyPipeline;
wgpu::BindGroup g_CopyBindGroup;
2022-02-19 05:33:56 +00:00
static std::unique_ptr<dawn::native::Instance> g_Instance;
static dawn::native::Adapter g_Adapter;
static wgpu::AdapterProperties g_AdapterProperties;
static std::unique_ptr<utils::BackendBinding> g_BackendBinding;
2022-05-09 21:13:38 +00:00
TextureWithSampler create_render_texture(bool multisampled) {
2022-02-19 05:33:56 +00:00
const auto size = wgpu::Extent3D{
.width = g_graphicsConfig.width,
.height = g_graphicsConfig.height,
};
const auto format = g_graphicsConfig.colorFormat;
uint32_t sampleCount = 1;
if (multisampled) {
sampleCount = g_graphicsConfig.msaaSamples;
}
const auto textureDescriptor = wgpu::TextureDescriptor{
.label = "Render texture",
.usage = wgpu::TextureUsage::RenderAttachment | wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopySrc |
wgpu::TextureUsage::CopyDst,
2022-02-19 05:33:56 +00:00
.size = size,
.format = format,
.sampleCount = sampleCount,
};
auto texture = g_device.CreateTexture(&textureDescriptor);
const auto viewDescriptor = wgpu::TextureViewDescriptor{};
auto view = texture.CreateView(&viewDescriptor);
const auto samplerDescriptor = wgpu::SamplerDescriptor{
.label = "Render sampler",
.magFilter = wgpu::FilterMode::Linear,
.minFilter = wgpu::FilterMode::Linear,
.mipmapFilter = wgpu::FilterMode::Linear,
};
auto sampler = g_device.CreateSampler(&samplerDescriptor);
return {
.texture = std::move(texture),
.view = std::move(view),
.size = size,
.format = format,
.sampler = std::move(sampler),
};
}
static TextureWithSampler create_depth_texture() {
const auto size = wgpu::Extent3D{
.width = g_graphicsConfig.width,
.height = g_graphicsConfig.height,
};
const auto format = g_graphicsConfig.depthFormat;
const auto textureDescriptor = wgpu::TextureDescriptor{
.label = "Depth texture",
.usage = wgpu::TextureUsage::RenderAttachment | wgpu::TextureUsage::TextureBinding,
.size = size,
.format = format,
.sampleCount = g_graphicsConfig.msaaSamples,
};
auto texture = g_device.CreateTexture(&textureDescriptor);
const auto viewDescriptor = wgpu::TextureViewDescriptor{};
auto view = texture.CreateView(&viewDescriptor);
const auto samplerDescriptor = wgpu::SamplerDescriptor{
.label = "Depth sampler",
.magFilter = wgpu::FilterMode::Linear,
.minFilter = wgpu::FilterMode::Linear,
.mipmapFilter = wgpu::FilterMode::Linear,
};
auto sampler = g_device.CreateSampler(&samplerDescriptor);
return {
.texture = std::move(texture),
.view = std::move(view),
.size = size,
.format = format,
.sampler = std::move(sampler),
};
}
2022-05-09 21:13:38 +00:00
void create_copy_pipeline() {
wgpu::ShaderModuleWGSLDescriptor sourceDescriptor{};
sourceDescriptor.source = R"""(
@group(0) @binding(0)
var efb_sampler: sampler;
@group(0) @binding(1)
var efb_texture: texture_2d<f32>;
struct VertexOutput {
@builtin(position) pos: vec4<f32>,
@location(0) uv: vec2<f32>,
};
var<private> pos: array<vec2<f32>, 3> = array<vec2<f32>, 3>(
vec2(-1.0, 1.0),
vec2(-1.0, -3.0),
vec2(3.0, 1.0),
);
var<private> uvs: array<vec2<f32>, 3> = array<vec2<f32>, 3>(
vec2(0.0, 0.0),
vec2(0.0, 2.0),
vec2(2.0, 0.0),
);
@stage(vertex)
fn vs_main(@builtin(vertex_index) vtxIdx: u32) -> VertexOutput {
var out: VertexOutput;
out.pos = vec4<f32>(pos[vtxIdx], 0.0, 1.0);
out.uv = uvs[vtxIdx];
return out;
}
@stage(fragment)
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return textureSample(efb_texture, efb_sampler, in.uv);
}
)""";
const wgpu::ShaderModuleDescriptor moduleDescriptor{
.nextInChain = &sourceDescriptor,
.label = "XFB Copy Module",
};
auto module = g_device.CreateShaderModule(&moduleDescriptor);
const std::array colorTargets{
wgpu::ColorTargetState{
.format = g_graphicsConfig.colorFormat,
},
};
const wgpu::FragmentState fragmentState{
.module = module,
.entryPoint = "fs_main",
.targetCount = colorTargets.size(),
.targets = colorTargets.data(),
};
const std::array bindGroupLayoutEntries{
wgpu::BindGroupLayoutEntry{
.binding = 0,
.visibility = wgpu::ShaderStage::Fragment,
.sampler =
wgpu::SamplerBindingLayout{
.type = wgpu::SamplerBindingType::Filtering,
},
},
wgpu::BindGroupLayoutEntry{
.binding = 1,
.visibility = wgpu::ShaderStage::Fragment,
.texture =
wgpu::TextureBindingLayout{
.sampleType = wgpu::TextureSampleType::Float,
.viewDimension = wgpu::TextureViewDimension::e2D,
},
},
};
const wgpu::BindGroupLayoutDescriptor bindGroupLayoutDescriptor{
.entryCount = bindGroupLayoutEntries.size(),
.entries = bindGroupLayoutEntries.data(),
};
g_CopyBindGroupLayout = g_device.CreateBindGroupLayout(&bindGroupLayoutDescriptor);
const wgpu::PipelineLayoutDescriptor layoutDescriptor{
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &g_CopyBindGroupLayout,
};
auto pipelineLayout = g_device.CreatePipelineLayout(&layoutDescriptor);
const wgpu::RenderPipelineDescriptor pipelineDescriptor{
.layout = pipelineLayout,
.vertex =
wgpu::VertexState{
.module = module,
.entryPoint = "vs_main",
},
.fragment = &fragmentState,
};
g_CopyPipeline = g_device.CreateRenderPipeline(&pipelineDescriptor);
}
void create_copy_bind_group() {
const std::array bindGroupEntries{
wgpu::BindGroupEntry{
.binding = 0,
.sampler = g_graphicsConfig.msaaSamples > 1 ? gpu::g_frameBufferResolved.sampler : gpu::g_frameBuffer.sampler,
},
wgpu::BindGroupEntry{
.binding = 1,
.textureView = g_graphicsConfig.msaaSamples > 1 ? gpu::g_frameBufferResolved.view : gpu::g_frameBuffer.view,
},
};
const wgpu::BindGroupDescriptor bindGroupDescriptor{
.layout = g_CopyBindGroupLayout,
.entryCount = bindGroupEntries.size(),
.entries = bindGroupEntries.data(),
};
g_CopyBindGroup = g_device.CreateBindGroup(&bindGroupDescriptor);
}
2022-02-19 05:33:56 +00:00
static void error_callback(WGPUErrorType type, char const* message, void* userdata) {
2022-03-08 07:44:46 +00:00
Log.report(logvisor::Fatal, FMT_STRING("Dawn error {}: {}"),
2022-02-19 05:33:56 +00:00
magic_enum::enum_name(static_cast<wgpu::ErrorType>(type)), message);
}
static void device_callback(WGPURequestDeviceStatus status, WGPUDevice device, char const* message, void* userdata) {
if (status == WGPURequestDeviceStatus_Success) {
g_device = wgpu::Device::Acquire(device);
} else {
Log.report(logvisor::Warning, FMT_STRING("Device request failed with message: {}"), message);
}
*static_cast<bool*>(userdata) = true;
}
bool initialize(SDL_Window* window, wgpu::BackendType backendType) {
if (!g_Instance) {
Log.report(logvisor::Info, FMT_STRING("Creating Dawn instance"));
g_Instance = std::make_unique<dawn::native::Instance>();
}
#ifndef NDEBUG
// D3D12's debug layer is very slow
// g_Instance->EnableBackendValidation(backendType != wgpu::BackendType::D3D12);
#endif
if (!utils::DiscoverAdapter(g_Instance.get(), window, backendType)) {
return false;
}
2022-02-19 05:33:56 +00:00
{
std::vector<dawn::native::Adapter> adapters = g_Instance->GetAdapters();
std::sort(adapters.begin(), adapters.end(), [&](const auto& a, const auto& b) {
wgpu::AdapterProperties propertiesA;
wgpu::AdapterProperties propertiesB;
a.GetProperties(&propertiesA);
b.GetProperties(&propertiesB);
constexpr std::array PreferredTypeOrder{
wgpu::AdapterType::DiscreteGPU,
wgpu::AdapterType::IntegratedGPU,
wgpu::AdapterType::CPU,
};
const auto typeItA = std::find(PreferredTypeOrder.begin(), PreferredTypeOrder.end(), propertiesA.adapterType);
const auto typeItB = std::find(PreferredTypeOrder.begin(), PreferredTypeOrder.end(), propertiesB.adapterType);
if (typeItA == PreferredTypeOrder.end() && typeItB != PreferredTypeOrder.end()) {
return -1;
}
return static_cast<int>(typeItA - typeItB);
});
const auto adapterIt = std::find_if(adapters.begin(), adapters.end(), [=](const auto& adapter) -> bool {
2022-02-19 05:33:56 +00:00
wgpu::AdapterProperties properties;
adapter.GetProperties(&properties);
return properties.backendType == backendType;
2022-02-19 05:33:56 +00:00
});
if (adapterIt == adapters.end()) {
return false;
2022-02-19 05:33:56 +00:00
}
g_Adapter = *adapterIt;
}
g_Adapter.GetProperties(&g_AdapterProperties);
g_backendType = g_AdapterProperties.backendType;
const auto backendName = magic_enum::enum_name(g_backendType);
Log.report(logvisor::Info, FMT_STRING("Graphics adapter information\n API: {}\n Device: {} ({})\n Driver: {}"),
backendName, g_AdapterProperties.name, magic_enum::enum_name(g_AdapterProperties.adapterType),
g_AdapterProperties.driverDescription);
2022-02-19 05:33:56 +00:00
{
2022-05-09 04:56:44 +00:00
WGPUSupportedLimits supportedLimits{};
g_Adapter.GetLimits(&supportedLimits);
const wgpu::RequiredLimits requiredLimits{
.limits =
{
// Use "best" supported alignments
2022-05-04 00:26:45 +00:00
.minUniformBufferOffsetAlignment = supportedLimits.limits.minUniformBufferOffsetAlignment == 0
2022-05-05 05:39:43 +00:00
? static_cast<uint32_t>(WGPU_LIMIT_U32_UNDEFINED)
2022-05-04 00:26:45 +00:00
: supportedLimits.limits.minUniformBufferOffsetAlignment,
.minStorageBufferOffsetAlignment = supportedLimits.limits.minStorageBufferOffsetAlignment == 0
2022-05-05 05:39:43 +00:00
? static_cast<uint32_t>(WGPU_LIMIT_U32_UNDEFINED)
2022-05-04 00:26:45 +00:00
: supportedLimits.limits.minStorageBufferOffsetAlignment,
},
};
std::vector<wgpu::FeatureName> features;
const auto supportedFeatures = g_Adapter.GetSupportedFeatures();
for (const auto* const feature : supportedFeatures) {
if (strcmp(feature, "texture-compression-bc") == 0) {
features.push_back(wgpu::FeatureName::TextureCompressionBC);
}
}
const std::array enableToggles {
/* clang-format off */
#if _WIN32
"use_dxc",
#endif
#ifdef NDEBUG
2022-05-14 23:23:47 +00:00
"skip_validation",
"disable_robustness",
#endif
2022-05-14 23:23:47 +00:00
"use_user_defined_labels_in_backend",
"disable_symbol_renaming",
/* clang-format on */
};
wgpu::DawnTogglesDeviceDescriptor togglesDescriptor{};
togglesDescriptor.forceEnabledTogglesCount = enableToggles.size();
togglesDescriptor.forceEnabledToggles = enableToggles.data();
2022-02-19 05:33:56 +00:00
const auto deviceDescriptor = wgpu::DeviceDescriptor{
.nextInChain = &togglesDescriptor,
.requiredFeaturesCount = static_cast<uint32_t>(features.size()),
.requiredFeatures = features.data(),
.requiredLimits = &requiredLimits,
2022-02-19 05:33:56 +00:00
};
bool deviceCallbackReceived = false;
g_Adapter.RequestDevice(&deviceDescriptor, &device_callback, &deviceCallbackReceived);
// while (!deviceCallbackReceived) {
// TODO wgpuInstanceProcessEvents
// }
if (!g_device) {
return false;
}
2022-02-19 05:33:56 +00:00
g_device.SetUncapturedErrorCallback(&error_callback, nullptr);
}
g_queue = g_device.GetQueue();
g_BackendBinding =
std::unique_ptr<utils::BackendBinding>(utils::CreateBinding(g_backendType, window, g_device.Get()));
if (!g_BackendBinding) {
return false;
2022-02-19 05:33:56 +00:00
}
auto swapChainFormat = static_cast<wgpu::TextureFormat>(g_BackendBinding->GetPreferredSwapChainTextureFormat());
if (swapChainFormat == wgpu::TextureFormat::RGBA8UnormSrgb) {
swapChainFormat = wgpu::TextureFormat::RGBA8Unorm;
} else if (swapChainFormat == wgpu::TextureFormat::BGRA8UnormSrgb) {
swapChainFormat = wgpu::TextureFormat::BGRA8Unorm;
}
Log.report(logvisor::Info, FMT_STRING("Using swapchain format {}"), magic_enum::enum_name(swapChainFormat));
2022-02-19 05:33:56 +00:00
{
const auto descriptor = wgpu::SwapChainDescriptor{
.format = swapChainFormat,
.implementation = g_BackendBinding->GetSwapChainImplementation(),
};
g_swapChain = g_device.CreateSwapChain(nullptr, &descriptor);
}
{
2022-03-08 23:35:40 +00:00
const auto size = get_window_size();
2022-02-19 05:33:56 +00:00
g_graphicsConfig = GraphicsConfig{
2022-03-08 23:35:40 +00:00
.width = size.fb_width,
.height = size.fb_height,
2022-02-19 05:33:56 +00:00
.colorFormat = swapChainFormat,
.depthFormat = wgpu::TextureFormat::Depth32Float,
2022-05-27 19:52:16 +00:00
.msaaSamples = 1,
.textureAnisotropy = 16,
2022-02-19 05:33:56 +00:00
};
2022-05-09 21:13:38 +00:00
create_copy_pipeline();
2022-03-08 23:35:40 +00:00
resize_swapchain(size.fb_width, size.fb_height);
g_windowSize = size;
2022-02-19 05:33:56 +00:00
}
return true;
2022-02-19 05:33:56 +00:00
}
void shutdown() {
g_CopyBindGroupLayout = {};
g_CopyPipeline = {};
g_CopyBindGroup = {};
g_frameBuffer = {};
g_frameBufferResolved = {};
g_depthBuffer = {};
2022-02-19 05:33:56 +00:00
wgpuSwapChainRelease(g_swapChain.Release());
wgpuQueueRelease(g_queue.Release());
g_BackendBinding.reset();
wgpuDeviceRelease(g_device.Release());
g_Instance.reset();
}
void resize_swapchain(uint32_t width, uint32_t height) {
g_graphicsConfig.width = width;
g_graphicsConfig.height = height;
g_swapChain.Configure(g_graphicsConfig.colorFormat, wgpu::TextureUsage::RenderAttachment, width, height);
g_frameBuffer = create_render_texture(true);
g_frameBufferResolved = create_render_texture(false);
g_depthBuffer = create_depth_texture();
2022-05-09 21:13:38 +00:00
create_copy_bind_group();
2022-02-19 05:33:56 +00:00
}
} // namespace aurora::gpu