23.2 KB、538行 生 Blame 履歴
1// Dear ImGui: standalone example application for using SDL3 + WebGPU
2// - Emscripten is supported for publishing on web. See https://emscripten.org.
3// - Dawn is used as a WebGPU implementation on desktop.
4
5// Learn about Dear ImGui:
6// - FAQ https://dearimgui.com/faq
7// - Getting Started https://dearimgui.com/getting-started
8// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
9// - Introduction, links and more at the top of imgui.cpp
10
11
12#include "imgui.h"
13#include "imgui_impl_sdl3.h"
14#include "imgui_impl_wgpu.h"
15#include <stdio.h>
16#include <stdlib.h>
17#include <SDL3/SDL.h>
18
19// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
20#ifdef __EMSCRIPTEN__
21#include <emscripten.h>
22#include <emscripten/html5.h>
23#include "../libs/emscripten/emscripten_mainloop_stub.h"
24#endif
25
26#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
27#include <webgpu/webgpu_cpp.h>
28#endif
29
30// Data
31static WGPUInstance wgpu_instance = nullptr;
32static WGPUDevice wgpu_device = nullptr;
33static WGPUSurface wgpu_surface = nullptr;
34static WGPUQueue wgpu_queue = nullptr;
35static WGPUSurfaceConfiguration wgpu_surface_configuration = {};
36static int wgpu_surface_width = 1280;
37static int wgpu_surface_height = 800;
38
39// Forward declarations
40static bool InitWGPU(SDL_Window* window);
41WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window);
42
43static void ResizeSurface(int width, int height)
44{
45 wgpu_surface_configuration.width = wgpu_surface_width = width;
46 wgpu_surface_configuration.height = wgpu_surface_height = height;
47 wgpuSurfaceConfigure( wgpu_surface, (WGPUSurfaceConfiguration*)&wgpu_surface_configuration );
48}
49
50// Main code
51int main(int, char**)
52{
53 // Setup SDL
54 // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function]
55 if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
56 {
57 printf("Error: SDL_Init(): %s\n", SDL_GetError());
58 return 1;
59 }
60
61 // Create SDL window graphics context
62 float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
63 SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE;
64 wgpu_surface_width = (int)(wgpu_surface_width * main_scale);
65 wgpu_surface_height = (int)(wgpu_surface_height * main_scale);
66 SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+WebGPU example", wgpu_surface_width, wgpu_surface_height, window_flags);
67 if (window == nullptr)
68 {
69 printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
70 return 1;
71 }
72
73 // Initialize WGPU
74 InitWGPU(window);
75
76 // Setup Dear ImGui context
77 IMGUI_CHECKVERSION();
78 ImGui::CreateContext();
79 ImGuiIO& io = ImGui::GetIO(); (void)io;
80 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
81 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
82
83 // Setup Dear ImGui style
84 ImGui::StyleColorsDark();
85 //ImGui::StyleColorsLight();
86
87 // Setup scaling
88 ImGuiStyle& style = ImGui::GetStyle();
89 style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
90 style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
91
92 // Setup Platform/Renderer backends
93 ImGui_ImplSDL3_InitForOther(window);
94
95 ImGui_ImplWGPU_InitInfo init_info;
96 init_info.Device = wgpu_device;
97 init_info.NumFramesInFlight = 3;
98 init_info.RenderTargetFormat = wgpu_surface_configuration.format;
99 init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
100 ImGui_ImplWGPU_Init(&init_info);
101
102 // Load Fonts
103 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
104 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
105 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
106 // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
107 // - Read 'docs/FONTS.md' for more instructions and details.
108 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
109 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
110 // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
111 //style.FontSizeBase = 20.0f;
112 //io.Fonts->AddFontDefaultVector();
113 //io.Fonts->AddFontDefaultBitmap();
114#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
115 //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
116 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
117 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
118 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
119 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
120 //IM_ASSERT(font != nullptr);
121#endif
122
123 // Our state
124 bool show_demo_window = true;
125 bool show_another_window = false;
126 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
127
128 // Main loop
129 bool done = false;
130#ifdef __EMSCRIPTEN__
131 // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
132 // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
133 io.IniFilename = nullptr;
134 EMSCRIPTEN_MAINLOOP_BEGIN
135#else
136 while (!done)
137#endif
138 {
139 // Poll and handle events (inputs, window resize, etc.)
140 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
141 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
142 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
143 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
144 // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function]
145 SDL_Event event;
146 while (SDL_PollEvent(&event))
147 {
148 ImGui_ImplSDL3_ProcessEvent(&event);
149 if (event.type == SDL_EVENT_QUIT)
150 done = true;
151 if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
152 done = true;
153 }
154
155 // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function]
156 // React to changes in screen size
157 int width, height;
158 SDL_GetWindowSize(window, &width, &height);
159 if (width != wgpu_surface_width || height != wgpu_surface_height)
160 ResizeSurface(width, height);
161
162 // Check surface status for error. If texture is not optimal, try to reconfigure the surface.
163 WGPUSurfaceTexture surface_texture;
164 wgpuSurfaceGetCurrentTexture(wgpu_surface, &surface_texture);
165 if (ImGui_ImplWGPU_IsSurfaceStatusError(surface_texture.status))
166 {
167 fprintf(stderr, "Unrecoverable Surface Texture status=%#.8x\n", surface_texture.status);
168 abort();
169 }
170 if (ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(surface_texture.status))
171 {
172 if (surface_texture.texture)
173 wgpuTextureRelease(surface_texture.texture);
174 if (width > 0 && height > 0)
175 ResizeSurface(width, height);
176 continue;
177 }
178
179 // Start the Dear ImGui frame
180 ImGui_ImplWGPU_NewFrame();
181 ImGui_ImplSDL3_NewFrame();
182 ImGui::NewFrame();
183
184 // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
185 if (show_demo_window)
186 ImGui::ShowDemoWindow(&show_demo_window);
187
188 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
189 {
190 static float f = 0.0f;
191 static int counter = 0;
192
193 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
194
195 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
196 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
197 ImGui::Checkbox("Another Window", &show_another_window);
198
199 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
200 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
201
202 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
203 counter++;
204 ImGui::SameLine();
205 ImGui::Text("counter = %d", counter);
206
207 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
208 ImGui::End();
209 }
210
211 // 3. Show another simple window.
212 if (show_another_window)
213 {
214 ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
215 ImGui::Text("Hello from another window!");
216 if (ImGui::Button("Close Me"))
217 show_another_window = false;
218 ImGui::End();
219 }
220
221 // Rendering
222 ImGui::Render();
223
224 WGPUTextureViewDescriptor view_desc = {};
225 view_desc.format = wgpu_surface_configuration.format;
226 view_desc.dimension = WGPUTextureViewDimension_2D;
227 view_desc.mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED;
228 view_desc.arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED;
229 view_desc.aspect = WGPUTextureAspect_All;
230
231 WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, &view_desc);
232
233 WGPURenderPassColorAttachment color_attachments = {};
234 color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
235 color_attachments.loadOp = WGPULoadOp_Clear;
236 color_attachments.storeOp = WGPUStoreOp_Store;
237 color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
238 color_attachments.view = texture_view;
239
240 WGPURenderPassDescriptor render_pass_desc = {};
241 render_pass_desc.colorAttachmentCount = 1;
242 render_pass_desc.colorAttachments = &color_attachments;
243 render_pass_desc.depthStencilAttachment = nullptr;
244
245 WGPUCommandEncoderDescriptor enc_desc = {};
246 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
247
248 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
249 ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
250 wgpuRenderPassEncoderEnd(pass);
251
252 WGPUCommandBufferDescriptor cmd_buffer_desc = {};
253 WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
254 wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer);
255
256#ifndef __EMSCRIPTEN__
257 wgpuSurfacePresent(wgpu_surface);
258 // Tick needs to be called in Dawn to display validation errors
259#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
260 wgpuDeviceTick(wgpu_device);
261#endif
262#endif
263 wgpuTextureViewRelease(texture_view);
264 wgpuRenderPassEncoderRelease(pass);
265 wgpuCommandEncoderRelease(encoder);
266 wgpuCommandBufferRelease(cmd_buffer);
267 }
268#ifdef __EMSCRIPTEN__
269 EMSCRIPTEN_MAINLOOP_END;
270#endif
271
272 // Cleanup
273 // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function]
274 ImGui_ImplWGPU_Shutdown();
275 ImGui_ImplSDL3_Shutdown();
276 ImGui::DestroyContext();
277
278 wgpuSurfaceUnconfigure(wgpu_surface);
279 wgpuSurfaceRelease(wgpu_surface);
280 wgpuQueueRelease(wgpu_queue);
281 wgpuDeviceRelease(wgpu_device);
282 wgpuInstanceRelease(wgpu_instance);
283
284 SDL_DestroyWindow(window);
285 SDL_Quit();
286
287 return 0;
288}
289
290#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
291static WGPUAdapter RequestAdapter(wgpu::Instance& instance)
292{
293 wgpu::Adapter acquired_adapter;
294 wgpu::RequestAdapterOptions adapter_options;
295 auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message)
296 {
297 if (status != wgpu::RequestAdapterStatus::Success)
298 {
299 printf("Failed to get an adapter: %s\n", message.data);
300 return;
301 }
302 acquired_adapter = std::move(adapter);
303 };
304
305 // Synchronously (wait until) acquire Adapter
306 wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapter_options, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) };
307 wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX);
308 IM_ASSERT(acquired_adapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request");
309 return acquired_adapter.MoveToCHandle();
310}
311
312static WGPUDevice RequestDevice(wgpu::Instance& instance, wgpu::Adapter& adapter)
313{
314 // Set device callback functions
315 wgpu::DeviceDescriptor device_desc;
316 device_desc.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous,
317 [](const wgpu::Device&, wgpu::DeviceLostReason type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetDeviceLostReasonName((WGPUDeviceLostReason)type), msg.data); }
318 );
319 device_desc.SetUncapturedErrorCallback(
320 [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetErrorTypeName((WGPUErrorType)type), msg.data); }
321 );
322
323 wgpu::Device acquired_device;
324 auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device local_device, wgpu::StringView message)
325 {
326 if (status != wgpu::RequestDeviceStatus::Success)
327 {
328 printf("Failed to get an device: %s\n", message.data);
329 return;
330 }
331 acquired_device = std::move(local_device);
332 };
333
334 // Synchronously (wait until) get Device
335 wgpu::Future waitDeviceFunc { adapter.RequestDevice(&device_desc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) };
336 wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX);
337 IM_ASSERT(acquired_device != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request");
338 return acquired_device.MoveToCHandle();
339}
340#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
341static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2)
342{
343 IM_UNUSED(userdata2);
344 if (status == WGPURequestAdapterStatus_Success)
345 {
346 WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1;
347 *extAdapter = adapter;
348 }
349 else
350 {
351 printf("Request_adapter status=%#.8x message=%.*s\n", status, (int)message.length, message.data);
352 }
353}
354
355static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2)
356{
357 IM_UNUSED(userdata2);
358 if (status == WGPURequestDeviceStatus_Success)
359 {
360 WGPUDevice* extDevice = (WGPUDevice*)userdata1;
361 *extDevice = device;
362 }
363 else
364 {
365 printf("Request_device status=%#.8x message=%.*s\n", status, (int)message.length, message.data);
366 }
367}
368
369static WGPUAdapter RequestAdapter(WGPUInstance& instance)
370{
371 WGPURequestAdapterOptions adapter_options = {};
372
373 WGPUAdapter local_adapter = nullptr;
374 WGPURequestAdapterCallbackInfo adapterCallbackInfo = {};
375 adapterCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly;
376 adapterCallbackInfo.callback = handle_request_adapter;
377 adapterCallbackInfo.userdata1 = &local_adapter;
378
379 WGPUFuture future = wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo);
380 WGPUFutureWaitInfo waitInfo = { future, false };
381 wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull);
382 IM_ASSERT(local_adapter && "Error on Adapter request");
383 return local_adapter;
384}
385
386static WGPUDevice RequestDevice(WGPUInstance& instance, WGPUAdapter& adapter)
387{
388 WGPUDevice local_device = nullptr;
389 WGPURequestDeviceCallbackInfo deviceCallbackInfo = {};
390 deviceCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly;
391 deviceCallbackInfo.callback = handle_request_device;
392 deviceCallbackInfo.userdata1 = &local_device;
393 WGPUFuture future = wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo);
394 WGPUFutureWaitInfo waitInfo = { future, false };
395 wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull);
396 IM_ASSERT(local_device && "Error on Device request");
397 return local_device;
398}
399#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU
400
401static bool InitWGPU(SDL_Window* window)
402{
403 WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities
404
405 // Google DAWN backend: Adapter and Device acquisition, Surface creation
406#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
407 wgpu::InstanceDescriptor instance_desc = {};
408 static constexpr wgpu::InstanceFeatureName timedWaitAny = wgpu::InstanceFeatureName::TimedWaitAny;
409 instance_desc.requiredFeatureCount = 1;
410 instance_desc.requiredFeatures = &timedWaitAny;
411 wgpu::Instance instance = wgpu::CreateInstance(&instance_desc);
412
413 wgpu::Adapter adapter = RequestAdapter(instance);
414 ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter.Get());
415
416 wgpu_device = RequestDevice(instance, adapter);
417
418 // Create the surface.
419#ifdef __EMSCRIPTEN__
420 wgpu::EmscriptenSurfaceSourceCanvasHTMLSelector canvas_desc = {};
421 canvas_desc.selector = "#canvas";
422
423 wgpu::SurfaceDescriptor surface_desc = {};
424 surface_desc.nextInChain = &canvas_desc;
425 wgpu::Surface surface = instance.CreateSurface(&surface_desc);
426#else
427 wgpu::Surface surface = CreateWGPUSurface(instance.Get(), window);
428#endif
429 if (!surface)
430 return false;
431
432 // Moving Dawn objects into WGPU handles
433 wgpu_instance = instance.MoveToCHandle();
434 wgpu_surface = surface.MoveToCHandle();
435
436 WGPUSurfaceCapabilities surface_capabilities = {};
437 wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities);
438
439 preferred_fmt = surface_capabilities.formats[0];
440
441 // WGPU backend: Adapter and Device acquisition, Surface creation
442#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
443 WGPUInstanceDescriptor instanceDesc = {};
444 WGPUInstanceFeatureName timedWaitAny = WGPUInstanceFeatureName_TimedWaitAny;
445 instanceDesc.requiredFeatureCount = 1;
446 instanceDesc.requiredFeatures = &timedWaitAny;
447 wgpu_instance = wgpuCreateInstance(&instanceDesc);
448
449#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
450 wgpuSetLogCallback(
451 [](WGPULogLevel level, WGPUStringView msg, void* userdata) { fprintf(stderr, "%s: %.*s\n", ImGui_ImplWGPU_GetLogLevelName(level), (int)msg.length, msg.data); }, nullptr
452 );
453 wgpuSetLogLevel(WGPULogLevel_Warn);
454#endif
455
456 WGPUAdapter adapter = RequestAdapter(wgpu_instance);
457 ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter);
458
459 wgpu_device = RequestDevice(wgpu_instance, adapter);
460
461 // Create the surface.
462 wgpu_surface = CreateWGPUSurface(wgpu_instance, window);
463 if (!wgpu_surface)
464 return false;
465
466 WGPUSurfaceCapabilities surface_capabilities = {};
467 wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities);
468
469 preferred_fmt = surface_capabilities.formats[0];
470#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU
471
472 wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo;
473 wgpu_surface_configuration.alphaMode = WGPUCompositeAlphaMode_Auto;
474 wgpu_surface_configuration.usage = WGPUTextureUsage_RenderAttachment;
475 wgpu_surface_configuration.width = wgpu_surface_width;
476 wgpu_surface_configuration.height = wgpu_surface_height;
477 wgpu_surface_configuration.device = wgpu_device;
478 wgpu_surface_configuration.format = preferred_fmt;
479
480 wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration);
481 wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
482
483 return true;
484}
485
486// SDL3 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend
487// As of today (2025/10) there is no "official" support in SDL3 to create a surface for WebGPU backend
488// This stub uses "low level" SDL3 calls to acquire information from a specific Window Manager.
489// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN.
490#ifndef __EMSCRIPTEN__
491
492#if defined(SDL_PLATFORM_WIN32)
493#ifndef WIN32_LEAN_AND_MEAN
494#define WIN32_LEAN_AND_MEAN 1
495#endif
496#include <windows.h>
497#endif
498
499WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window)
500{
501 SDL_PropertiesID propertiesID = SDL_GetWindowProperties(window);
502
503 ImGui_ImplWGPU_CreateSurfaceInfo create_info = {};
504 create_info.Instance = instance;
505#if defined(SDL_PLATFORM_MACOS)
506 {
507 create_info.System = "cocoa";
508 create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL);
509 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
510 }
511#elif defined(SDL_PLATFORM_LINUX)
512 if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0)
513 {
514 create_info.System = "wayland";
515 create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, NULL);
516 create_info.RawSurface = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL);
517 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
518 }
519 else if (!SDL_strcmp(SDL_GetCurrentVideoDriver(), "x11"))
520 {
521 create_info.System = "x11";
522 create_info.RawWindow = (void*)SDL_GetNumberProperty(propertiesID, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0);
523 create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL);
524 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
525 }
526#elif defined(SDL_PLATFORM_WIN32)
527 {
528 create_info.System = "win32";
529 create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
530 create_info.RawInstance = (void*)::GetModuleHandle(NULL);
531 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
532 }
533#else
534#error "Unsupported WebGPU native platform!"
535 return nullptr;
536#endif
537}
538#endif // #ifndef __EMSCRIPTEN__