26#if defined(__EMSCRIPTEN__)
27 static constexpr wgpu::CallbackMode kWaitMode = wgpu::CallbackMode::AllowProcessEvents;
31 static constexpr wgpu::CallbackMode kWaitMode = wgpu::CallbackMode::WaitAnyOnly;
39 bool init_attempted =
false;
49 wgpu::Instance instance;
51 bool instance_attempted =
false;
60 static bool validate_device(
const wgpu::Device& device) {
65 wgpu::BufferDescriptor desc = {};
67 desc.usage = wgpu::BufferUsage::CopyDst;
69 wgpu::Buffer test = device.CreateBuffer(&desc);
70 return test !=
nullptr;
75 static GPU& getClassInstance() {
76 static GPU gpuInstance;
81 const wgpu::Device& get_device() {
82 return thread_device().device;
85 const wgpu::Instance& get_instance() {
89 const wgpu::Queue& get_queue() {
90 return thread_device().queue;
93 bool is_initialized() {
94 return thread_device().device !=
nullptr;
99 bool wait(wgpu::Future future,
const bool& done) {
100#if defined(__EMSCRIPTEN__)
103 instance.ProcessEvents();
104 emscripten_sleep(10);
107 instance.WaitAny(future, UINT64_MAX);
112 static constexpr wgpu::CallbackMode wait_mode() {
118 GPU& operator=(
const GPU&) =
delete;
120 GPU& operator=(
GPU&&) =
delete;
131 for (
const auto& entry : embedded_shaders::shaders) {
132 if (entry.id == shader_id) {
134 return std::string(entry.source);
138 throw std::invalid_argument(
139 std::string(
"GPU::readWGSLFile: unknown shader id '") + std::string(shader_id) +
140 "' (not found in embedded shaders)"
144 wgpu::ComputePipeline createPipeline(
const std::string& filename,
const std::string& label) {
145 wgpu::ShaderSourceWGSL wgsl;
147 wgsl.code = shaderCode.c_str();
148 wgpu::ShaderModuleDescriptor md = {};
149 md.nextInChain = &wgsl;
150 md.label = label.c_str();
151 wgpu::ShaderModule sm = get_device().CreateShaderModule(&md);
153 wgpu::ComputePipelineDescriptor cpd = {};
154 cpd.compute.module = sm;
155 cpd.compute.entryPoint =
"main";
156 return get_device().CreateComputePipeline(&cpd);
159 static uint32_t getAlignedBytesPerRow(uint32_t width, uint32_t bytesPerPixel = 4) {
160 uint32_t unaligned = width * bytesPerPixel;
161 uint32_t align = 256;
162 return (unaligned + align - 1) & ~(align - 1);
165 static void printShaderError(wgpu::ShaderModule shaderModule) {
166 shaderModule.GetCompilationInfo(
168 wgpu::CallbackMode::AllowProcessEvents,
170 [](wgpu::CompilationInfoRequestStatus status,
const wgpu::CompilationInfo* info) {
171 if (status != wgpu::CompilationInfoRequestStatus::Success || !info)
174 for (uint32_t i {0}; i < info->messageCount; ++i) {
175 const auto& msg = info->messages[i];
176 const std::string_view text(
177 msg.message.data ? msg.message.data :
"", msg.message.length
181 case wgpu::CompilationMessageType::Error:
183 "Shader Error Line {}:{} - {}", msg.lineNum, msg.linePos, text
186 case wgpu::CompilationMessageType::Warning:
188 "Shader Warning Line {}:{} - {}", msg.lineNum, msg.linePos, text
193 "Shader Info Line {}:{} - {}", msg.lineNum, msg.linePos, text
205 ThreadDevice& td = thread_device();
206 if (td.init_attempted)
208 td.init_attempted =
true;
210 std::lock_guard<std::mutex> lock(mutex_);
211 if (!init_instance())
216 wgpu::Adapter adapter = request_adapter();
220 wgpu::Device device = request_device(adapter);
221 if (!validate_device(device)) {
222 IMG2NUM_LOG_WARN(
"Fatal: Could not get WebGPU Device. Falling back to CPU.");
226 td.queue = device.GetQueue();
227 td.device = std::move(device);
228 IMG2NUM_LOG_INFO(
"GPU Fully Initialized.");
233 bool init_instance() {
234 if (instance_attempted)
235 return instance !=
nullptr;
236 instance_attempted =
true;
238 wgpu::InstanceDescriptor instanceDesc = {};
239#if !defined(__EMSCRIPTEN__)
241 static constexpr wgpu::InstanceFeatureName kTimedWaitAny =
242 wgpu::InstanceFeatureName::TimedWaitAny;
243 instanceDesc.requiredFeatureCount = 1;
244 instanceDesc.requiredFeatures = &kTimedWaitAny;
246 instance = wgpu::CreateInstance(&instanceDesc);
249 IMG2NUM_LOG_WARN(
"Fatal: WebGPU instance creation failed. Falling back to CPU.");
257 wgpu::Adapter request_adapter() {
258 IMG2NUM_LOG_DEBUG(
"Requesting Adapter...");
259 wgpu::Adapter adapter;
260 bool adapter_ready =
false;
261 wgpu::Future future = instance.RequestAdapter(
263 [&](wgpu::RequestAdapterStatus status, wgpu::Adapter a, wgpu::StringView msg) {
264 if (status == wgpu::RequestAdapterStatus::Success) {
265 adapter = std::move(a);
266 IMG2NUM_LOG_INFO(
"Adapter Acquired");
269 "Adapter Failed: {}", std::string_view(msg.data ? msg.data :
"", msg.length)
272 adapter_ready =
true;
275 wait(future, adapter_ready);
278 IMG2NUM_LOG_WARN(
"Fatal: Could not get WebGPU Adapter. Falling back to CPU.");
281 if (wgpu::AdapterInfo info; adapter.GetInfo(&info) != wgpu::Status::Success ||
282 info.backendType == wgpu::BackendType::Null) {
283 IMG2NUM_LOG_WARN(
"No usable WebGPU adapter found. Falling back to CPU.");
290 wgpu::Device request_device(
const wgpu::Adapter& adapter) {
291 IMG2NUM_LOG_DEBUG(
"Requesting Device...");
293 wgpu::DeviceDescriptor deviceDesc = {};
294 deviceDesc.SetUncapturedErrorCallback([](
const wgpu::Device&, wgpu::ErrorType type,
295 wgpu::StringView msg) {
297 std::string err_str = (msg.data && msg.length > 0) ? std::string(msg.data, msg.length)
298 :
"Unknown Error (Null message)";
302 "\n[WEBGPU FATAL ERROR] Type: {} | Msg: {}\n",
static_cast<uint32_t
>(type), err_str
305 deviceDesc.SetDeviceLostCallback(
306#
if defined(__EMSCRIPTEN__)
307 wgpu::CallbackMode::AllowProcessEvents,
310 wgpu::CallbackMode::AllowSpontaneous,
312 [](
const wgpu::Device&, wgpu::DeviceLostReason reason, wgpu::StringView msg) {
313 std::string err_msg = (msg.data && msg.length > 0)
314 ? std::string(msg.data, msg.length)
315 :
"Unknown device lost reason";
317 if (reason == wgpu::DeviceLostReason::CallbackCancelled ||
318 reason == wgpu::DeviceLostReason::Destroyed) {
322 "[DEVICE LOST] Reason: {} Msg: {}",
static_cast<int>(reason), err_msg
327#if !defined(__EMSCRIPTEN__)
330 static constexpr wgpu::FeatureName kImplicitSync =
331 wgpu::FeatureName::ImplicitDeviceSynchronization;
332 if (adapter.HasFeature(kImplicitSync)) {
333 deviceDesc.requiredFeatureCount = 1;
334 deviceDesc.requiredFeatures = &kImplicitSync;
339 wgpu::Limits supportedLimits;
340 wgpu::Limits requiredLimits;
341 if (adapter.GetLimits(&supportedLimits)) {
345 requiredLimits = supportedLimits;
347 IMG2NUM_LOG_DEBUG(
"maxBufferSize: {}", requiredLimits.maxBufferSize);
349 "maxStorageBufferBindingSize: {}", requiredLimits.maxStorageBufferBindingSize
352 deviceDesc.requiredLimits = &requiredLimits;
356 bool device_ready =
false;
357 wgpu::Future future = adapter.RequestDevice(
358 &deviceDesc, kWaitMode,
359 [&](wgpu::RequestDeviceStatus status, wgpu::Device d, wgpu::StringView msg) {
360 if (status == wgpu::RequestDeviceStatus::Success) {
361 device = std::move(d);
362 IMG2NUM_LOG_INFO(
"Device Acquired");
365 "Device Failed: {}", msg.data && msg.length > 0
366 ? std::string(msg.data, msg.length)
373 wait(future, device_ready);