TextureRenderer.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package me.hammerle.snuviengine.api;
  2. import java.nio.FloatBuffer;
  3. import org.lwjgl.BufferUtils;
  4. import static org.lwjgl.opengl.GL11.*;
  5. import static org.lwjgl.opengl.GL15.*;
  6. import static org.lwjgl.opengl.GL20.*;
  7. import static org.lwjgl.opengl.GL30.*;
  8. public class TextureRenderer
  9. {
  10. private int vao;
  11. private int vbo;
  12. private FloatBuffer buffer = BufferUtils.createFloatBuffer(12);
  13. private boolean built = false;
  14. public TextureRenderer()
  15. {
  16. Shader.addTask(() ->
  17. {
  18. vao = glGenVertexArrays();
  19. vbo = glGenBuffers();
  20. GLHelper.glBindVertexArray(vao);
  21. GLHelper.glBindBuffer(vbo);
  22. glEnableVertexAttribArray(0);
  23. glVertexAttribPointer(0, 2, GL_FLOAT, false, 16, 0);
  24. glEnableVertexAttribArray(1);
  25. glVertexAttribPointer(1, 2, GL_FLOAT, false, 16, 8);
  26. });
  27. }
  28. 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)
  29. {
  30. if(buffer.position() + 12 > buffer.capacity())
  31. {
  32. FloatBuffer newBuffer = BufferUtils.createFloatBuffer(buffer.capacity() * 2);
  33. buffer.flip();
  34. newBuffer.put(buffer);
  35. buffer = newBuffer;
  36. }
  37. buffer.put(x1);
  38. buffer.put(y1);
  39. buffer.put(tx1);
  40. buffer.put(ty1);
  41. buffer.put(x2);
  42. buffer.put(y2);
  43. buffer.put(tx2);
  44. buffer.put(ty2);
  45. buffer.put(x3);
  46. buffer.put(y3);
  47. buffer.put(tx3);
  48. buffer.put(ty3);
  49. }
  50. public void addRectangle(float minX, float minY, float maxX, float maxY, float tMinX, float tMinY, float tMaxX, float tMaxY)
  51. {
  52. addTriangle(minX, maxY, minX, minY, maxX, maxY, tMinX, tMaxY, tMinX, tMinY, tMaxX, tMaxY);
  53. addTriangle(maxX, maxY, minX, minY, maxX, minY, tMaxX, tMaxY, tMinX, tMinY, tMaxX, tMinY);
  54. }
  55. public void build()
  56. {
  57. if(!Shader.initDone || buffer.position() == 0)
  58. {
  59. throw new ShaderException("build called too early");
  60. }
  61. buffer.flip();
  62. GLHelper.glBindVertexArray(vao);
  63. GLHelper.glBindBuffer(vbo);
  64. glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);
  65. buffer.limit(buffer.capacity());
  66. built = true;
  67. }
  68. public void draw()
  69. {
  70. if(!built)
  71. {
  72. throw new ShaderException("build must be called before drawing");
  73. }
  74. GLHelper.glBindVertexArray(vao);
  75. GLHelper.glBindBuffer(vbo);
  76. glDrawArrays(GL_TRIANGLES, 0, buffer.limit() / 4);
  77. }
  78. public void delete()
  79. {
  80. buffer = null;
  81. glDeleteVertexArrays(vao);
  82. glDeleteBuffers(vbo);
  83. vao = -1;
  84. vbo = -1;
  85. built = false;
  86. }
  87. }