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(); defer vbo.destroy();
try vao.bind(); try vao.bind();
try vbo.bind(c.GL_ARRAY_BUFFER); 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( c.glVertexAttribPointer(
0, 0,

View File

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