opengl: more generic setData for buffer

This commit is contained in:
Mitchell Hashimoto
2022-04-01 17:52:36 -07:00
parent f1cffea944
commit 63673287f6
2 changed files with 30 additions and 15 deletions

View File

@ -56,7 +56,7 @@ pub fn main() !void {
defer vbo.destroy();
try vao.bind();
try vbo.bind(c.GL_ARRAY_BUFFER);
try vbo.setData(c.GL_ARRAY_BUFFER, vertices[0..], c.GL_STATIC_DRAW);
try vbo.setData(c.GL_ARRAY_BUFFER, vertices, c.GL_STATIC_DRAW);
c.glVertexAttribPointer(
0,

View File

@ -1,5 +1,6 @@
const Buffer = @This();
const std = @import("std");
const c = @import("c.zig");
const errors = @import("errors.zig");
@ -25,29 +26,43 @@ pub inline fn bind(v: Buffer, target: c.GLenum) !void {
pub inline fn setData(
v: Buffer,
target: c.GLenum,
data: []const f32,
data: anytype,
usage: c.GLenum,
) !void {
// Maybe one day in debug mode we can validate that this buffer
// is currently bound.
_ = v;
// Determine the per-element size. This is all comptime-computed.
const dataInfo = @typeInfo(@TypeOf(data));
const size: usize = switch (dataInfo) {
.Pointer => |ptr| switch (ptr.size) {
.Slice => @sizeOf(ptr.child),
else => unreachable,
// Determine the size and pointer to the given data.
const info: struct {
size: isize,
ptr: *const anyopaque,
} = switch (@typeInfo(@TypeOf(data))) {
.Array => |ary| .{
.size = @sizeOf(ary.child) * ary.len,
.ptr = &data,
},
.Pointer => |ptr| switch (ptr.size) {
.One => .{
.size = @sizeOf(ptr.child) * data.len,
.ptr = data,
},
.Slice => .{
.size = @sizeOf(ptr.child) * data.len,
.ptr = data.ptr,
},
else => {
std.log.err("invalid buffer data pointer size: {}", .{ptr.size});
unreachable;
},
},
else => {
std.log.err("invalid buffer data type: {s}", .{@tagName(@typeInfo(@TypeOf(data)))});
unreachable;
},
else => unreachable,
};
c.glBufferData(
target,
@intCast(isize, size * data.len),
data.ptr,
usage,
);
c.glBufferData(target, info.size, info.ptr, usage);
try errors.getError();
}