adapter.zig (3307B)
1 const std = @import("std"); 2 3 const c = @import("c.zig").c; 4 const CallbackMode = @import("common.zig").CallbackMode; 5 const ChainedStruct = @import("common.zig").ChainedStruct; 6 const Device = @import("device.zig").Device; 7 const StringView = @import("common.zig").StringView; 8 9 const RequestDeviceStatus = enum(u32) { 10 success = 0x00000001, 11 instance_dropped = 0x00000002, 12 @"error" = 0x00000003, 13 unknown = 0x00000004, 14 }; 15 16 const RequestDeviceError = error{ 17 InstanceDropped, 18 Error, 19 Unknown, 20 }; 21 22 const RequestDeviceCallback = fn ( 23 status: RequestDeviceStatus, 24 device: ?*Device, 25 message: StringView, 26 userdata1: ?*anyopaque, 27 userdata2: ?*anyopaque, 28 ) callconv(.C) void; 29 30 const RequestDeviceCallbackInfo = extern struct { 31 next: ?*ChainedStruct = null, 32 mode: CallbackMode, 33 callback: *const RequestDeviceCallback, 34 userdata1: ?*anyopaque, 35 userdata2: ?*anyopaque, 36 }; 37 38 pub const Adapter = opaque { 39 pub fn release(adapter: *Adapter) void { 40 c.wgpuAdapterRelease(@ptrCast(adapter)); 41 } 42 43 pub fn requestDevice( 44 adapter: *Adapter, 45 descriptor: *const Device.Descriptor, 46 ) !*Device { 47 const RequestDeviceResponse = struct { 48 complete: bool = false, 49 status: RequestDeviceStatus, 50 device: ?*Device, 51 52 pub fn callback( 53 status: RequestDeviceStatus, 54 device: ?*Device, 55 message: StringView, 56 userdata1: ?*anyopaque, 57 userdata2: ?*anyopaque, 58 ) callconv(.C) void { 59 _ = userdata2; 60 const self: *@This() = @alignCast(@ptrCast(userdata1)); 61 switch (status) { 62 .success => {}, 63 else => { 64 std.log.err( 65 "failed to request device - {s}", 66 .{message.toSlice()}, 67 ); 68 }, 69 } 70 self.* = .{ 71 .status = status, 72 .device = device, 73 .complete = true, 74 }; 75 } 76 }; 77 78 var response: RequestDeviceResponse = undefined; 79 const callback = RequestDeviceCallbackInfo{ 80 .next = null, 81 .mode = .allow_spontaneous, 82 .callback = &RequestDeviceResponse.callback, 83 .userdata1 = &response, 84 .userdata2 = null, 85 }; 86 _ = c.wgpuAdapterRequestDevice( 87 @ptrCast(adapter), 88 @ptrCast(descriptor), 89 @as(*const c.WGPURequestDeviceCallbackInfo, @ptrCast(&callback)).*, 90 ); 91 while (!response.complete) { 92 std.time.sleep(std.time.ns_per_s * 0.1); 93 } 94 switch (response.status) { 95 .success => return response.device.?, 96 .instance_dropped => { 97 return RequestDeviceError.InstanceDropped; 98 }, 99 .@"error" => { 100 return RequestDeviceError.Error; 101 }, 102 .unknown => { 103 return RequestDeviceError.Unknown; 104 }, 105 } 106 } 107 108 // enumerateFeatures(...) 109 // getInfo(...) 110 // getLimits(...) 111 // hasFeature(...) 112 // reference(...) 113 };