const std = @import("std"); const sdl = @import("sdl2"); const gl = @import("zgl"); const Self = @This(); window: sdl.Window, context: sdl.gl.Context, color_loc: u32, buffer: gl.Buffer, color: [4]f32, pub fn init() !Self { try sdl.init(.{ .video = true, .audio = true, .events = true }); // Set OpenGL version try sdl.gl.setAttribute(.{ .context_major_version = 3 }); try sdl.gl.setAttribute(.{ .context_minor_version = 3 }); const window = try sdl.createWindow( "USG", .{ .centered = {} }, .{ .centered = {} }, 1280, 720, .{ .opengl = true, .shown = true } ); const ctx = try sdl.gl.createContext(window); var color_loc: u32 = undefined; const program = gl.Program.create(); { const vs = gl.Shader.create(.vertex); defer vs.delete(); vs.source(1, &.{@embedFile("shaders/vector.vs")}); vs.compile(); const fs = gl.Shader.create(.fragment); defer fs.delete(); fs.source(1, &.{@embedFile("shaders/fragment.fs")}); fs.compile(); program.attach(vs); defer program.detach(vs); program.attach(fs); defer program.detach(fs); program.link(); color_loc = program.uniformLocation("color").?; } program.use(); var vertex_array = gl.VertexArray.gen(); vertex_array.bind(); const buf = gl.Buffer.gen(); buf.bind(.array_buffer); gl.clearColor(0.91, 0.97, 1.00, 1.00); return Self{ .window = window, .context = ctx, .color_loc = color_loc, .buffer = buf, .color = .{0,0,0,0} }; } pub fn render(self: Self) void { sdl.gl.swapWindow(self.window); gl.clear(.{ .color = true }); } pub fn deinit(self: Self) void { sdl.quit(); self.window.destroy(); sdl.gl.deleteContext(self.context); } pub fn setColor(self: *Self, r: u8, g: u32, b: u32, a: u32) void { self.*.color = .{ @intToFloat(f32, r)/255.0, @intToFloat(f32, g)/255.0, @intToFloat(f32, b)/255.0, @intToFloat(f32, a)/255.0, }; } pub fn drawRectangle(self: *Self, x: u32, y: u32, w: u32, h: u32) void { var wsize = self.window.getSize(); var xunit = 2 / @intToFloat(f32, wsize.width); var yunit = 2 / @intToFloat(f32, wsize.height); var xf = @intToFloat(f32, x) * xunit - 1; var yf = 1 - @intToFloat(f32, y) * yunit; var wf = @intToFloat(f32, w) * xunit; var hf = @intToFloat(f32, h) * yunit; gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 3, .float, false, 0, 0); std.debug.print("{} {}\n", .{ xf, yf }); const vertex_buffer = [_]f32{ xf, yf, 0.0, xf + wf, yf, 0.0, xf, yf + hf, 0.0, }; self.buffer.data(f32, &vertex_buffer, .static_draw); gl.uniform4fv(self.color_loc, &.{ self.color }); gl.drawArrays(.triangles, 0, 3); gl.disableVertexAttribArray(0); _ = xf; _ = yf; }