### Initialize WebGPU and Request Adapter (C) Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This C code snippet demonstrates the initialization of the WebGPU API by creating an instance and asynchronously requesting a GPU adapter. It includes necessary headers, defines a callback function for adapter acquisition, and manages the adapter's reference count. The example utilizes `wgpuCreateInstance` and `wgpuInstanceRequestAdapter` for adapter retrieval and `wgpuInstanceProcessEvents` to handle callbacks. ```c #include #include // Callback invoked when adapter is ready void onAdapterReceived(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata) { if (status == WGPURequestAdapterStatus_Success) { printf("Adapter acquired successfully\n"); WGPUAdapter* adapterPtr = (WGPUAdapter*)userdata; *adapterPtr = adapter; wgpuAdapterAddRef(adapter); // Keep reference } else { printf("Failed to get adapter: %.*s\n", (int)message.length, message.data); } } int main() { // Create instance (entry point to WebGPU) WGPUInstanceDescriptor instanceDesc = { .nextInChain = NULL }; WGPUInstance instance = wgpuCreateInstance(&instanceDesc); // Request adapter asynchronously WGPUAdapter adapter = NULL; WGPURequestAdapterOptions options = { .nextInChain = NULL, .powerPreference = WGPUPowerPreference_HighPerformance, .forceFallbackAdapter = WGPU_FALSE }; WGPURequestAdapterCallbackInfo callbackInfo = { .mode = WGPUCallbackMode_AllowProcessEvents, .callback = onAdapterReceived, .userdata1 = &adapter, .userdata2 = NULL }; WGPUFuture future = wgpuInstanceRequestAdapter( instance, &options, callbackInfo); // Process callbacks on this thread while (adapter == NULL) { wgpuInstanceProcessEvents(instance); } // Cleanup wgpuAdapterRelease(adapter); wgpuInstanceRelease(instance); return 0; } ``` -------------------------------- ### Query Timestamp for Performance Measurement Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This example shows how to create and use timestamp queries to measure GPU performance, including setting up query sets and buffers. ```APIDOC ## Query Timestamp for Performance Measurement ### Description Create and use timestamp queries for GPU profiling and performance measurement. ### Method `wgpuDeviceCreateQuerySet` `wgpuDeviceCreateBuffer` `wgpuCommandEncoderWriteTimestamp` `wgpuCommandEncoderResolveQuerySet` ### Endpoint N/A (Function calls within command encoder) ### Parameters #### timestampExample - **device** (WGPUDevice) - The logical device. #### Query Set Creation - **device** (WGPUDevice) - The device to create the query set on. - **querySetDesc** (WGPUQuerySetDescriptor*) - Descriptor for the query set. - **type** (WGPUQueryType) - Must be `WGPUQueryType_Timestamp`. - **count** (uint32_t) - Number of timestamps to store (e.g., 2 for start/end). #### Buffer Creation - **device** (WGPUDevice) - The device to create the buffer on. - **bufferDesc** (WGPUBufferDescriptor*) - Descriptor for the buffer. - **usage** (WGPUBufferUsageFlags) - Must include `WGPUBufferUsage_QueryResolve` and `WGPUBufferUsage_CopySrc`. - **size** (size_t) - Size of the buffer (e.g., `count * sizeof(uint64_t)`). #### Timestamp Writing - **encoder** (WGPUCommandEncoder) - The command encoder. - **querySet** (WGPUQuerySet) - The query set. - **queryIndex** (uint32_t) - The index in the query set to write the timestamp. #### Query Resolution - **encoder** (WGPUCommandEncoder) - The command encoder. - **querySet** (WGPUQuerySet) - The query set. - **firstQuery** (uint32_t) - The index of the first query to resolve. - **queryCount** (uint32_t) - The number of queries to resolve. - **destination** (WGPUBuffer) - The buffer to write the resolved timestamps to. - **destinationOffset** (size_t) - The offset in the destination buffer. ### Request Example ```c // Create query set and buffer WGPUQuerySet querySet = wgpuDeviceCreateQuerySet(device, &querySetDesc); WGPUBuffer queryBuffer = wgpuDeviceCreateBuffer(device, &bufferDesc); // In command encoder WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device, NULL); wgpuCommandEncoderWriteTimestamp(encoder, querySet, 0); // Start timestamp // ... GPU work ... wgpuCommandEncoderWriteTimestamp(encoder, querySet, 1); // End timestamp wgpuCommandEncoderResolveQuerySet(encoder, querySet, 0, 2, queryBuffer, 0); // Submit and later map queryBuffer to read results ``` ### Response #### Success Response (200) N/A (Functions record commands; results are read from buffer after submission) #### Response Example N/A ``` -------------------------------- ### Example Usage of Struct-Chaining (C) Source: https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/StructChaining.md Demonstrates how to initialize and link extension structs (ext2, ext1) and then attach them to a base struct (base) to form a struct chain. This example illustrates setting data members and linking structs via the 'next' pointer. ```c WGPUMyStructExtension2 ext2 = WGPU_MY_STRUCT_EXTENSION2_INIT; // .chain.sType is already set correctly by the INIT macro. // .chain.next is set to NULL indicating the end of the chain. ext2.z = 2; WGPUMyStructExtension1 ext1 = WGPU_MY_STRUCT_EXTENSION1_INIT; // .chain.sType is already set correctly by the INIT macro. // .chain.next may be set in either of two ways, equivalently: ext1.chain.next = &ext2.chain; ext1.chain.next = (WGPUChainedStruct*) &ext2; ext1.y = 1; WGPUMyStructBase base = WGPU_MY_STRUCT_BASE_INIT; // Note: base structs do not have STypes (they are statically typed). base.nextInChain = &ext1.chain; base.x = 0; ``` -------------------------------- ### Generate webgpu.h from YAML Specification (Shell) Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This command-line example shows how to use a Go generator to create the `webgpu.h` header file from a YAML specification. It details the `make gen` command and the underlying Go script execution with its parameters, outlining the steps involved in validation, parsing, transformation, and generation. ```bash # Validate schema and regenerate header from YAML make gen # This runs: # go run ./gen -schema schema.json \ # -yaml webgpu.yml \ # -out-json webgpu.json \ # -out-header webgpu.h # The generator performs: # 1. JSON schema validation of webgpu.yml # 2. Detection of duplicate definitions # 3. Parsing YAML into Go structures # 4. Sorting and transformation of API elements # 5. Template-based C header generation # 6. JSON format output ``` -------------------------------- ### Create and Execute Compute Pipeline with WebGPU Native C Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Demonstrates the complete workflow for creating a compute pipeline and dispatching workgroups using the WebGPU native API in C. It covers shader module creation, bind group and pipeline layout setup, buffer and bind group creation, command encoding, submission, and resource cleanup. This function requires a valid WGPUDevice as input. ```c #include void computeExample(WGPUDevice device) { // Create compute shader const char* computeCode = "@group(0) @binding(0) var data: array;\n" "@compute @workgroup_size(64)\n" "fn main(@builtin(global_invocation_id) id: vec3) {\n" " data[id.x] = data[id.x] * 2.0;\n" "}\n"; WGPUShaderSourceWGSL source = { .chain = {.next = NULL, .sType = WGPUSType_ShaderSourceWGSL}, .code = {.data = computeCode, .length = WGPU_STRLEN} }; WGPUShaderModuleDescriptor shaderDesc = { .nextInChain = (WGPUChainedStruct*)&source, .label = {.data = "compute shader", .length = WGPU_STRLEN} }; WGPUShaderModule shader = wgpuDeviceCreateShaderModule( device, &shaderDesc); // Create bind group layout WGPUBindGroupLayoutEntry binding = { .binding = 0, .visibility = WGPUShaderStage_Compute, .buffer = { .type = WGPUBufferBindingType_Storage, .hasDynamicOffset = WGPU_FALSE, .minBindingSize = 0 } }; WGPUBindGroupLayoutDescriptor bglDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .entryCount = 1, .entries = &binding }; WGPUBindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout(device, &bglDesc); // Create pipeline layout WGPUPipelineLayoutDescriptor layoutDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .bindGroupLayoutCount = 1, .bindGroupLayouts = &bindGroupLayout }; WGPUPipelineLayout layout = wgpuDeviceCreatePipelineLayout( device, &layoutDesc); // Create compute pipeline WGPUComputePipelineDescriptor pipelineDesc = { .nextInChain = NULL, .label = {.data = "compute pipeline", .length = WGPU_STRLEN}, .layout = layout, .compute = { .nextInChain = NULL, .module = shader, .entryPoint = {.data = "main", .length = WGPU_STRLEN}, .constantCount = 0, .constants = NULL } }; WGPUComputePipeline pipeline = wgpuDeviceCreateComputePipeline( device, &pipelineDesc); // Create storage buffer WGPUBufferDescriptor bufferDesc = { .nextInChain = NULL, .label = {.data = "storage buffer", .length = WGPU_STRLEN}, .usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc, .size = 256 * sizeof(float), .mappedAtCreation = WGPU_FALSE }; WGPUBuffer buffer = wgpuDeviceCreateBuffer(device, &bufferDesc); // Create bind group WGPUBindGroupEntry bgEntry = { .binding = 0, .buffer = buffer, .offset = 0, .size = WGPU_WHOLE_SIZE }; WGPUBindGroupDescriptor bgDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .layout = bindGroupLayout, .entryCount = 1, .entries = &bgEntry }; WGPUBindGroup bindGroup = wgpuDeviceCreateBindGroup(device, &bgDesc); // Encode compute pass WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder( device, NULL); WGPUComputePassDescriptor passDesc = { .nextInChain = NULL, .label = {.data = "compute pass", .length = WGPU_STRLEN}, .timestampWrites = NULL }; WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass( encoder, &passDesc); wgpuComputePassEncoderSetPipeline(pass, pipeline); wgpuComputePassEncoderSetBindGroup(pass, 0, bindGroup, 0, NULL); wgpuComputePassEncoderDispatchWorkgroups(pass, 4, 1, 1); // 4*64=256 wgpuComputePassEncoderEnd(pass); WGPUCommandBuffer cmdBuffer = wgpuCommandEncoderFinish(encoder, NULL); // Submit WGPUQueue queue = wgpuDeviceGetQueue(device); wgpuQueueSubmit(queue, 1, &cmdBuffer); // Cleanup wgpuComputePassEncoderRelease(pass); wgpuCommandEncoderRelease(encoder); wgpuCommandBufferRelease(cmdBuffer); wgpuBindGroupRelease(bindGroup); wgpuBindGroupLayoutRelease(bindGroupLayout); wgpuPipelineLayoutRelease(layout); wgpuComputePipelineRelease(pipeline); wgpuBufferRelease(buffer); wgpuShaderModuleRelease(shader); wgpuQueueRelease(queue); } ``` -------------------------------- ### Encode Render Commands and Submit to GPU Queue (C) Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Encodes render commands for a single frame, including texture view creation, render pass setup, drawing, command buffer finalization, and submission to the GPU queue for presentation. It handles surface texture acquisition and cleanup of created resources. ```c #include void renderFrame(WGPUDevice device, WGPUSurface surface, WGPURenderPipeline pipeline) { // Get current surface texture WGPUSurfaceTexture surfaceTexture; wgpuSurfaceGetCurrentTexture(surface, &surfaceTexture); if (surfaceTexture.status != WGPUSurfaceGetCurrentTextureStatus_Success) { return; } // Create texture view WGPUTextureViewDescriptor viewDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .format = WGPUTextureFormat_BGRA8Unorm, .dimension = WGPUTextureViewDimension_2D, .baseMipLevel = 0, .mipLevelCount = 1, .baseArrayLayer = 0, .arrayLayerCount = 1, .aspect = WGPUTextureAspect_All }; WGPUTextureView view = wgpuTextureCreateView( surfaceTexture.texture, &viewDesc); // Create command encoder WGPUCommandEncoderDescriptor encoderDesc = { .nextInChain = NULL, .label = {.data = "render encoder", .length = WGPU_STRLEN} }; WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder( device, &encoderDesc); // Begin render pass WGPURenderPassColorAttachment colorAttachment = { .nextInChain = NULL, .view = view, .depthSlice = WGPU_DEPTH_SLICE_UNDEFINED, .resolveTarget = NULL, .loadOp = WGPULoadOp_Clear, .storeOp = WGPUStoreOp_Store, .clearValue = {0.0, 0.0, 0.0, 1.0} // Black }; WGPURenderPassDescriptor passDesc = { .nextInChain = NULL, .label = {.data = "render pass", .length = WGPU_STRLEN}, .colorAttachmentCount = 1, .colorAttachments = &colorAttachment, .depthStencilAttachment = NULL, .occlusionQuerySet = NULL, .timestampWrites = NULL }; WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass( encoder, &passDesc); // Record draw commands wgpuRenderPassEncoderSetPipeline(pass, pipeline); wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0); // 3 vertices wgpuRenderPassEncoderEnd(pass); wgpuRenderPassEncoderRelease(pass); // Finish encoding WGPUCommandBuffer cmdBuffer = wgpuCommandEncoderFinish( encoder, NULL); wgpuCommandEncoderRelease(encoder); // Submit to queue WGPUQueue queue = wgpuDeviceGetQueue(device); wgpuQueueSubmit(queue, 1, &cmdBuffer); wgpuCommandBufferRelease(cmdBuffer); // Present wgpuSurfacePresent(surface); // Cleanup wgpuTextureViewRelease(view); wgpuTextureRelease(surfaceTexture.texture); wgpuQueueRelease(queue); } ``` -------------------------------- ### Creating GPU Instance and Requesting Adapter Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Initializes the WebGPU instance and asynchronously requests a GPU adapter, which is a physical or virtual GPU. This is the first step in using the WebGPU API. ```APIDOC ## Creating GPU Instance and Requesting Adapter ### Description Initializes the WebGPU instance and asynchronously requests a GPU adapter, which is a physical or virtual GPU. This is the first step in using the WebGPU API. ### Method `wgpuCreateInstance`, `wgpuInstanceRequestAdapter` ### Endpoint N/A (Native C API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #include #include // Callback invoked when adapter is ready void onAdapterReceived(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata) { if (status == WGPURequestAdapterStatus_Success) { printf("Adapter acquired successfully\n"); WGPUAdapter* adapterPtr = (WGPUAdapter*)userdata; *adapterPtr = adapter; wgpuAdapterAddRef(adapter); // Keep reference } else { printf("Failed to get adapter: %.*s\n", (int)message.length, message.data); } } int main() { // Create instance (entry point to WebGPU) WGPUInstanceDescriptor instanceDesc = { .nextInChain = NULL }; WGPUInstance instance = wgpuCreateInstance(&instanceDesc); // Request adapter asynchronously WGPUAdapter adapter = NULL; WGPURequestAdapterOptions options = { .nextInChain = NULL, .powerPreference = WGPUPowerPreference_HighPerformance, .forceFallbackAdapter = WGPU_FALSE }; WGPURequestAdapterCallbackInfo callbackInfo = { .mode = WGPUCallbackMode_AllowProcessEvents, .callback = onAdapterReceived, .userdata1 = &adapter, .userdata2 = NULL }; WGPUFuture future = wgpuInstanceRequestAdapter( instance, &options, callbackInfo); // Process callbacks on this thread while (adapter == NULL) { wgpuInstanceProcessEvents(instance); } // Cleanup wgpuAdapterRelease(adapter); wgpuInstanceRelease(instance); return 0; } ``` ### Response #### Success Response Adapter is successfully acquired and its reference is held. The `onAdapterReceived` callback is invoked. #### Response Example ``` Adapter acquired successfully ``` ``` -------------------------------- ### Create WebGPU Render Pipeline with C Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This C function demonstrates how to create a WebGPU render pipeline. It defines vertex and fragment shader entry points, blend states, color targets, primitive and multisample configurations, and finally assembles these into a pipeline descriptor for creation. Dependencies include the webgpu/webgpu.h header. ```c #include WGPURenderPipeline createRenderPipeline(WGPUDevice device, WGPUShaderModule shader) { // Pipeline layout (empty for this example) WGPUPipelineLayoutDescriptor layoutDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .bindGroupLayoutCount = 0, .bindGroupLayouts = NULL }; WGPUPipelineLayout layout = wgpuDeviceCreatePipelineLayout( device, &layoutDesc); // Vertex state WGPUVertexState vertexState = { .nextInChain = NULL, .module = shader, .entryPoint = {.data = "vs_main", .length = WGPU_STRLEN}, .constantCount = 0, .constants = NULL, .bufferCount = 0, .buffers = NULL }; // Fragment state WGPUBlendState blendState = { .color = { .operation = WGPUBlendOperation_Add, .srcFactor = WGPUBlendFactor_One, .dstFactor = WGPUBlendFactor_Zero }, .alpha = { .operation = WGPUBlendOperation_Add, .srcFactor = WGPUBlendFactor_One, .dstFactor = WGPUBlendFactor_Zero } }; WGPUColorTargetState colorTarget = { .nextInChain = NULL, .format = WGPUTextureFormat_BGRA8Unorm, .blend = &blendState, .writeMask = WGPUColorWriteMask_All }; WGPUFragmentState fragmentState = { .nextInChain = NULL, .module = shader, .entryPoint = {.data = "fs_main", .length = WGPU_STRLEN}, .constantCount = 0, .constants = NULL, .targetCount = 1, .targets = &colorTarget }; // Primitive state WGPUPrimitiveState primitiveState = { .nextInChain = NULL, .topology = WGPUPrimitiveTopology_TriangleList, .stripIndexFormat = WGPUIndexFormat_Undefined, .frontFace = WGPUFrontFace_CCW, .cullMode = WGPUCullMode_None }; // Multisample state WGPUMultisampleState multisampleState = { .nextInChain = NULL, .count = 1, .mask = 0xFFFFFFFF, .alphaToCoverageEnabled = WGPU_FALSE }; // Create pipeline WGPURenderPipelineDescriptor pipelineDesc = { .nextInChain = NULL, .label = {.data = "render pipeline", .length = WGPU_STRLEN}, .layout = layout, .vertex = vertexState, .primitive = primitiveState, .depthStencil = NULL, .multisample = multisampleState, .fragment = &fragmentState }; WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline( device, &pipelineDesc); wgpuPipelineLayoutRelease(layout); return pipeline; } ``` -------------------------------- ### Buffer Mapping Operations Source: https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/BufferMapping.md Details the behavior and error conditions for various buffer mapping operations including getting mapped ranges, reading mapped ranges, and writing to mapped ranges. ```APIDOC ## Buffer Mapping Behavior ### Description This section details the behavior and error conditions for the `@ref wgpuBufferGetMappedRange`, `@ref wgpuBufferGetConstMappedRange`, `@ref wgpuBufferReadMappedRange`, and `@ref wgpuBufferWriteMappedRange` methods. ### Methods - `wgpuBufferGetMappedRange` - `wgpuBufferGetConstMappedRange` - `wgpuBufferReadMappedRange` - `wgpuBufferWriteMappedRange` ### Behavior and Error Conditions These methods fail (return `NULL` or `WGPUStatus_Error`) with `@ref ImplementationDefinedLogging` if: - There is any content-timeline error, as defined in the WebGPU specification for `getMappedRange()`, given the same buffer, offset, and size (e.g., buffer is not mapped, alignment constraints, overlaps). - **Exception**: Overlaps between *const* ranges are allowed in C *on non-Wasm targets only*. - `@ref wgpuBufferGetMappedRange` or `@ref wgpuBufferWriteMappedRange` is called, but the buffer is not mapped with `@ref WGPUMapMode_Write`. ### Additional Guarantees for `wgpuBufferGetMappedRange` and `wgpuBufferGetConstMappedRange` - These methods do not guarantee specific address values relative to other calls to `GetMappedRange`. - They guarantee that the mapped pointer will be aligned to 16 bytes if the `MapAsync` and `GetMappedRange` offsets are also aligned to 16 bytes. - Specifically: `GetMappedRange pointer` and `MapAsync offset + GetMappedRange offset` must be _congruent modulo_ `16`. - Implementations **should** attempt to provide better alignments (up to 256 bytes) if it can be done without significant runtime overhead (e.g., without new memory allocations and data copying). ``` -------------------------------- ### Asynchronous Buffer Mapping Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Maps a GPU buffer asynchronously, allowing for reading or writing data. This example shows how to request a read-only mapping and process the data once the buffer is mapped. ```APIDOC ## void mapBufferExample(WGPUDevice device, WGPUBuffer buffer) ### Description Maps a GPU buffer asynchronously for reading or writing. The `onBufferMapped` callback handles the result of the mapping operation, processing data if successful or reporting errors. ### Method N/A (C function) ### Endpoint N/A (C function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #include #include typedef struct { WGPUBuffer buffer; int ready; } MapContext; void onBufferMapped(WGPUMapAsyncStatus status, WGPUStringView message, void* userdata1, void* userdata2) { MapContext* ctx = (MapContext*)userdata1; if (status == WGPUMapAsyncStatus_Success) { printf("Buffer mapped successfully\n"); ctx->ready = 1; // Read mapped data const void* data = wgpuBufferGetConstMappedRange( ctx->buffer, 0, WGPU_WHOLE_MAP_SIZE); // Process data... const float* floatData = (const float*)data; printf("First value: %f\n", floatData[0]); // Unmap when done wgpuBufferUnmap(ctx->buffer); } else { printf("Buffer mapping failed: %.*s\n", (int)message.length, message.data); } } void mapBufferExample(WGPUDevice device, WGPUBuffer buffer) { MapContext ctx = {.buffer = buffer, .ready = 0}; WGPUBufferMapCallbackInfo callbackInfo = { .mode = WGPUCallbackMode_AllowProcessEvents, .callback = onBufferMapped, .userdata1 = &ctx, .userdata2 = NULL }; // Request mapping for reading WGPUFuture future = wgpuBufferMapAsync( buffer, WGPUMapMode_Read, 0, // offset WGPU_WHOLE_SIZE, // size callbackInfo ); // Wait for mapping (process events on instance) // In real code: wgpuInstanceProcessEvents(instance) in a loop } ``` ### Response #### Success Response (200) N/A (C function) #### Response Example N/A (C function) ``` -------------------------------- ### Surface Creation and Configuration Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This section details how to create a platform-specific surface for presentation and configure its properties like format, usage, and dimensions. ```APIDOC ## Surface Creation and Configuration ### Description Create a platform-specific surface for presentation and configure its properties. ### Method `wgpuInstanceCreateSurface` (for creation) `wgpuSurfaceConfigure` (for configuration) ### Endpoint N/A (Function calls) ### Parameters #### createWindowsSurface (Helper function for Windows) - **instance** (WGPUInstance) - The WebGPU instance. - **hwnd** (HWND) - The window handle for Windows. #### configureSurface - **surface** (WGPUSurface) - The surface to configure. - **adapter** (WGPUAdapter) - The physical adapter. - **device** (WGPUDevice) - The logical device. - **width** (int) - The width of the surface. - **height** (int) - The height of the surface. ### Request Example ```c #ifdef _WIN32 WGPUSurface surface = createWindowsSurface(instance, hwnd); configureSurface(surface, adapter, device, 800, 600); #endif ``` ### Response #### Success Response (200) N/A (Functions return `WGPUSurface` or modify existing surface) #### Response Example N/A ``` -------------------------------- ### Create WebGPU Device and Buffer with Reference Counting Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Demonstrates requesting a WebGPU device asynchronously and creating a GPU buffer. It includes proper reference counting for the device and buffer objects, as well as writing data to the buffer using mapped memory. Assumes a valid WGPUAdapter is available. ```c #include #include void onDeviceReceived(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata) { if (status == WGPURequestDeviceStatus_Success) { WGPUDevice* devicePtr = (WGPUDevice*)userdata; *devicePtr = device; wgpuDeviceAddRef(device); } } void createBufferExample(WGPUAdapter adapter) { // Request device WGPUDevice device = NULL; WGPUDeviceDescriptor deviceDesc = { .nextInChain = NULL, .label = WGPU_STRING_VIEW_INIT, .requiredFeatureCount = 0, .requiredLimits = NULL }; WGPURequestDeviceCallbackInfo callbackInfo = { .mode = WGPUCallbackMode_AllowProcessEvents, .callback = onDeviceReceived, .userdata1 = &device, .userdata2 = NULL }; wgpuAdapterRequestDevice(adapter, &deviceDesc, callbackInfo); // Process callback (simplified) // In real code, use wgpuInstanceProcessEvents() loop // Create buffer with mapped-at-creation WGPUBufferDescriptor bufferDesc = { .nextInChain = NULL, .label = (WGPUStringView){ .data = "vertex buffer", .length = WGPU_STRLEN }, .usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst, .size = 1024, .mappedAtCreation = WGPU_TRUE }; WGPUBuffer buffer = wgpuDeviceCreateBuffer(device, &bufferDesc); if (buffer != NULL) { // Write to mapped memory void* mappedData = wgpuBufferGetMappedRange( buffer, 0, WGPU_WHOLE_MAP_SIZE); float vertices[] = {0.0f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f}; memcpy(mappedData, vertices, sizeof(vertices)); wgpuBufferUnmap(buffer); // Release buffer (decrements refcount) wgpuBufferRelease(buffer); } // Releasing device also destroys it wgpuDeviceRelease(device); } ``` -------------------------------- ### Configure WebGPU Surface Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Configures a WebGPU surface with device, format, usage, dimensions, and present mode. It first retrieves surface capabilities and then sets up the configuration for rendering. ```c #include void configureSurface(WGPUSurface surface, WGPUAdapter adapter, WGPUDevice device, int width, int height) { // Get surface capabilities WGPUSurfaceCapabilities caps; wgpuSurfaceGetCapabilities(surface, adapter, &caps); // Choose format WGPUTextureFormat format = caps.formats[0]; // Configure surface WGPUSurfaceConfiguration config = { .nextInChain = NULL, .device = device, .format = format, .usage = WGPUTextureUsage_RenderAttachment, .viewFormatCount = 0, .viewFormats = NULL, .alphaMode = WGPUCompositeAlphaMode_Opaque, .width = width, .height = height, .presentMode = WGPUPresentMode_Fifo }; wgpuSurfaceConfigure(surface, &config); // Free capabilities wgpuSurfaceCapabilitiesFreeMembers(caps); } ``` -------------------------------- ### Create Windows Surface for WebGPU Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Creates a platform-specific surface for presentation on Windows using the HWND. It requires a WGPUInstance and an HWND. The function returns a WGPUSurface object. ```c #include #ifdef _WIN32 #include WGPUSurface createWindowsSurface(WGPUInstance instance, HWND hwnd) { WGPUSurfaceSourceWindowsHWND surfaceSource = { .chain = { .next = NULL, .sType = WGPUSType_SurfaceSourceWindowsHWND }, .hinstance = GetModuleHandle(NULL), .hwnd = hwnd }; WGPUSurfaceDescriptor surfaceDesc = { .nextInChain = (WGPUChainedStruct*)&surfaceSource, .label = {.data = "main window", .length = WGPU_STRLEN} }; return wgpuInstanceCreateSurface(instance, &surfaceDesc); } #endif ``` -------------------------------- ### Create WebGPU Shader Module with WGSL Source Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Demonstrates creating a WebGPU shader module from WGSL source code using the struct chaining mechanism. This allows passing WGSL as an extension to the base shader module descriptor. Requires a valid WGPUDevice. ```c #include WGPUShaderModule createShaderModule(WGPUDevice device) { const char* shaderCode = "@vertex\n" "fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4 {\n" " var pos = array, 3>(\n" " vec2(0.0, 0.5),\n" " vec2(-0.5, -0.5),\n" " vec2(0.5, -0.5)\n" " );\n" " return vec4(pos[idx], 0.0, 1.0);\n" "}\n" "@fragment\n" "fn fs_main() -> @location(0) vec4 {\n" " return vec4(1.0, 0.0, 0.0, 1.0);\n" "}\n"; // Extension struct for WGSL source WGPUShaderSourceWGSL wgslSource = { .chain = { .next = NULL, .sType = WGPUSType_ShaderSourceWGSL }, .code = { .data = shaderCode, .length = WGPU_STRLEN // null-terminated } }; // Base descriptor with chained extension WGPUShaderModuleDescriptor shaderDesc = { .nextInChain = (WGPUChainedStruct*)&wgslSource, .label = { .data = "triangle shader", .length = WGPU_STRLEN } }; WGPUShaderModule shader = wgpuDeviceCreateShaderModule( device, &shaderDesc); // shader has one application-owned reference return shader; } ``` -------------------------------- ### Error Handling with Device Lost Callback Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Demonstrates how to set up a callback function to asynchronously handle device loss events, including reasons and messages. ```APIDOC ## Error Handling with Device Lost Callback ### Description Handle device loss events asynchronously by registering a callback function. ### Method `wgpuDeviceSetDeviceLostCallback` ### Endpoint N/A (Function call) ### Parameters #### setupDeviceLostCallback - **device** (WGPUDevice) - The logical device for which to set the callback. #### onDeviceLost (Callback function) - **device** (WGPUDevice const *) - Pointer to the device (may be NULL if released). - **reason** (WGPUDeviceLostReason) - The reason for device loss. - **message** (WGPUStringView) - A message detailing the loss. - **userdata1** (void*) - User-defined data. - **userdata2** (void*) - User-defined data. ### Request Example ```c WGPUDeviceLostCallbackInfo callbackInfo = { .mode = WGPUCallbackMode_AllowSpontaneous, .callback = onDeviceLost, .userdata1 = NULL, .userdata2 = NULL }; wgpuDeviceSetDeviceLostCallback(device, callbackInfo); ``` ### Response #### Success Response (200) N/A (Function registers a callback) #### Response Example N/A ``` -------------------------------- ### WebGPU Timestamp Query for Performance Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Demonstrates creating and using timestamp queries for GPU profiling. It involves creating a query set and a buffer to store results, writing timestamps at points of interest in the command buffer, resolving queries, and submitting for later analysis. ```c #include void timestampExample(WGPUDevice device) { // Create query set for timestamps WGPUQuerySetDescriptor querySetDesc = { .nextInChain = NULL, .label = {.data = "timestamps", .length = WGPU_STRLEN}, .type = WGPUQueryType_Timestamp, .count = 2 // start and end }; WGPUQuerySet querySet = wgpuDeviceCreateQuerySet( device, &querySetDesc); // Create buffer for query results WGPUBufferDescriptor bufferDesc = { .nextInChain = NULL, .label = {.data = "query buffer", .length = WGPU_STRLEN}, .usage = WGPUBufferUsage_QueryResolve | WGPUBufferUsage_CopySrc, .size = 2 * sizeof(uint64_t), .mappedAtCreation = WGPU_FALSE }; WGPUBuffer queryBuffer = wgpuDeviceCreateBuffer(device, &bufferDesc); // In command encoder WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder( device, NULL); // Write start timestamp wgpuCommandEncoderWriteTimestamp(encoder, querySet, 0); // ... GPU work here ... // Write end timestamp wgpuCommandEncoderWriteTimestamp(encoder, querySet, 1); // Resolve queries to buffer wgpuCommandEncoderResolveQuerySet( encoder, querySet, 0, 2, queryBuffer, 0); WGPUCommandBuffer cmdBuffer = wgpuCommandEncoderFinish(encoder, NULL); // Submit WGPUQueue queue = wgpuDeviceGetQueue(device); wgpuQueueSubmit(queue, 1, &cmdBuffer); // Later: map queryBuffer to read timestamps // Cleanup wgpuCommandEncoderRelease(encoder); wgpuCommandBufferRelease(cmdBuffer); wgpuQuerySetRelease(querySet); wgpuBufferRelease(queryBuffer); wgpuQueueRelease(queue); } ``` -------------------------------- ### Code Generation from YAML Specification Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Describes the process of generating the `webgpu.h` header file from a YAML specification using a Go-based generator tool. This includes validation, parsing, transformation, and template-based C header generation. ```APIDOC ## Code Generation from YAML Specification ### Description This section outlines the command and process for generating the `webgpu.h` C header file from a YAML specification using a Go generator. It details the steps involved, from schema validation to final header output. ### Method Command Line Tool (`make gen`) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash # Validate schema and regenerate header from YAML make gen # This runs: # go run ./gen -schema schema.json \ # -yaml webgpu.yml \ # -out-json webgpu.json \ # -out-header webgpu.h # The generator performs: # 1. JSON schema validation of webgpu.yml # 2. Detection of duplicate definitions # 3. Parsing YAML into Go structures # 4. Sorting and transformation of API elements # 5. Template-based C header generation # 6. JSON format output ``` ### Response #### Success Response (200) Generates `webgpu.h`, `webgpu.json` files. #### Response Example ``` // Contents of webgpu.h will be generated C header code. // Contents of webgpu.json will be JSON output of API elements. ``` ``` -------------------------------- ### Generate WebGPU Headers from YAML Specs Source: https://github.com/webgpu-native/webgpu-headers/blob/main/gen/README.md This command demonstrates how to use the generator to create webgpu.h and implementation-specific headers from YAML files. It requires specifying the schema, input YAMLs, and output header files in sequence. The order of YAML files is important, with the core webgpu.yml expected first. ```shell > go run ./gen -schema schema.json -yaml webgpu.yml -header webgpu.h -yaml wgpu.yml -header wgpu.h ``` -------------------------------- ### Command Encoding and Queue Submission Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt Encodes render commands and submits them to the GPU queue for execution. This involves setting up render targets, command encoders, render passes, and finally submitting the encoded commands. ```APIDOC ## void renderFrame(WGPUDevice device, WGPUSurface surface, WGPURenderPipeline pipeline) ### Description Encodes render commands and submits them to the GPU queue for execution. This function demonstrates the process of acquiring a surface texture, creating views, command encoders, and render passes, recording draw commands, and submitting the command buffer for rendering. ### Method N/A (C function) ### Endpoint N/A (C function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #include void renderFrame(WGPUDevice device, WGPUSurface surface, WGPURenderPipeline pipeline) { // ... implementation details as provided in the source code ... } ``` ### Response #### Success Response (200) N/A (C function) #### Response Example N/A (C function) ``` -------------------------------- ### Go Generator for WebGPU C Headers Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This Go program parses WebGPU specification YAML files, validates them against a JSON schema, and generates C header files. It uses command-line flags for input and output paths and handles YAML unmarshalling and API transformation. ```go package main import ( "encoding/json" "flag" "github.com/goccy/go-yaml" ) func main() { // Parse command-line flags flag.StringVar(&schemaPath, "schema", "", "path of the json schema") flag.Var(&yamlPaths, "yaml", "path of the yaml spec") flag.Var(&outHeaderPaths, "out-header", "output path of the header") flag.Parse() // Validate YAML against JSON schema if err := ValidateYamls(schemaPath, yamlPaths); err != nil { panic(err) } // Parse YAML src, _ := os.ReadFile(yamlPath) var yml Yml yaml.Unmarshal(src, &yml) // Sort and transform API definitions SortAndTransform(&yml) // Generate header using embedded template GenerateCHeader(&yml, outputPath) } ``` -------------------------------- ### WebGPU YAML Configuration Structure Source: https://context7.com/webgpu-native/webgpu-headers/llms.txt This section describes the structure of the webgpu.yml file, which defines constants, objects with methods, and enums for WebGPU. It outlines naming conventions and data types used in the configuration. ```yaml name: webgpu enum_prefix: 0x0000 constants: - name: strlen value: usize_max doc: | Sentinel value used in WGPUStringView to indicate that the pointer is to a null-terminated string. objects: - name: buffer methods: - name: map_async returns: future args: - name: mode type: map_mode - name: offset type: uint64_t - name: size type: uint64_t - name: callback_info type: buffer_map_callback_info enums: - name: buffer_usage entries: - name: map_read value: 0x00000001 - name: map_write value: 0x00000002 - name: copy_src value: 0x00000004 ``` -------------------------------- ### WebGPU Extension Naming Conventions Source: https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/Extensions.md Illustrates the naming conventions for various types of extensions in webgpu.h, such as new functions, objects, enums, bitflag types, and callbacks. These conventions help in organizing and identifying implementation-specific extensions. ```text wgpuPrefixNewFunction WGPUPrefixNewObject wgpuPrefixNewObjectNewMethod wgpuOldObjectPrefixNewMethod WGPUPrefixNewEnum WGPUPrefixNewEnum_NewValue WGPUOldEnum_PrefixNewValue WGPUPrefixNewStruct WGPUPrefixNewBitflagType WGPUPrefixNewBitflagType_NewValue WGPUOldBitflagType_PrefixNewValue WGPUPrefixNewCallback WGPU_PREFIX_NEW_CONSTANT ``` -------------------------------- ### Configure WGPUSurface in C Source: https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/Surfaces.md This C code snippet demonstrates how to set up the WGPUSurfaceConfiguration structure with necessary parameters like device, format, dimensions, usage, present mode, and alpha mode, followed by calling wgpuSurfaceConfigure to apply the settings. It requires a valid WGPUDevice and pre-determined format and present mode. ```c WGPUSurfaceConfiguration config = { nextInChain = nullptr, device = myDevice, format = preferredFormat, width = 640, // Depending on the window size. height = 480, usage = WGPUTextureUsage_RenderAttachment, presentMode = supportsMailbox ? WGPUPresentMode_Mailbox : WGPUPresentMode_Fifo, alphaMode = WGPUCompositeAlphaMode_Auto, }; wgpuSurfaceConfigure(mySurface, &config); ``` -------------------------------- ### Runtime Extension Detection in WebGPU Source: https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/Extensions.md Explains how applications can detect the support for unknown webgpu.h implementations at runtime. This includes dynamic loading of functions, checking for the presence of methods that create new objects, and verifying the existence of methods that accept new struct types. ```text - New functions/methods may be runtime-detected by loading them dynamically, and checking whether loading succeeds. (@ref wgpuGetProcAddress() returns `NULL` for unknown function names.) - New objects may be detected by the presence of the methods that create them. - New (root) structs, enum/bitflag types, and callback types are always supported if the methods that accept them exist. ```