Misc amends (8381)

This commit is contained in:
ocornut
2025-09-24 16:41:25 +02:00
parent 46ca8bc16f
commit 4deba36e83
11 changed files with 388 additions and 402 deletions

View File

@@ -1,4 +1,4 @@
// Dear ImGui: standalone example application for using GLFW + WebGPU
// Dear ImGui: standalone example application for using SDL3 + WebGPU
// - Emscripten is supported for publishing on web. See https://emscripten.org.
// - Dawn is used as a WebGPU implementation on desktop.
@@ -14,36 +14,31 @@
#include "imgui_impl_wgpu.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/html5.h>
#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
#include <emscripten/html5_webgpu.h>
#endif
#include "../libs/emscripten/emscripten_mainloop_stub.h"
#endif
#include <SDL3/SDL.h>
#include <webgpu/webgpu.h>
#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
#include <webgpu/webgpu_cpp.h>
#endif
// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/html5.h>
#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
#include <emscripten/html5_webgpu.h>
#endif
#include "../libs/emscripten/emscripten_mainloop_stub.h"
#endif
// Global WebGPU required states
#include <webgpu/webgpu.h>
#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
#include <webgpu/webgpu_cpp.h>
#endif
// Data
WGPUInstance wgpu_instance = nullptr;
WGPUDevice wgpu_device = nullptr;
WGPUSurface wgpu_surface = nullptr;
WGPUQueue wgpu_queue = nullptr;
WGPUSurfaceConfiguration wgpu_surface_configuration {};
int wgpu_surface_width = 1280;
int wgpu_surface_height = 720;
int wgpu_surface_height = 800;
// Forward declarations
static bool InitWGPU(void* window);
@@ -52,38 +47,36 @@ void ResizeSurface(int width, int height)
{
wgpu_surface_configuration.width = wgpu_surface_width = width;
wgpu_surface_configuration.height = wgpu_surface_height = height;
wgpuSurfaceConfigure( wgpu_surface, (WGPUSurfaceConfiguration *) &wgpu_surface_configuration );
wgpuSurfaceConfigure( wgpu_surface, (WGPUSurfaceConfiguration*)&wgpu_surface_configuration );
}
static void ReleaseTextureAndConfigureSurface(WGPUTexture &texture, int fb_width, int fb_height)
static void ReleaseTextureAndConfigureSurface(WGPUTexture& texture, int fb_width, int fb_height)
{
if (texture)
wgpuTextureRelease(texture);
if ( fb_width > 0 && fb_height > 0 )
if (fb_width > 0 && fb_height > 0)
ResizeSurface(fb_width, fb_height);
}
// Main code
int main(int, char**)
{
#if defined(__linux__)
// SDL3 default is "x11" (it works also in "wayland"), uncomment the line below to use "wayland"
// SDL_SetHint(SDL_HINT_VIDEO_DRIVER, "wayland");
#endif
// Init SDL
if (!SDL_Init(SDL_INIT_VIDEO ))
// Setup SDL
// [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function]
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
{
printf("Error: SDL_Init(): %s\n", SDL_GetError());
return EXIT_FAILURE;
return 1;
}
// Create SDL window graphics context
float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); // FIXME-WGPU: Test this?
SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE;
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+WebGPU example", wgpu_surface_width, wgpu_surface_height, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return EXIT_FAILURE;
return 1;
}
// Initialize WGPU
@@ -100,6 +93,11 @@ int main(int, char**)
ImGui::StyleColorsDark();
//ImGui::StyleColorsLight();
// Setup scaling
ImGuiStyle& style = ImGui::GetStyle();
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)
style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose)
// Setup Platform/Renderer backends
ImGui_ImplSDL3_InitForOther(window);
@@ -114,19 +112,18 @@ int main(int, char**)
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author!
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
// - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details.
// - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
//style.FontSizeBase = 20.0f;
//io.Fonts->AddFontDefault();
#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
//io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f);
//io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
//IM_ASSERT(font != nullptr);
#endif
@@ -135,47 +132,50 @@ int main(int, char**)
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
SDL_Event event;
bool canCloseWindow = false;
// Main loop
bool done = false;
#ifdef __EMSCRIPTEN__
// For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
// You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
io.IniFilename = nullptr;
EMSCRIPTEN_MAINLOOP_BEGIN
#else
while (!canCloseWindow)
while (!done)
#endif
{
while (SDL_PollEvent(&event))
{
ImGui_ImplSDL3_ProcessEvent(&event);
if (event.type == SDL_EVENT_QUIT ||
(event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)))
canCloseWindow = true;
}
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function]
SDL_Event event;
while (SDL_PollEvent(&event))
{
ImGui_ImplSDL3_ProcessEvent(&event);
if (event.type == SDL_EVENT_QUIT)
done = true;
if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
done = true;
}
// [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function]
// React to changes in screen size
int width, height;
SDL_GetWindowSize(window, &width, &height);
if (width != wgpu_surface_width || height != wgpu_surface_height)
{
ImGui_ImplWGPU_InvalidateDeviceObjects();
ImGui_ImplWGPU_InvalidateDeviceObjects(); // FIXME-WGPU: Why doing this? this will recreate all font textures etc.
ResizeSurface(width, height);
ImGui_ImplWGPU_CreateDeviceObjects();
//continue;
}
WGPUSurfaceTexture surfaceTexture;
wgpuSurfaceGetCurrentTexture(wgpu_surface, &surfaceTexture);
// Check SurfaceTexture status, if NOT optimal status we try to re-configure Surface
if (!ImGui_ImplWGPU_CheckSurfaceTextureOptimalStatus_Helper(surfaceTexture.status)) {
// Check if surface texture is not optimal and try to re-configure Surface
if (!ImGui_ImplWGPU_CheckSurfaceTextureOptimalStatus_Helper(surfaceTexture.status))
{
ReleaseTextureAndConfigureSurface(surfaceTexture.texture, width, height);
continue;
}
@@ -274,6 +274,7 @@ int main(int, char**)
#endif
// Cleanup
// [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function]
ImGui_ImplWGPU_Shutdown();
ImGui_ImplSDL3_Shutdown();
ImGui::DestroyContext();
@@ -284,39 +285,39 @@ int main(int, char**)
wgpuDeviceRelease(wgpu_device);
wgpuInstanceRelease(wgpu_instance);
// Terminate SDL
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
return 0;
}
#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
static WGPUAdapter GetAdapter(wgpu::Instance &instance)
static WGPUAdapter GetAdapter(wgpu::Instance& instance)
{
wgpu::Adapter acquiredAdapter;
wgpu::RequestAdapterOptions adapterOptions;
auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message) {
auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message)
{
if (status != wgpu::RequestAdapterStatus::Success)
{
printf("Failed to get an adapter: %s\n", message.data);
return;
}
acquiredAdapter = std::move(adapter);
acquiredAdapter = std::move(adapter); // FIXME-WGPU: no need to use std::move?
};
// Synchronously (wait until) acquire Adapter
wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapterOptions, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) };
wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX);
assert(acquiredAdapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request");
IM_ASSERT(acquiredAdapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request");
#ifndef NDEBUG
ImGui_ImplWGPU_PrintAdapterInfo_Helper(acquiredAdapter.Get());
#endif
return acquiredAdapter.MoveToCHandle();
}
static WGPUDevice GetDevice(wgpu::Instance &instance, wgpu::Adapter &adapter)
static WGPUDevice GetDevice(wgpu::Instance &instance, wgpu::Adapter& adapter)
{
// Set device callback functions
wgpu::DeviceDescriptor deviceDesc;
@@ -324,7 +325,8 @@ static WGPUDevice GetDevice(wgpu::Instance &instance, wgpu::Adapter &adapter)
deviceDesc.SetUncapturedErrorCallback(ImGui_ImplWGPU_DAWN_ErrorCallback_Helper);
wgpu::Device acquiredDevice;
auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device localDevice, wgpu::StringView message) {
auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device localDevice, wgpu::StringView message)
{
if (status != wgpu::RequestDeviceStatus::Success)
{
printf("Failed to get an device: %s\n", message.data);
@@ -336,7 +338,7 @@ static WGPUDevice GetDevice(wgpu::Instance &instance, wgpu::Adapter &adapter)
// Synchronously (wait until) get Device
wgpu::Future waitDeviceFunc { adapter.RequestDevice(&deviceDesc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) };
wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX);
assert(acquiredDevice != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request");
IM_ASSERT(acquiredDevice != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request");
return acquiredDevice.MoveToCHandle();
}
#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
@@ -344,36 +346,40 @@ static WGPUDevice GetDevice(wgpu::Instance &instance, wgpu::Adapter &adapter)
// Adapter and device initialization via JS
EM_ASYNC_JS( void, getAdapterAndDeviceViaJS, (),
{
if (!navigator.gpu) throw Error("WebGPU not supported.");
if (!navigator.gpu)
throw Error("WebGPU not supported.");
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
Module.preinitializedWebGPUDevice = device;
} );
#else // __EMSCRIPTEN__
static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void *userdata1, void *userdata2)
static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2)
{
if (status == WGPURequestAdapterStatus_Success)
{
WGPUAdapter *extAdapter = (WGPUAdapter *) userdata1;
WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1;
*extAdapter = adapter;
}
else
printf("Request_adapter status=%#.8x message=%.*s\n", status, (int) message.length, message.data);
{
printf("Request_adapter status=%#.8x message=%.*s\n", status, (int)message.length, message.data);
}
}
static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void *userdata1, void *userdata2)
static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2)
{
if (status == WGPURequestDeviceStatus_Success)
{
WGPUDevice *extDevice = (WGPUDevice *) userdata1;
WGPUDevice* extDevice = (WGPUDevice*)userdata1;
*extDevice = device;
}
else
printf("Request_device status=%#.8x message=%.*s\n", status, (int) message.length, message.data);
{
printf("Request_device status=%#.8x message=%.*s\n", status, (int message.length, message.data);
}
}
static WGPUAdapter GetAdapter(WGPUInstance &instance)
static WGPUAdapter GetAdapter(WGPUInstance& instance)
{
WGPURequestAdapterOptions adapterOptions = {};
@@ -383,7 +389,7 @@ static WGPUAdapter GetAdapter(WGPUInstance &instance)
adapterCallbackInfo.userdata1 = &localAdapter;
wgpuInstanceRequestAdapter(wgpu_instance, &adapterOptions, adapterCallbackInfo);
assert(localAdapter && "Error on Adapter request");
IM_ASSERT(localAdapter && "Error on Adapter request");
#ifndef NDEBUG
ImGui_ImplWGPU_PrintAdapterInfo_Helper(localAdapter);
@@ -392,7 +398,7 @@ static WGPUAdapter GetAdapter(WGPUInstance &instance)
return localAdapter;
}
static WGPUDevice GetDevice(WGPUAdapter &adapter)
static WGPUDevice GetDevice(WGPUAdapter& adapter)
{
static WGPUDevice localDevice;
WGPURequestDeviceCallbackInfo deviceCallbackInfo = {};
@@ -400,7 +406,7 @@ static WGPUDevice GetDevice(WGPUAdapter &adapter)
deviceCallbackInfo.userdata1 = &localDevice;
wgpuAdapterRequestDevice(adapter, NULL, deviceCallbackInfo);
assert(localDevice && "Error on Device request");
IM_ASSERT(localDevice && "Error on Device request");
return localDevice;
}
@@ -429,7 +435,7 @@ static bool InitWGPU(void* window)
surfaceDesc.nextInChain = &canvasDesc;
wgpu::Surface surface = instance.CreateSurface(&surfaceDesc) ;
#else
wgpu::Surface surface = ImGui_ImplSDL3_CreateWGPUSurface_Helper(instance.Get(), (SDL_Window *) window);
wgpu::Surface surface = ImGui_ImplSDL3_CreateWGPUSurface(instance.Get(), (SDL_Window*)window);
#endif
if (!surface)
return false;
@@ -450,7 +456,7 @@ static bool InitWGPU(void* window)
#ifdef __EMSCRIPTEN__
getAdapterAndDeviceViaJS();
wgpu_device = emscripten_webgpu_get_device();
wgpu_device = emscripten_webgpu_get_device();
assert(wgpu_device != nullptr && "Error creating the Device");
WGPUSurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {};
@@ -471,8 +477,7 @@ static bool InitWGPU(void* window)
wgpu_device = GetDevice(adapter);
// Create the surface.
wgpu_surface = ImGui_ImplSDL3_CreateWGPUSurface_Helper(wgpu_instance, (SDL_Window *) window);
wgpu_surface = ImGui_ImplSDL3_CreateWGPUSurface(wgpu_instance, (SDL_Window*)window);
if (!wgpu_surface)
return false;
@@ -492,8 +497,7 @@ static bool InitWGPU(void* window)
wgpu_surface_configuration.format = preferred_fmt;
wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration);
wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
return true;
}