diff --git a/src/main.c b/src/main.c index bcffe66..e95b65c 100644 --- a/src/main.c +++ b/src/main.c @@ -1,6 +1,52 @@ +#include +#include #include #include +WGPUAdapter requestAdapterSync(WGPUInstance instance, + WGPURequestAdapterOptions const *options) { + typedef struct { + WGPUAdapter adapter; + bool requestEnded; + } UserData; + + UserData userData = {.adapter = NULL, .requestEnded = false}; + + // Callback called by wgpuInstanceRequestAdapter when the request returns + // This is a C++ lambda function, but could be any function defined in the + // global scope. It must be non-capturing (the brackets [] are empty) so + // that it behaves like a regular C function pointer, which is what + // wgpuInstanceRequestAdapter expects (WebGPU being a C API). The workaround + // is to convey what we want to capture through the pUserData pointer, + // provided as the last argument of wgpuInstanceRequestAdapter and received + // by the callback as its last argument. + auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, + WGPUAdapter adapter, char const *message, + void *pUserData) { + UserData &userData = *reinterpret_cast(pUserData); + if (status == WGPURequestAdapterStatus_Success) { + userData.adapter = adapter; + } else { + std::cout << "Could not get WebGPU adapter: " << message << std::endl; + } + userData.requestEnded = true; + }; + + // Call to the WebGPU request adapter procedure + wgpuInstanceRequestAdapter(instance /* equivalent of navigator.gpu */, + options, onAdapterRequestEnded, (void *)&userData); + + // We wait until userData.requestEnded gets true + { + {Wait for request to end + } + } + + assert(userData.requestEnded); + + return userData.adapter; +} + int main() { // We create a descriptor WGPUInstanceDescriptor desc = {};