Created
July 28, 2023 03:34
-
-
Save ssteinbach/d27d82e08f852361a35628ee5443b0b4 to your computer and use it in GitHub Desktop.
Automatic ZGui UI From Struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// function for automatically building an imgui (via zgui) UI based | |
/// on struct fields. Really useful when you're moving quickly and | |
/// have a debug flags/fields struct | |
pub fn draw_zgui_ui( | |
for_thing: anytype | |
) !bool | |
{ | |
var buf:[1024:0]u8 = undefined; | |
@memset(&buf, 0); | |
switch (@typeInfo(@TypeOf(for_thing.*))) | |
{ | |
.Struct => |info| | |
{ | |
inline for (info.fields) | |
|f| | |
{ | |
const label = try std.fmt.bufPrintZ( | |
&buf, | |
"{s}", | |
.{ f.name } | |
); | |
switch (@typeInfo((f.type))) | |
{ | |
.Float => { | |
// skipping f64 | |
if (f.type == f64) { | |
continue; | |
} else { | |
_ = zgui.dragFloat( | |
label, | |
.{ .v = & @field(for_thing, f.name) } | |
); | |
} | |
}, | |
.Bool => { | |
_ = zgui.checkbox( | |
label, | |
.{ .v = & @field(for_thing, f.name) } | |
); | |
}, | |
.Enum => { | |
_ = zgui.combo_from_enum(label, &@field(for_thing, f.name)); | |
}, | |
.Vector => |v| { | |
// @TODO: move this into a function in zgui | |
_ = switch (v.len) { | |
1 => zgui.dragFloat(label, .{ .v = @as(*[1]f32, & @field(for_thing, f.name)) }), | |
2 => zgui.dragFloat2(label, .{ .v = @ptrCast(*[2]f32, & @field(for_thing, f.name)) }), | |
3 => zgui.dragFloat3(label, .{ .v = @ptrCast(*[3]f32, & @field(for_thing, f.name)) }), | |
4 => zgui.dragFloat4(label, .{ .v = @ptrCast(*[4]f32, & @field(for_thing, f.name)) }), | |
else => @compileError("No support for vector sizes greater than 4"), | |
}; | |
}, | |
.Struct => { | |
if (zgui.treeNodeFlags(label, .{.default_open = true})) | |
{ | |
defer zgui.treePop(); | |
_ = try draw_zgui_ui(&@field(for_thing, f.name)); | |
} | |
}, | |
else => { | |
@compileError( | |
std.fmt.comptimePrint( | |
"potato No way to build a ui for field named:" | |
++ " {s} of type: {any}\n", | |
.{f.name, @typeInfo((@TypeOf(f)))}) | |
); | |
} | |
} | |
} | |
}, | |
else => { | |
@compileError( | |
std.fmt.comptimePrint("potato No way to build a ui for: {any}\n", | |
.{@typeInfo((@TypeOf(for_thing)))}) | |
); | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment