package me.hammerle.snuviengine.api; import java.nio.FloatBuffer; import org.lwjgl.BufferUtils; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; public class TextureRenderer { private int vao; private int vbo; private int triangles = 0; private FloatBuffer buffer; private boolean built = false; public TextureRenderer(int triangles) { buffer = BufferUtils.createFloatBuffer(triangles * 12); Shader.addTask(() -> { vao = glGenVertexArrays(); vbo = glGenBuffers(); GLHelper.glBindVertexArray(vao); GLHelper.glBindBuffer(vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, false, 16, 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, false, 16, 8); }); } public void addTriangle(float x1, float y1, float x2, float y2, float x3, float y3, float tx1, float ty1, float tx2, float ty2, float tx3, float ty3) { if(buffer.position() + 12 > buffer.capacity()) { FloatBuffer newBuffer = BufferUtils.createFloatBuffer(buffer.capacity() * 2); buffer.flip(); newBuffer.put(buffer); buffer = newBuffer; } buffer.put(x1); buffer.put(y1); buffer.put(tx1); buffer.put(ty1); buffer.put(x2); buffer.put(y2); buffer.put(tx2); buffer.put(ty2); buffer.put(x3); buffer.put(y3); buffer.put(tx3); buffer.put(ty3); triangles++; } public void addRectangle(float minX, float minY, float maxX, float maxY, float tMinX, float tMinY, float tMaxX, float tMaxY) { addTriangle(minX, maxY, minX, minY, maxX, maxY, tMinX, tMaxY, tMinX, tMinY, tMaxX, tMaxY); addTriangle(maxX, maxY, minX, minY, maxX, minY, tMaxX, tMaxY, tMinX, tMinY, tMaxX, tMinY); } public boolean isBuilt() { return built; } public void build() { if(!Shader.initDone) { throw new ShaderException("build called too early"); } if(triangles == 0 || built) { return; } buffer.flip(); GLHelper.glBindVertexArray(vao); GLHelper.glBindBuffer(vbo); glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW); buffer.limit(buffer.capacity()); built = true; } public void clear() { triangles = 0; built = false; } public void draw() { if(triangles == 0) { return; } if(!built) { throw new ShaderException("build must be called before drawing"); } GLHelper.glBindVertexArray(vao); GLHelper.glBindBuffer(vbo); glDrawArrays(GL_TRIANGLES, 0, buffer.limit() / 4); } public void delete() { buffer = null; glDeleteVertexArrays(vao); glDeleteBuffers(vbo); vao = -1; vbo = -1; built = false; } }