From 344d6e68bee7f286f7c4b4b25518367c595b4619 Mon Sep 17 00:00:00 2001 From: sanine Date: Mon, 13 Mar 2023 22:42:40 -0500 Subject: add shader.lua --- honey/shader.lua | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 honey/shader.lua (limited to 'honey/shader.lua') diff --git a/honey/shader.lua b/honey/shader.lua new file mode 100644 index 0000000..82d7e8a --- /dev/null +++ b/honey/shader.lua @@ -0,0 +1,68 @@ +local gl = honey.gl + +local module = {} +setmetatable(module, {__index=_G}) +setfenv(1, module) + + +Shader = {} +Shader.__index = Shader + +local function compileShader(source, type) + local shader = gl.CreateShader(type) + gl.ShaderSource(shader, source) + gl.CompileShader(shader) + return shader +end + +function Shader.new(_, sources) + local self = {} + self.locations = {} + self.links = {} + + local shaders = {} + if sources.vertex then + table.insert(shaders, compileShader(sources.vertex, gl.VERTEX_SHADER)) + end + if sources.fragment then + table.insert(shaders, compileShader(sources.fragment, gl.FRAGMENT_SHADER)) + end + + self.program = gl.CreateProgram() + for _, shader in ipairs(shaders) do + gl.AttachShader(self.program, shader) + end + gl.LinkProgram(self.program) + for _, shader in ipairs(shaders) do + gl.DeleteShader(shader) + end + + setmetatable(self, Shader) + return self +end +setmetatable(Shader, {__call=Shader.new}) + + +function Shader.getLocation(self, name) + if self.locations[name] then + return self.locations[name] + end + + local location = gl.GetUniformLocation(self.program, name) + self.locations[name] = location + return location +end + + +function Shader.use(self) + gl.UseProgram(self.program) +end + + +function Shader.setMatrix(self, name, matrix) + local location = self:getLocation(name) + gl.UniformMatrix4fv(location, false, matrix.data) +end + + +return module.Shader -- cgit v1.2.1